| 1 | // Copyright 2014 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Stringer is a tool to automate the creation of methods that satisfy the fmt.Stringer |
| 6 | // interface. Given the name of a (signed or unsigned) integer type T that has constants |
| 7 | // defined, stringer will create a new self-contained Go source file implementing |
| 8 | // |
| 9 | // func (t T) String() string |
| 10 | // |
| 11 | // The file is created in the same package and directory as the package that defines T. |
| 12 | // It has helpful defaults designed for use with go generate. |
| 13 | // |
| 14 | // Stringer works best with constants that are consecutive values such as created using iota, |
| 15 | // but creates good code regardless. In the future it might also provide custom support for |
| 16 | // constant sets that are bit patterns. |
| 17 | // |
| 18 | // For example, given this snippet, |
| 19 | // |
| 20 | // package painkiller |
| 21 | // |
| 22 | // type Pill int |
| 23 | // |
| 24 | // const ( |
| 25 | // Placebo Pill = iota |
| 26 | // Aspirin |
| 27 | // Ibuprofen |
| 28 | // Paracetamol |
| 29 | // Acetaminophen = Paracetamol |
| 30 | // ) |
| 31 | // |
| 32 | // running this command |
| 33 | // |
| 34 | // stringer -type=Pill |
| 35 | // |
| 36 | // in the same directory will create the file pill_string.go, in package painkiller, |
| 37 | // containing a definition of |
| 38 | // |
| 39 | // func (Pill) String() string |
| 40 | // |
| 41 | // That method will translate the value of a Pill constant to the string representation |
| 42 | // of the respective constant name, so that the call fmt.Print(painkiller.Aspirin) will |
| 43 | // print the string "Aspirin". |
| 44 | // |
| 45 | // Typically this process would be run using go generate, like this: |
| 46 | // |
| 47 | // //go:generate stringer -type=Pill |
| 48 | // |
| 49 | // If multiple constants have the same value, the lexically first matching name will |
| 50 | // be used (in the example, Acetaminophen will print as "Paracetamol"). |
| 51 | // |
| 52 | // With no arguments, it processes the package in the current directory. |
| 53 | // Otherwise, the arguments must name a single directory holding a Go package |
| 54 | // or a set of Go source files that represent a single Go package. |
| 55 | // |
| 56 | // The -type flag accepts a comma-separated list of types so a single run can |
| 57 | // generate methods for multiple types. The default output file is t_string.go, |
| 58 | // where t is the lower-cased name of the first type listed. It can be overridden |
| 59 | // with the -output flag. |
| 60 | // |
| 61 | // Types can also be declared in tests, in which case type declarations in the |
| 62 | // non-test package or its test variant are preferred over types defined in the |
| 63 | // package with suffix "_test". |
| 64 | // The default output file for type declarations in tests is t_string_test.go with t picked as above. |
| 65 | // |
| 66 | // The -linecomment flag tells stringer to generate the text of any line comment, trimmed |
| 67 | // of leading spaces, instead of the constant name. For instance, if the constants above had a |
| 68 | // Pill prefix, one could write |
| 69 | // |
| 70 | // PillAspirin // Aspirin |
| 71 | // |
| 72 | // to suppress it in the output. |
| 73 | // |
| 74 | // The -trimprefix flag specifies a prefix to remove from the constant names |
| 75 | // when generating the string representations. For instance, -trimprefix=Pill |
| 76 | // would be an alternative way to ensure that PillAspirin.String() == "Aspirin". |
| 77 | package main // import "golang.org/x/tools/cmd/stringer" |
| 78 | |
| 79 | import ( |
| 80 | "bytes" |
| 81 | "flag" |
| 82 | "fmt" |
| 83 | "go/ast" |
| 84 | "go/constant" |
| 85 | "go/format" |
| 86 | "go/token" |
| 87 | "go/types" |
| 88 | "log" |
| 89 | "os" |
| 90 | "path/filepath" |
| 91 | "sort" |
| 92 | "strings" |
| 93 | |
| 94 | "golang.org/x/tools/go/packages" |
| 95 | ) |
| 96 | |
| 97 | var ( |
| 98 | typeNames = flag.String("type", "", "comma-separated list of type names; must be set") |
| 99 | output = flag.String("output", "", "output file name; default srcdir/<type>_string.go") |
| 100 | trimprefix = flag.String("trimprefix", "", "trim the `prefix` from the generated constant names") |
| 101 | linecomment = flag.Bool("linecomment", false, "use line comment text as printed text when present") |
| 102 | buildTags = flag.String("tags", "", "comma-separated list of build tags to apply") |
| 103 | ) |
| 104 | |
| 105 | // Usage is a replacement usage function for the flags package. |
| 106 | func Usage() { |
| 107 | fmt.Fprintf(os.Stderr, "Usage of stringer:\n") |
| 108 | fmt.Fprintf(os.Stderr, "\tstringer [flags] -type T [directory]\n") |
| 109 | fmt.Fprintf(os.Stderr, "\tstringer [flags] -type T files... # Must be a single package\n") |
| 110 | fmt.Fprintf(os.Stderr, "For more information, see:\n") |
| 111 | fmt.Fprintf(os.Stderr, "\thttps://pkg.go.dev/golang.org/x/tools/cmd/stringer\n") |
| 112 | fmt.Fprintf(os.Stderr, "Flags:\n") |
| 113 | flag.PrintDefaults() |
| 114 | } |
| 115 | |
| 116 | func main() { |
| 117 | log.SetFlags(0) |
| 118 | log.SetPrefix("stringer: ") |
| 119 | flag.Usage = Usage |
| 120 | flag.Parse() |
| 121 | if len(*typeNames) == 0 { |
| 122 | flag.Usage() |
| 123 | os.Exit(2) |
| 124 | } |
| 125 | types := strings.Split(*typeNames, ",") |
| 126 | var tags []string |
| 127 | if len(*buildTags) > 0 { |
| 128 | tags = strings.Split(*buildTags, ",") |
| 129 | } |
| 130 | |
| 131 | // We accept either one directory or a list of files. Which do we have? |
| 132 | args := flag.Args() |
| 133 | if len(args) == 0 { |
| 134 | // Default: process whole package in current directory. |
| 135 | args = []string{"."} |
| 136 | } |
| 137 | |
| 138 | // Parse the package once. |
| 139 | var dir string |
| 140 | // TODO(suzmue): accept other patterns for packages (directories, list of files, import paths, etc). |
| 141 | if len(args) == 1 && isDirectory(args[0]) { |
| 142 | dir = args[0] |
| 143 | } else { |
| 144 | if len(tags) != 0 { |
| 145 | log.Fatal("-tags option applies only to directories, not when files are specified") |
| 146 | } |
| 147 | dir = filepath.Dir(args[0]) |
| 148 | } |
| 149 | |
| 150 | // For each type, generate code in the first package where the type is declared. |
| 151 | // The order of packages is as follows: |
| 152 | // package x |
| 153 | // package x compiled for tests |
| 154 | // package x_test |
| 155 | // |
| 156 | // Each package pass could result in a separate generated file. |
| 157 | // These files must have the same package and test/not-test nature as the types |
| 158 | // from which they were generated. |
| 159 | // |
| 160 | // Types will be excluded when generated, to avoid repetitions. |
| 161 | pkgs := loadPackages(args, tags, *trimprefix, *linecomment, nil /* logf */) |
| 162 | sort.Slice(pkgs, func(i, j int) bool { |
| 163 | // Put x_test packages last. |
| 164 | iTest := strings.HasSuffix(pkgs[i].name, "_test") |
| 165 | jTest := strings.HasSuffix(pkgs[j].name, "_test") |
| 166 | if iTest != jTest { |
| 167 | return !iTest |
| 168 | } |
| 169 | |
| 170 | return len(pkgs[i].files) < len(pkgs[j].files) |
| 171 | }) |
| 172 | for _, pkg := range pkgs { |
| 173 | g := Generator{ |
| 174 | pkg: pkg, |
| 175 | } |
| 176 | |
| 177 | // Print the header and package clause. |
| 178 | g.Printf("// Code generated by \"stringer %s\"; DO NOT EDIT.\n", strings.Join(os.Args[1:], " ")) |
| 179 | g.Printf("\n") |
| 180 | g.Printf("package %s", g.pkg.name) |
| 181 | g.Printf("\n") |
| 182 | g.Printf("import \"strconv\"\n") // Used by all methods. |
| 183 | |
| 184 | // Run generate for types that can be found. Keep the rest for the remainingTypes iteration. |
| 185 | var foundTypes, remainingTypes []string |
| 186 | for _, typeName := range types { |
| 187 | values := findValues(typeName, pkg) |
| 188 | if len(values) > 0 { |
| 189 | g.generate(typeName, values) |
| 190 | foundTypes = append(foundTypes, typeName) |
| 191 | } else { |
| 192 | remainingTypes = append(remainingTypes, typeName) |
| 193 | } |
| 194 | } |
| 195 | if len(foundTypes) == 0 { |
| 196 | // This package didn't have any of the relevant types, skip writing a file. |
| 197 | continue |
| 198 | } |
| 199 | if len(remainingTypes) > 0 && output != nil && *output != "" { |
| 200 | log.Fatalf("cannot write to single file (-output=%q) when matching types are found in multiple packages", *output) |
| 201 | } |
| 202 | types = remainingTypes |
| 203 | |
| 204 | // Format the output. |
| 205 | src := g.format() |
| 206 | |
| 207 | // Write to file. |
| 208 | outputName := *output |
| 209 | if outputName == "" { |
| 210 | // Type names will be unique across packages since only the first |
| 211 | // match is picked. |
| 212 | // So there won't be collisions between a package compiled for tests |
| 213 | // and the separate package of tests (package foo_test). |
| 214 | outputName = filepath.Join(dir, baseName(pkg, foundTypes[0])) |
| 215 | } |
| 216 | err := os.WriteFile(outputName, src, 0o644) |
| 217 | if err != nil { |
| 218 | log.Fatalf("writing output: %s", err) |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | if len(types) > 0 { |
| 223 | log.Fatalf("no values defined for types: %s", strings.Join(types, ",")) |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | // baseName that will put the generated code together with pkg. |
| 228 | func baseName(pkg *Package, typename string) string { |
| 229 | suffix := "string.go" |
| 230 | if pkg.hasTestFiles { |
| 231 | suffix = "string_test.go" |
| 232 | } |
| 233 | return fmt.Sprintf("%s_%s", strings.ToLower(typename), suffix) |
| 234 | } |
| 235 | |
| 236 | // isDirectory reports whether the named file is a directory. |
| 237 | func isDirectory(name string) bool { |
| 238 | info, err := os.Stat(name) |
| 239 | if err != nil { |
| 240 | log.Fatal(err) |
| 241 | } |
| 242 | return info.IsDir() |
| 243 | } |
| 244 | |
| 245 | // Generator holds the state of the analysis. Primarily used to buffer |
| 246 | // the output for format.Source. |
| 247 | type Generator struct { |
| 248 | buf bytes.Buffer // Accumulated output. |
| 249 | pkg *Package // Package we are scanning. |
| 250 | |
| 251 | logf func(format string, args ...any) // test logging hook; nil when not testing |
| 252 | } |
| 253 | |
| 254 | func (g *Generator) Printf(format string, args ...any) { |
| 255 | fmt.Fprintf(&g.buf, format, args...) |
| 256 | } |
| 257 | |
| 258 | // File holds a single parsed file and associated data. |
| 259 | type File struct { |
| 260 | pkg *Package // Package to which this file belongs. |
| 261 | file *ast.File // Parsed AST. |
| 262 | // These fields are reset for each type being generated. |
| 263 | typeName string // Name of the constant type. |
| 264 | values []Value // Accumulator for constant values of that type. |
| 265 | |
| 266 | trimPrefix string |
| 267 | lineComment bool |
| 268 | } |
| 269 | |
| 270 | type Package struct { |
| 271 | name string |
| 272 | defs map[*ast.Ident]types.Object |
| 273 | files []*File |
| 274 | hasTestFiles bool |
| 275 | } |
| 276 | |
| 277 | // loadPackages analyzes the single package constructed from the patterns and tags. |
| 278 | // loadPackages exits if there is an error. |
| 279 | // |
| 280 | // Returns all variants (such as tests) of the package. |
| 281 | // |
| 282 | // logf is a test logging hook. It can be nil when not testing. |
| 283 | func loadPackages( |
| 284 | patterns, tags []string, |
| 285 | trimPrefix string, lineComment bool, |
| 286 | logf func(format string, args ...any), |
| 287 | ) []*Package { |
| 288 | cfg := &packages.Config{ |
| 289 | Mode: packages.NeedName | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax | packages.NeedFiles, |
| 290 | // Tests are included, let the caller decide how to fold them in. |
| 291 | Tests: true, |
| 292 | BuildFlags: []string{fmt.Sprintf("-tags=%s", strings.Join(tags, " "))}, |
| 293 | Logf: logf, |
| 294 | } |
| 295 | pkgs, err := packages.Load(cfg, patterns...) |
| 296 | if err != nil { |
| 297 | log.Fatal(err) |
| 298 | } |
| 299 | if len(pkgs) == 0 { |
| 300 | log.Fatalf("error: no packages matching %v", strings.Join(patterns, " ")) |
| 301 | } |
| 302 | |
| 303 | out := make([]*Package, len(pkgs)) |
| 304 | for i, pkg := range pkgs { |
| 305 | p := &Package{ |
| 306 | name: pkg.Name, |
| 307 | defs: pkg.TypesInfo.Defs, |
| 308 | files: make([]*File, len(pkg.Syntax)), |
| 309 | } |
| 310 | |
| 311 | for j, file := range pkg.Syntax { |
| 312 | p.files[j] = &File{ |
| 313 | file: file, |
| 314 | pkg: p, |
| 315 | |
| 316 | trimPrefix: trimPrefix, |
| 317 | lineComment: lineComment, |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | // Keep track of test files, since we might want to generated |
| 322 | // code that ends up in that kind of package. |
| 323 | // Can be replaced once https://go.dev/issue/38445 lands. |
| 324 | for _, f := range pkg.GoFiles { |
| 325 | if strings.HasSuffix(f, "_test.go") { |
| 326 | p.hasTestFiles = true |
| 327 | break |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | out[i] = p |
| 332 | } |
| 333 | return out |
| 334 | } |
| 335 | |
| 336 | func findValues(typeName string, pkg *Package) []Value { |
| 337 | values := make([]Value, 0, 100) |
| 338 | for _, file := range pkg.files { |
| 339 | // Set the state for this run of the walker. |
| 340 | file.typeName = typeName |
| 341 | file.values = nil |
| 342 | if file.file != nil { |
| 343 | ast.Inspect(file.file, file.genDecl) |
| 344 | values = append(values, file.values...) |
| 345 | } |
| 346 | } |
| 347 | return values |
| 348 | } |
| 349 | |
| 350 | // generate produces the String method for the named type. |
| 351 | func (g *Generator) generate(typeName string, values []Value) { |
| 352 | // Generate code that will fail if the constants change value. |
| 353 | g.Printf("func _() {\n") |
| 354 | g.Printf("\t// An \"invalid array index\" compiler error signifies that the constant values have changed.\n") |
| 355 | g.Printf("\t// Re-run the stringer command to generate them again.\n") |
| 356 | g.Printf("\tvar x [1]struct{}\n") |
| 357 | for _, v := range values { |
| 358 | g.Printf("\t_ = x[%s - %s]\n", v.originalName, v.str) |
| 359 | } |
| 360 | g.Printf("}\n") |
| 361 | runs := splitIntoRuns(values) |
| 362 | // The decision of which pattern to use depends on the number of |
| 363 | // runs in the numbers. If there's only one, it's easy. For more than |
| 364 | // one, there's a tradeoff between complexity and size of the data |
| 365 | // and code vs. the simplicity of a map. A map takes more space, |
| 366 | // but so does the code. The decision here (crossover at 10) is |
| 367 | // arbitrary, but considers that for large numbers of runs the cost |
| 368 | // of the linear scan in the switch might become important, and |
| 369 | // rather than use yet another algorithm such as binary search, |
| 370 | // we punt and use a map. In any case, the likelihood of a map |
| 371 | // being necessary for any realistic example other than bitmasks |
| 372 | // is very low. And bitmasks probably deserve their own analysis, |
| 373 | // to be done some other day. |
| 374 | switch { |
| 375 | case len(runs) == 1: |
| 376 | g.buildOneRun(runs, typeName) |
| 377 | case len(runs) <= 10: |
| 378 | g.buildMultipleRuns(runs, typeName) |
| 379 | default: |
| 380 | g.buildMap(runs, typeName) |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | // splitIntoRuns breaks the values into runs of contiguous sequences. |
| 385 | // For example, given 1,2,3,5,6,7 it returns {1,2,3},{5,6,7}. |
| 386 | // The input slice is known to be non-empty. |
| 387 | func splitIntoRuns(values []Value) [][]Value { |
| 388 | // We use stable sort so the lexically first name is chosen for equal elements. |
| 389 | sort.Stable(byValue(values)) |
| 390 | // Remove duplicates. Stable sort has put the one we want to print first, |
| 391 | // so use that one. The String method won't care about which named constant |
| 392 | // was the argument, so the first name for the given value is the only one to keep. |
| 393 | // We need to do this because identical values would cause the switch or map |
| 394 | // to fail to compile. |
| 395 | j := 1 |
| 396 | for i := 1; i < len(values); i++ { |
| 397 | if values[i].value != values[i-1].value { |
| 398 | values[j] = values[i] |
| 399 | j++ |
| 400 | } |
| 401 | } |
| 402 | values = values[:j] |
| 403 | runs := make([][]Value, 0, 10) |
| 404 | for len(values) > 0 { |
| 405 | // One contiguous sequence per outer loop. |
| 406 | i := 1 |
| 407 | for i < len(values) && values[i].value == values[i-1].value+1 { |
| 408 | i++ |
| 409 | } |
| 410 | runs = append(runs, values[:i]) |
| 411 | values = values[i:] |
| 412 | } |
| 413 | return runs |
| 414 | } |
| 415 | |
| 416 | // format returns the gofmt-ed contents of the Generator's buffer. |
| 417 | func (g *Generator) format() []byte { |
| 418 | src, err := format.Source(g.buf.Bytes()) |
| 419 | if err != nil { |
| 420 | // Should never happen, but can arise when developing this code. |
| 421 | // The user can compile the output to see the error. |
| 422 | log.Printf("warning: internal error: invalid Go generated: %s", err) |
| 423 | log.Printf("warning: compile the package to analyze the error") |
| 424 | return g.buf.Bytes() |
| 425 | } |
| 426 | return src |
| 427 | } |
| 428 | |
| 429 | // Value represents a declared constant. |
| 430 | type Value struct { |
| 431 | originalName string // The name of the constant. |
| 432 | name string // The name with trimmed prefix. |
| 433 | // The value is stored as a bit pattern alone. The boolean tells us |
| 434 | // whether to interpret it as an int64 or a uint64; the only place |
| 435 | // this matters is when sorting. |
| 436 | // Much of the time the str field is all we need; it is printed |
| 437 | // by Value.String. |
| 438 | value uint64 // Will be converted to int64 when needed. |
| 439 | signed bool // Whether the constant is a signed type. |
| 440 | str string // The string representation given by the "go/constant" package. |
| 441 | } |
| 442 | |
| 443 | func (v *Value) String() string { |
| 444 | return v.str |
| 445 | } |
| 446 | |
| 447 | // byValue lets us sort the constants into increasing order. |
| 448 | // We take care in the Less method to sort in signed or unsigned order, |
| 449 | // as appropriate. |
| 450 | type byValue []Value |
| 451 | |
| 452 | func (b byValue) Len() int { return len(b) } |
| 453 | func (b byValue) Swap(i, j int) { b[i], b[j] = b[j], b[i] } |
| 454 | func (b byValue) Less(i, j int) bool { |
| 455 | if b[i].signed { |
| 456 | return int64(b[i].value) < int64(b[j].value) |
| 457 | } |
| 458 | return b[i].value < b[j].value |
| 459 | } |
| 460 | |
| 461 | // genDecl processes one declaration clause. |
| 462 | func (f *File) genDecl(node ast.Node) bool { |
| 463 | decl, ok := node.(*ast.GenDecl) |
| 464 | if !ok || decl.Tok != token.CONST { |
| 465 | // We only care about const declarations. |
| 466 | return true |
| 467 | } |
| 468 | // The name of the type of the constants we are declaring. |
| 469 | // Can change if this is a multi-element declaration. |
| 470 | typ := "" |
| 471 | // Loop over the elements of the declaration. Each element is a ValueSpec: |
| 472 | // a list of names possibly followed by a type, possibly followed by values. |
| 473 | // If the type and value are both missing, we carry down the type (and value, |
| 474 | // but the "go/types" package takes care of that). |
| 475 | for _, spec := range decl.Specs { |
| 476 | vspec := spec.(*ast.ValueSpec) // Guaranteed to succeed as this is CONST. |
| 477 | if vspec.Type == nil && len(vspec.Values) > 0 { |
| 478 | // "X = 1". With no type but a value. If the constant is untyped, |
| 479 | // skip this vspec and reset the remembered type. |
| 480 | typ = "" |
| 481 | |
| 482 | // If this is a simple type conversion, remember the type. |
| 483 | // We don't mind if this is actually a call; a qualified call won't |
| 484 | // be matched (that will be SelectorExpr, not Ident), and only unusual |
| 485 | // situations will result in a function call that appears to be |
| 486 | // a type conversion. |
| 487 | ce, ok := vspec.Values[0].(*ast.CallExpr) |
| 488 | if !ok { |
| 489 | continue |
| 490 | } |
| 491 | id, ok := ce.Fun.(*ast.Ident) |
| 492 | if !ok { |
| 493 | continue |
| 494 | } |
| 495 | typ = id.Name |
| 496 | } |
| 497 | if vspec.Type != nil { |
| 498 | // "X T". We have a type. Remember it. |
| 499 | ident, ok := vspec.Type.(*ast.Ident) |
| 500 | if !ok { |
| 501 | continue |
| 502 | } |
| 503 | typ = ident.Name |
| 504 | } |
| 505 | if typ != f.typeName { |
| 506 | // This is not the type we're looking for. |
| 507 | continue |
| 508 | } |
| 509 | // We now have a list of names (from one line of source code) all being |
| 510 | // declared with the desired type. |
| 511 | // Grab their names and actual values and store them in f.values. |
| 512 | for _, name := range vspec.Names { |
| 513 | if name.Name == "_" { |
| 514 | continue |
| 515 | } |
| 516 | // This dance lets the type checker find the values for us. It's a |
| 517 | // bit tricky: look up the object declared by the name, find its |
| 518 | // types.Const, and extract its value. |
| 519 | obj, ok := f.pkg.defs[name] |
| 520 | if !ok { |
| 521 | log.Fatalf("no value for constant %s", name) |
| 522 | } |
| 523 | info := obj.Type().Underlying().(*types.Basic).Info() |
| 524 | if info&types.IsInteger == 0 { |
| 525 | log.Fatalf("can't handle non-integer constant type %s", typ) |
| 526 | } |
| 527 | value := obj.(*types.Const).Val() // Guaranteed to succeed as this is CONST. |
| 528 | if value.Kind() != constant.Int { |
| 529 | log.Fatalf("can't happen: constant is not an integer %s", name) |
| 530 | } |
| 531 | i64, isInt := constant.Int64Val(value) |
| 532 | u64, isUint := constant.Uint64Val(value) |
| 533 | if !isInt && !isUint { |
| 534 | log.Fatalf("internal error: value of %s is not an integer: %s", name, value.String()) |
| 535 | } |
| 536 | if !isInt { |
| 537 | u64 = uint64(i64) |
| 538 | } |
| 539 | v := Value{ |
| 540 | originalName: name.Name, |
| 541 | value: u64, |
| 542 | signed: info&types.IsUnsigned == 0, |
| 543 | str: value.String(), |
| 544 | } |
| 545 | if c := vspec.Comment; f.lineComment && c != nil && len(c.List) == 1 { |
| 546 | v.name = strings.TrimSpace(c.Text()) |
| 547 | } else { |
| 548 | v.name = strings.TrimPrefix(v.originalName, f.trimPrefix) |
| 549 | } |
| 550 | f.values = append(f.values, v) |
| 551 | } |
| 552 | } |
| 553 | return false |
| 554 | } |
| 555 | |
| 556 | // Helpers |
| 557 | |
| 558 | // usize returns the number of bits of the smallest unsigned integer |
| 559 | // type that will hold n. Used to create the smallest possible slice of |
| 560 | // integers to use as indexes into the concatenated strings. |
| 561 | func usize(n int) int { |
| 562 | switch { |
| 563 | case n < 1<<8: |
| 564 | return 8 |
| 565 | case n < 1<<16: |
| 566 | return 16 |
| 567 | default: |
| 568 | // 2^32 is enough constants for anyone. |
| 569 | return 32 |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | // declareIndexAndNameVars declares the index slices and concatenated names |
| 574 | // strings representing the runs of values. |
| 575 | func (g *Generator) declareIndexAndNameVars(runs [][]Value, typeName string) { |
| 576 | var indexes, names []string |
| 577 | for i, run := range runs { |
| 578 | index, name := g.createIndexAndNameDecl(run, typeName, fmt.Sprintf("_%d", i)) |
| 579 | if len(run) != 1 { |
| 580 | indexes = append(indexes, index) |
| 581 | } |
| 582 | names = append(names, name) |
| 583 | } |
| 584 | g.Printf("const (\n") |
| 585 | for _, name := range names { |
| 586 | g.Printf("\t%s\n", name) |
| 587 | } |
| 588 | g.Printf(")\n\n") |
| 589 | |
| 590 | if len(indexes) > 0 { |
| 591 | g.Printf("var (") |
| 592 | for _, index := range indexes { |
| 593 | g.Printf("\t%s\n", index) |
| 594 | } |
| 595 | g.Printf(")\n\n") |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | // declareIndexAndNameVar is the single-run version of declareIndexAndNameVars |
| 600 | func (g *Generator) declareIndexAndNameVar(run []Value, typeName string) { |
| 601 | index, name := g.createIndexAndNameDecl(run, typeName, "") |
| 602 | g.Printf("const %s\n", name) |
| 603 | g.Printf("var %s\n", index) |
| 604 | } |
| 605 | |
| 606 | // createIndexAndNameDecl returns the pair of declarations for the run. The caller will add "const" and "var". |
| 607 | func (g *Generator) createIndexAndNameDecl(run []Value, typeName string, suffix string) (string, string) { |
| 608 | b := new(bytes.Buffer) |
| 609 | indexes := make([]int, len(run)) |
| 610 | for i := range run { |
| 611 | b.WriteString(run[i].name) |
| 612 | indexes[i] = b.Len() |
| 613 | } |
| 614 | nameConst := fmt.Sprintf("_%s_name%s = %q", typeName, suffix, b.String()) |
| 615 | nameLen := b.Len() |
| 616 | b.Reset() |
| 617 | fmt.Fprintf(b, "_%s_index%s = [...]uint%d{0, ", typeName, suffix, usize(nameLen)) |
| 618 | for i, v := range indexes { |
| 619 | if i > 0 { |
| 620 | fmt.Fprintf(b, ", ") |
| 621 | } |
| 622 | fmt.Fprintf(b, "%d", v) |
| 623 | } |
| 624 | fmt.Fprintf(b, "}") |
| 625 | return b.String(), nameConst |
| 626 | } |
| 627 | |
| 628 | // declareNameVars declares the concatenated names string representing all the values in the runs. |
| 629 | func (g *Generator) declareNameVars(runs [][]Value, typeName string, suffix string) { |
| 630 | g.Printf("const _%s_name%s = \"", typeName, suffix) |
| 631 | for _, run := range runs { |
| 632 | for i := range run { |
| 633 | g.Printf("%s", run[i].name) |
| 634 | } |
| 635 | } |
| 636 | g.Printf("\"\n") |
| 637 | } |
| 638 | |
| 639 | // buildOneRun generates the variables and String method for a single run of contiguous values. |
| 640 | func (g *Generator) buildOneRun(runs [][]Value, typeName string) { |
| 641 | values := runs[0] |
| 642 | g.Printf("\n") |
| 643 | g.declareIndexAndNameVar(values, typeName) |
| 644 | g.Printf(stringOneRun, typeName, values[0].String()) |
| 645 | } |
| 646 | |
| 647 | // Arguments to format are: |
| 648 | // |
| 649 | // [1]: type name |
| 650 | // [2]: lowest defined value for type, as a string |
| 651 | const stringOneRun = `func (i %[1]s) String() string { |
| 652 | idx := int(i) - %[2]s |
| 653 | if i < %[2]s || idx >= len(_%[1]s_index)-1 { |
| 654 | return "%[1]s(" + strconv.FormatInt(int64(i), 10) + ")" |
| 655 | } |
| 656 | return _%[1]s_name[_%[1]s_index[idx] : _%[1]s_index[idx+1]] |
| 657 | } |
| 658 | ` |
| 659 | |
| 660 | // buildMultipleRuns generates the variables and String method for multiple runs of contiguous values. |
| 661 | // For this pattern, a single Printf format won't do. |
| 662 | func (g *Generator) buildMultipleRuns(runs [][]Value, typeName string) { |
| 663 | g.Printf("\n") |
| 664 | g.declareIndexAndNameVars(runs, typeName) |
| 665 | g.Printf("func (i %s) String() string {\n", typeName) |
| 666 | g.Printf("\tswitch {\n") |
| 667 | for i, values := range runs { |
| 668 | if len(values) == 1 { |
| 669 | g.Printf("\tcase i == %s:\n", &values[0]) |
| 670 | g.Printf("\t\treturn _%s_name_%d\n", typeName, i) |
| 671 | continue |
| 672 | } |
| 673 | if values[0].value == 0 && !values[0].signed { |
| 674 | // For an unsigned lower bound of 0, "0 <= i" would be redundant. |
| 675 | g.Printf("\tcase i <= %s:\n", &values[len(values)-1]) |
| 676 | } else { |
| 677 | g.Printf("\tcase %s <= i && i <= %s:\n", &values[0], &values[len(values)-1]) |
| 678 | } |
| 679 | if values[0].value != 0 { |
| 680 | g.Printf("\t\ti -= %s\n", &values[0]) |
| 681 | } |
| 682 | g.Printf("\t\treturn _%s_name_%d[_%s_index_%d[i]:_%s_index_%d[i+1]]\n", |
| 683 | typeName, i, typeName, i, typeName, i) |
| 684 | } |
| 685 | g.Printf("\tdefault:\n") |
| 686 | g.Printf("\t\treturn \"%s(\" + strconv.FormatInt(int64(i), 10) + \")\"\n", typeName) |
| 687 | g.Printf("\t}\n") |
| 688 | g.Printf("}\n") |
| 689 | } |
| 690 | |
| 691 | // buildMap handles the case where the space is so sparse a map is a reasonable fallback. |
| 692 | // It's a rare situation but has simple code. |
| 693 | func (g *Generator) buildMap(runs [][]Value, typeName string) { |
| 694 | g.Printf("\n") |
| 695 | g.declareNameVars(runs, typeName, "") |
| 696 | g.Printf("\nvar _%s_map = map[%s]string{\n", typeName, typeName) |
| 697 | n := 0 |
| 698 | for _, values := range runs { |
| 699 | for _, value := range values { |
| 700 | g.Printf("\t%s: _%s_name[%d:%d],\n", &value, typeName, n, n+len(value.name)) |
| 701 | n += len(value.name) |
| 702 | } |
| 703 | } |
| 704 | g.Printf("}\n\n") |
| 705 | g.Printf(stringMap, typeName) |
| 706 | } |
| 707 | |
| 708 | // Argument to format is the type name. |
| 709 | const stringMap = `func (i %[1]s) String() string { |
| 710 | if str, ok := _%[1]s_map[i]; ok { |
| 711 | return str |
| 712 | } |
| 713 | return "%[1]s(" + strconv.FormatInt(int64(i), 10) + ")" |
| 714 | } |
| 715 | ` |