Debian Codegraph @

cmd/stringer/stringer.go

raw symbols SCIP
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 mainscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/ // import "golang.org/x/tools/cmd/stringer"
78
79 import (
80 "bytesscip-go gomod github.com/golang/go/src go1.25.0 bytes/"
81 "flagscip-go gomod github.com/golang/go/src go1.25.0 flag/"
82 "fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/"
83 "go/astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/"
84 "go/constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/"
85 "go/formatscip-go gomod github.com/golang/go/src go1.25.0 `go/format`/"
86 "go/tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/"
87 "go/typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/"
88 "logscip-go gomod github.com/golang/go/src go1.25.0 log/"
89 "osscip-go gomod github.com/golang/go/src go1.25.0 os/"
90 "path/filepathscip-go gomod github.com/golang/go/src go1.25.0 `path/filepath`/"
91 "sortscip-go gomod github.com/golang/go/src go1.25.0 sort/"
92 "stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/"
93
94 "golang.org/x/tools/go/packagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/"
95 )
96
97 var (
98 typeNamesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/typeNames. = flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Stringscip-go gomod github.com/golang/go/src go1.25.0 flag/String().("type", "", "comma-separated list of type names; must be set")
99 outputscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/output. = flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Stringscip-go gomod github.com/golang/go/src go1.25.0 flag/String().("output", "", "output file name; default srcdir/<type>_string.go")
100 trimprefixscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/trimprefix. = flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Stringscip-go gomod github.com/golang/go/src go1.25.0 flag/String().("trimprefix", "", "trim the `prefix` from the generated constant names")
101 linecommentscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/linecomment. = flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Boolscip-go gomod github.com/golang/go/src go1.25.0 flag/Bool().("linecomment", false, "use line comment text as printed text when present")
102 buildTagsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/buildTags. = flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Stringscip-go gomod github.com/golang/go/src go1.25.0 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 Usagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Usage().() {
107 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(osscip-go gomod github.com/golang/go/src go1.25.0 os/.Stderrscip-go gomod github.com/golang/go/src go1.25.0 os/Stderr., "Usage of stringer:\n")
108 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(osscip-go gomod github.com/golang/go/src go1.25.0 os/.Stderrscip-go gomod github.com/golang/go/src go1.25.0 os/Stderr., "\tstringer [flags] -type T [directory]\n")
109 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(osscip-go gomod github.com/golang/go/src go1.25.0 os/.Stderrscip-go gomod github.com/golang/go/src go1.25.0 os/Stderr., "\tstringer [flags] -type T files... # Must be a single package\n")
110 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(osscip-go gomod github.com/golang/go/src go1.25.0 os/.Stderrscip-go gomod github.com/golang/go/src go1.25.0 os/Stderr., "For more information, see:\n")
111 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(osscip-go gomod github.com/golang/go/src go1.25.0 os/.Stderrscip-go gomod github.com/golang/go/src go1.25.0 os/Stderr., "\thttps://pkg.go.dev/golang.org/x/tools/cmd/stringer\n")
112 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(osscip-go gomod github.com/golang/go/src go1.25.0 os/.Stderrscip-go gomod github.com/golang/go/src go1.25.0 os/Stderr., "Flags:\n")
113 flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.PrintDefaultsscip-go gomod github.com/golang/go/src go1.25.0 flag/PrintDefaults().()
114 }
115
116 func mainscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/main().() {
117 logscip-go gomod github.com/golang/go/src go1.25.0 log/.SetFlagsscip-go gomod github.com/golang/go/src go1.25.0 log/SetFlags().(0)
118 logscip-go gomod github.com/golang/go/src go1.25.0 log/.SetPrefixscip-go gomod github.com/golang/go/src go1.25.0 log/SetPrefix().("stringer: ")
119 flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Usagescip-go gomod github.com/golang/go/src go1.25.0 flag/Usage. = Usagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Usage().
120 flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Parsescip-go gomod github.com/golang/go/src go1.25.0 flag/Parse().()
121 if len(*typeNamesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/typeNames.) == 0 {
122 flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Usagescip-go gomod github.com/golang/go/src go1.25.0 flag/Usage.()
123 osscip-go gomod github.com/golang/go/src go1.25.0 os/.Exitscip-go gomod github.com/golang/go/src go1.25.0 os/Exit().(2)
124 }
125 types := stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.Splitscip-go gomod github.com/golang/go/src go1.25.0 strings/Split().(*typeNamesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/typeNames., ",")
126 var tags []string
127 if len(*buildTagsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/buildTags.) > 0 {
128 tags = stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.Splitscip-go gomod github.com/golang/go/src go1.25.0 strings/Split().(*buildTagsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/buildTags., ",")
129 }
130
131 // We accept either one directory or a list of files. Which do we have?
132 args := flagscip-go gomod github.com/golang/go/src go1.25.0 flag/.Argsscip-go gomod github.com/golang/go/src go1.25.0 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 && isDirectoryscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/isDirectory().(args[0]) {
142 dir = args[0]
143 } else {
144 if len(tags) != 0 {
145 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalscip-go gomod github.com/golang/go/src go1.25.0 log/Fatal().("-tags option applies only to directories, not when files are specified")
146 }
147 dir = filepathscip-go gomod github.com/golang/go/src go1.25.0 `path/filepath`/.Dirscip-go gomod github.com/golang/go/src go1.25.0 `path/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 := loadPackagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/loadPackages().(args, tags, *trimprefixscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/trimprefix., *linecommentscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/linecomment., nil /* logf */)
162 sortscip-go gomod github.com/golang/go/src go1.25.0 sort/.Slicescip-go gomod github.com/golang/go/src go1.25.0 sort/Slice().(pkgs, func(i, j int) bool {
163 // Put x_test packages last.
164 iTest := stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.HasSuffixscip-go gomod github.com/golang/go/src go1.25.0 strings/HasSuffix().(pkgs[i].namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#name., "_test")
165 jTest := stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.HasSuffixscip-go gomod github.com/golang/go/src go1.25.0 strings/HasSuffix().(pkgs[j].namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#name., "_test")
166 if iTest != jTest {
167 return !iTest
168 }
169
170 return len(pkgs[i].filesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#files.) < len(pkgs[j].filesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#files.)
171 })
172 for _, pkg := range pkgs {
173 g := Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#{
174 pkgscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#pkg.: pkg,
175 }
176
177 // Print the header and package clause.
178 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("// Code generated by \"stringer %s\"; DO NOT EDIT.\n", stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.Joinscip-go gomod github.com/golang/go/src go1.25.0 strings/Join().(osscip-go gomod github.com/golang/go/src go1.25.0 os/.Argsscip-go gomod github.com/golang/go/src go1.25.0 os/Args.[1:], " "))
179 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\n")
180 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("package %s", g.pkgscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#pkg..namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#name.)
181 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\n")
182 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#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 := findValuesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/findValues().(typeName, pkg)
188 if len(values) > 0 {
189 g.generatescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#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 && outputscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/output. != nil && *outputscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/output. != "" {
200 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalfscip-go gomod github.com/golang/go/src go1.25.0 log/Fatalf().("cannot write to single file (-output=%q) when matching types are found in multiple packages", *outputscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/output.)
201 }
202 types = remainingTypes
203
204 // Format the output.
205 src := g.formatscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#format().()
206
207 // Write to file.
208 outputName := *outputscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/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 = filepathscip-go gomod github.com/golang/go/src go1.25.0 `path/filepath`/.Joinscip-go gomod github.com/golang/go/src go1.25.0 `path/filepath`/Join().(dir, baseNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/baseName().(pkg, foundTypes[0]))
215 }
216 err := osscip-go gomod github.com/golang/go/src go1.25.0 os/.WriteFilescip-go gomod github.com/golang/go/src go1.25.0 os/WriteFile().(outputName, src, 0o644)
217 if err != nil {
218 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalfscip-go gomod github.com/golang/go/src go1.25.0 log/Fatalf().("writing output: %s", err)
219 }
220 }
221
222 if len(types) > 0 {
223 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalfscip-go gomod github.com/golang/go/src go1.25.0 log/Fatalf().("no values defined for types: %s", stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.Joinscip-go gomod github.com/golang/go/src go1.25.0 strings/Join().(types, ","))
224 }
225 }
226
227 // baseName that will put the generated code together with pkg.
228 func baseNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/baseName().(pkg *Packagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#, typename string) string {
229 suffix := "string.go"
230 if pkg.hasTestFilesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#hasTestFiles. {
231 suffix = "string_test.go"
232 }
233 return fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("%s_%s", stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.ToLowerscip-go gomod github.com/golang/go/src go1.25.0 strings/ToLower().(typename), suffix)
234 }
235
236 // isDirectory reports whether the named file is a directory.
237 func isDirectoryscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/isDirectory().(name string) bool {
238 info, err := osscip-go gomod github.com/golang/go/src go1.25.0 os/.Statscip-go gomod github.com/golang/go/src go1.25.0 os/Stat().(name)
239 if err != nil {
240 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalscip-go gomod github.com/golang/go/src go1.25.0 log/Fatal().(err)
241 }
242 return info.IsDirscip-go gomod github.com/golang/go/src go1.25.0 `io/fs`/FileInfo#IsDir().()
243 }
244
245 // Generator holds the state of the analysis. Primarily used to buffer
246 // the output for format.Source.
247 type Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator# struct {
248 bufscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buf. bytesscip-go gomod github.com/golang/go/src go1.25.0 bytes/.Bufferscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer# // Accumulated output.
249 pkgscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#pkg. *Packagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package# // Package we are scanning.
250
251 logfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#logf. func(format string, args ...any) // test logging hook; nil when not testing
252 }
253
254 func (g *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().(format string, args ...any) {
255 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(&g.bufscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buf., format, args...)
256 }
257
258 // File holds a single parsed file and associated data.
259 type Filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File# struct {
260 pkgscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#pkg. *Packagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package# // Package to which this file belongs.
261 filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#file. *astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Filescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/File# // Parsed AST.
262 // These fields are reset for each type being generated.
263 typeNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#typeName. string // Name of the constant type.
264 valuesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#values. []Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value# // Accumulator for constant values of that type.
265
266 trimPrefixscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#trimPrefix. string
267 lineCommentscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#lineComment. bool
268 }
269
270 type Packagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package# struct {
271 namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#name. string
272 defsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#defs. map[*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#]typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Objectscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#
273 filesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#files. []*Filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#
274 hasTestFilesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#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 loadPackagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/loadPackages().(
284 patterns, tags []string,
285 trimPrefix string, lineComment bool,
286 logf func(format string, args ...any),
287 ) []*Packagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package# {
288 cfg := &packagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/.Configscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Config#{
289 Modescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Config#Mode.: packagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/.NeedNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/NeedName. | packagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/.NeedTypesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/NeedTypes. | packagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/.NeedTypesInfoscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/NeedTypesInfo. | packagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/.NeedSyntaxscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/NeedSyntax. | packagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/.NeedFilesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/NeedFiles.,
290 // Tests are included, let the caller decide how to fold them in.
291 Testsscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Config#Tests.: true,
292 BuildFlagsscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Config#BuildFlags.: []string{fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("-tags=%s", stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.Joinscip-go gomod github.com/golang/go/src go1.25.0 strings/Join().(tags, " "))},
293 Logfscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Config#Logf.: logf,
294 }
295 pkgs, err := packagesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/.Loadscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Load().(cfg, patterns...)
296 if err != nil {
297 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalscip-go gomod github.com/golang/go/src go1.25.0 log/Fatal().(err)
298 }
299 if len(pkgs) == 0 {
300 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalfscip-go gomod github.com/golang/go/src go1.25.0 log/Fatalf().("error: no packages matching %v", stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.Joinscip-go gomod github.com/golang/go/src go1.25.0 strings/Join().(patterns, " "))
301 }
302
303 out := make([]*Packagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#, len(pkgs))
304 for i, pkg := range pkgs {
305 p := &Packagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#{
306 namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#name.: pkg.Namescip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Package#Name.,
307 defsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#defs.: pkg.TypesInfoscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Package#TypesInfo..Defsscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Info#Defs.,
308 filesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#files.: make([]*Filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#, len(pkg.Syntaxscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Package#Syntax.)),
309 }
310
311 for j, file := range pkg.Syntaxscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Package#Syntax. {
312 p.filesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#files.[j] = &Filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#{
313 filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#file.: file,
314 pkgscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#pkg.: p,
315
316 trimPrefixscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#trimPrefix.: trimPrefix,
317 lineCommentscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#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.GoFilesscip-go gomod golang.org/x/tools . `golang.org/x/tools/go/packages`/Package#GoFiles. {
325 if stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.HasSuffixscip-go gomod github.com/golang/go/src go1.25.0 strings/HasSuffix().(f, "_test.go") {
326 p.hasTestFilesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#hasTestFiles. = true
327 break
328 }
329 }
330
331 out[i] = p
332 }
333 return out
334 }
335
336 func findValuesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/findValues().(typeName string, pkg *Packagescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#) []Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value# {
337 values := make([]Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#, 0, 100)
338 for _, file := range pkg.filesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#files. {
339 // Set the state for this run of the walker.
340 file.typeNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#typeName. = typeName
341 file.valuesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#values. = nil
342 if file.filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#file. != nil {
343 astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Inspectscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Inspect().(file.filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#file., file.genDeclscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#genDecl().)
344 values = append(values, file.valuesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#values....)
345 }
346 }
347 return values
348 }
349
350 // generate produces the String method for the named type.
351 func (g *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) generatescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#generate().(typeName string, values []Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#) {
352 // Generate code that will fail if the constants change value.
353 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("func _() {\n")
354 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t// An \"invalid array index\" compiler error signifies that the constant values have changed.\n")
355 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t// Re-run the stringer command to generate them again.\n")
356 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\tvar x [1]struct{}\n")
357 for _, v := range values {
358 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t_ = x[%s - %s]\n", v.originalNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#originalName., v.strscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#str.)
359 }
360 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("}\n")
361 runs := splitIntoRunsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/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.buildOneRunscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buildOneRun().(runs, typeName)
377 case len(runs) <= 10:
378 g.buildMultipleRunsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buildMultipleRuns().(runs, typeName)
379 default:
380 g.buildMapscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#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 splitIntoRunsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/splitIntoRuns().(values []Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#) [][]Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value# {
388 // We use stable sort so the lexically first name is chosen for equal elements.
389 sortscip-go gomod github.com/golang/go/src go1.25.0 sort/.Stablescip-go gomod github.com/golang/go/src go1.25.0 sort/Stable().(byValuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/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].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value. != values[i-1].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value. {
398 values[j] = values[i]
399 j++
400 }
401 }
402 values = values[:j]
403 runs := make([][]Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/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].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value. == values[i-1].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#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 *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) formatscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#format().() []byte {
418 src, err := formatscip-go gomod github.com/golang/go/src go1.25.0 `go/format`/.Sourcescip-go gomod github.com/golang/go/src go1.25.0 `go/format`/Source().(g.bufscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buf..Bytesscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#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 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Printfscip-go gomod github.com/golang/go/src go1.25.0 log/Printf().("warning: internal error: invalid Go generated: %s", err)
423 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Printfscip-go gomod github.com/golang/go/src go1.25.0 log/Printf().("warning: compile the package to analyze the error")
424 return g.bufscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buf..Bytesscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#Bytes().()
425 }
426 return src
427 }
428
429 // Value represents a declared constant.
430 type Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value# struct {
431 originalNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#originalName. string // The name of the constant.
432 namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#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 valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value. uint64 // Will be converted to int64 when needed.
439 signedscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#signed. bool // Whether the constant is a signed type.
440 strscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#str. string // The string representation given by the "go/constant" package.
441 }
442
443 func (v *Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#) Stringscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#String().() string {
444 return v.strscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#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 byValuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/byValue# []Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#
451
452 func (b byValuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/byValue#) Lenscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/byValue#Len().() int { return len(b) }
453 func (b byValuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/byValue#) Swapscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/byValue#Swap().(i, j int) { b[i], b[j] = b[j], b[i] }
454 func (b byValuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/byValue#) Lessscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/byValue#Less().(i, j int) bool {
455 if b[i].signedscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#signed. {
456 return int64(b[i].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value.) < int64(b[j].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value.)
457 }
458 return b[i].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value. < b[j].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value.
459 }
460
461 // genDecl processes one declaration clause.
462 func (f *Filescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#) genDeclscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#genDecl().(node astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Nodescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Node#) bool {
463 decl, ok := node.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.GenDeclscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/GenDecl#)
464 if !ok || decl.Tokscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/GenDecl#Tok. != tokenscip-go gomod github.com/golang/go/src go1.25.0 `go/token`/.CONSTscip-go gomod github.com/golang/go/src go1.25.0 `go/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.Specsscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/GenDecl#Specs. {
476 vspec := spec.(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.ValueSpecscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#) // Guaranteed to succeed as this is CONST.
477 if vspec.Typescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#Type. == nil && len(vspec.Valuesscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#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.Valuesscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#Values.[0].(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.CallExprscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#)
488 if !ok {
489 continue
490 }
491 id, ok := ce.Funscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CallExpr#Fun..(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#)
492 if !ok {
493 continue
494 }
495 typ = id.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Name.
496 }
497 if vspec.Typescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#Type. != nil {
498 // "X T". We have a type. Remember it.
499 ident, ok := vspec.Typescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#Type..(*astscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/.Identscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#)
500 if !ok {
501 continue
502 }
503 typ = ident.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Name.
504 }
505 if typ != f.typeNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#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.Namesscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#Names. {
513 if name.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#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.pkgscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#pkg..defsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Package#defs.[name]
520 if !ok {
521 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalfscip-go gomod github.com/golang/go/src go1.25.0 log/Fatalf().("no value for constant %s", name)
522 }
523 info := obj.Typescip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Object#Type().().Underlyingscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Type#Underlying().().(*typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Basicscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Basic#).Infoscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Basic#Info().()
524 if info&typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.IsIntegerscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/IsInteger. == 0 {
525 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalfscip-go gomod github.com/golang/go/src go1.25.0 log/Fatalf().("can't handle non-integer constant type %s", typ)
526 }
527 value := obj.(*typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.Constscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Const#).Valscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/Const#Val().() // Guaranteed to succeed as this is CONST.
528 if value.Kindscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Value#Kind().() != constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.Intscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Int. {
529 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalfscip-go gomod github.com/golang/go/src go1.25.0 log/Fatalf().("can't happen: constant is not an integer %s", name)
530 }
531 i64, isInt := constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.Int64Valscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Int64Val().(value)
532 u64, isUint := constantscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/.Uint64Valscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Uint64Val().(value)
533 if !isInt && !isUint {
534 logscip-go gomod github.com/golang/go/src go1.25.0 log/.Fatalfscip-go gomod github.com/golang/go/src go1.25.0 log/Fatalf().("internal error: value of %s is not an integer: %s", name, value.Stringscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Value#String().())
535 }
536 if !isInt {
537 u64 = uint64(i64)
538 }
539 v := Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#{
540 originalNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#originalName.: name.Namescip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/Ident#Name.,
541 valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value.: u64,
542 signedscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#signed.: info&typesscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/.IsUnsignedscip-go gomod github.com/golang/go/src go1.25.0 `go/types`/IsUnsigned. == 0,
543 strscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#str.: value.Stringscip-go gomod github.com/golang/go/src go1.25.0 `go/constant`/Value#String().(),
544 }
545 if c := vspec.Commentscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/ValueSpec#Comment.; f.lineCommentscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#lineComment. && c != nil && len(c.Listscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CommentGroup#List.) == 1 {
546 v.namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#name. = stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.TrimSpacescip-go gomod github.com/golang/go/src go1.25.0 strings/TrimSpace().(c.Textscip-go gomod github.com/golang/go/src go1.25.0 `go/ast`/CommentGroup#Text().())
547 } else {
548 v.namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#name. = stringsscip-go gomod github.com/golang/go/src go1.25.0 strings/.TrimPrefixscip-go gomod github.com/golang/go/src go1.25.0 strings/TrimPrefix().(v.originalNamescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#originalName., f.trimPrefixscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#trimPrefix.)
549 }
550 f.valuesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#values. = append(f.valuesscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/File#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 usizescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/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 *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) declareIndexAndNameVarsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#declareIndexAndNameVars().(runs [][]Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#, typeName string) {
576 var indexes, names []string
577 for i, run := range runs {
578 index, name := g.createIndexAndNameDeclscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#createIndexAndNameDecl().(run, typeName, fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("_%d", i))
579 if len(run) != 1 {
580 indexes = append(indexes, index)
581 }
582 names = append(names, name)
583 }
584 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("const (\n")
585 for _, name := range names {
586 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t%s\n", name)
587 }
588 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().(")\n\n")
589
590 if len(indexes) > 0 {
591 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("var (")
592 for _, index := range indexes {
593 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t%s\n", index)
594 }
595 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().(")\n\n")
596 }
597 }
598
599 // declareIndexAndNameVar is the single-run version of declareIndexAndNameVars
600 func (g *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) declareIndexAndNameVarscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#declareIndexAndNameVar().(run []Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#, typeName string) {
601 index, name := g.createIndexAndNameDeclscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#createIndexAndNameDecl().(run, typeName, "")
602 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("const %s\n", name)
603 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#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 *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) createIndexAndNameDeclscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#createIndexAndNameDecl().(run []Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#, typeName string, suffix string) (string, string) {
608 b := new(bytesscip-go gomod github.com/golang/go/src go1.25.0 bytes/.Bufferscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#)
609 indexes := make([]int, len(run))
610 for i := range run {
611 b.WriteStringscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#WriteString().(run[i].namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#name.)
612 indexes[i] = b.Lenscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#Len().()
613 }
614 nameConst := fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Sprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Sprintf().("_%s_name%s = %q", typeName, suffix, b.Stringscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#String().())
615 nameLen := b.Lenscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#Len().()
616 b.Resetscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#Reset().()
617 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(b, "_%s_index%s = [...]uint%d{0, ", typeName, suffix, usizescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/usize().(nameLen))
618 for i, v := range indexes {
619 if i > 0 {
620 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(b, ", ")
621 }
622 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(b, "%d", v)
623 }
624 fmtscip-go gomod github.com/golang/go/src go1.25.0 fmt/.Fprintfscip-go gomod github.com/golang/go/src go1.25.0 fmt/Fprintf().(b, "}")
625 return b.Stringscip-go gomod github.com/golang/go/src go1.25.0 bytes/Buffer#String().(), nameConst
626 }
627
628 // declareNameVars declares the concatenated names string representing all the values in the runs.
629 func (g *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) declareNameVarsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#declareNameVars().(runs [][]Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#, typeName string, suffix string) {
630 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("const _%s_name%s = \"", typeName, suffix)
631 for _, run := range runs {
632 for i := range run {
633 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("%s", run[i].namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#name.)
634 }
635 }
636 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\"\n")
637 }
638
639 // buildOneRun generates the variables and String method for a single run of contiguous values.
640 func (g *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) buildOneRunscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buildOneRun().(runs [][]Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#, typeName string) {
641 values := runs[0]
642 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\n")
643 g.declareIndexAndNameVarscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#declareIndexAndNameVar().(values, typeName)
644 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().(stringOneRunscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/stringOneRun., typeName, values[0].Stringscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#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 stringOneRunscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/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 *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) buildMultipleRunsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buildMultipleRuns().(runs [][]Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#, typeName string) {
663 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\n")
664 g.declareIndexAndNameVarsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#declareIndexAndNameVars().(runs, typeName)
665 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("func (i %s) String() string {\n", typeName)
666 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\tswitch {\n")
667 for i, values := range runs {
668 if len(values) == 1 {
669 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\tcase i == %s:\n", &values[0])
670 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t\treturn _%s_name_%d\n", typeName, i)
671 continue
672 }
673 if values[0].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value. == 0 && !values[0].signedscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#signed. {
674 // For an unsigned lower bound of 0, "0 <= i" would be redundant.
675 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\tcase i <= %s:\n", &values[len(values)-1])
676 } else {
677 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\tcase %s <= i && i <= %s:\n", &values[0], &values[len(values)-1])
678 }
679 if values[0].valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#value. != 0 {
680 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t\ti -= %s\n", &values[0])
681 }
682 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#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.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\tdefault:\n")
686 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t\treturn \"%s(\" + strconv.FormatInt(int64(i), 10) + \")\"\n", typeName)
687 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t}\n")
688 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#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 *Generatorscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#) buildMapscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#buildMap().(runs [][]Valuescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#, typeName string) {
694 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\n")
695 g.declareNameVarsscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#declareNameVars().(runs, typeName, "")
696 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#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.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("\t%s: _%s_name[%d:%d],\n", &value, typeName, n, n+len(value.namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#name.))
701 n += len(value.namescip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Value#name.)
702 }
703 }
704 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().("}\n\n")
705 g.Printfscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/Generator#Printf().(stringMapscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/stringMap., typeName)
706 }
707
708 // Argument to format is the type name.
709 const stringMapscip-go gomod golang.org/x/tools . `golang.org/x/tools/cmd/stringer`/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 `