Debian Codegraph @

analysis/code/code.go

raw
1 // Package code answers structural and type questions about Go code.
2 package code
3
4 import (
5 "fmt"
6 "go/ast"
7 "go/build/constraint"
8 "go/constant"
9 "go/token"
10 "go/types"
11 "go/version"
12 "path/filepath"
13 "slices"
14 "strings"
15
16 "honnef.co/go/tools/analysis/facts/generated"
17 "honnef.co/go/tools/analysis/facts/purity"
18 "honnef.co/go/tools/analysis/facts/tokenfile"
19 "honnef.co/go/tools/go/ast/astutil"
20 "honnef.co/go/tools/go/types/typeutil"
21 "honnef.co/go/tools/knowledge"
22 "honnef.co/go/tools/pattern"
23
24 "golang.org/x/tools/go/analysis"
25 )
26
27 type Positioner interface {
28 Pos() token.Pos
29 }
30
31 func IsOfStringConvertibleByteSlice(pass *analysis.Pass, expr ast.Expr) bool {
32 typ, ok := pass.TypesInfo.TypeOf(expr).Underlying().(*types.Slice)
33 if !ok {
34 return false
35 }
36 elem := types.Unalias(typ.Elem())
37 if version.Compare(LanguageVersion(pass, expr), "go1.18") >= 0 {
38 // Before Go 1.18, one could not directly convert from []T (where 'type T byte')
39 // to string. See also https://github.com/golang/go/issues/23536.
40 elem = elem.Underlying()
41 }
42 return types.Identical(elem, types.Typ[types.Byte])
43 }
44
45 func IsOfPointerToTypeWithName(pass *analysis.Pass, expr ast.Expr, name string) bool {
46 ptr, ok := types.Unalias(pass.TypesInfo.TypeOf(expr)).(*types.Pointer)
47 if !ok {
48 return false
49 }
50 return typeutil.IsTypeWithName(ptr.Elem(), name)
51 }
52
53 func IsOfTypeWithName(pass *analysis.Pass, expr ast.Expr, name string) bool {
54 return typeutil.IsTypeWithName(pass.TypesInfo.TypeOf(expr), name)
55 }
56
57 func IsInTest(pass *analysis.Pass, node Positioner) bool {
58 // FIXME(dh): this doesn't work for global variables with
59 // initializers
60 f := pass.Fset.File(node.Pos())
61 return f != nil && strings.HasSuffix(f.Name(), "_test.go")
62 }
63
64 // IsMain reports whether the package being processed is a package
65 // main.
66 func IsMain(pass *analysis.Pass) bool {
67 return pass.Pkg.Name() == "main"
68 }
69
70 // IsMainLike reports whether the package being processed is a
71 // main-like package. A main-like package is a package that is
72 // package main, or that is intended to be used by a tool framework
73 // such as cobra to implement a command.
74 //
75 // Note that this function errs on the side of false positives; it may
76 // return true for packages that aren't main-like. IsMainLike is
77 // intended for analyses that wish to suppress diagnostics for
78 // main-like packages to avoid false positives.
79 func IsMainLike(pass *analysis.Pass) bool {
80 if pass.Pkg.Name() == "main" {
81 return true
82 }
83 for _, imp := range pass.Pkg.Imports() {
84 if imp.Path() == "github.com/spf13/cobra" {
85 return true
86 }
87 }
88 return false
89 }
90
91 func SelectorName(pass *analysis.Pass, expr *ast.SelectorExpr) string {
92 info := pass.TypesInfo
93 sel := info.Selections[expr]
94 if sel == nil {
95 if x, ok := expr.X.(*ast.Ident); ok {
96 pkg, ok := info.ObjectOf(x).(*types.PkgName)
97 if !ok {
98 // This shouldn't happen
99 return fmt.Sprintf("%s.%s", x.Name, expr.Sel.Name)
100 }
101 return fmt.Sprintf("%s.%s", pkg.Imported().Path(), expr.Sel.Name)
102 }
103 panic(fmt.Sprintf("unsupported selector: %v", expr))
104 }
105 if v, ok := sel.Obj().(*types.Var); ok && v.IsField() {
106 return fmt.Sprintf("(%s).%s", typeutil.DereferenceR(sel.Recv()), sel.Obj().Name())
107 } else {
108 return fmt.Sprintf("(%s).%s", sel.Recv(), sel.Obj().Name())
109 }
110 }
111
112 func IsNil(pass *analysis.Pass, expr ast.Expr) bool {
113 return pass.TypesInfo.Types[expr].IsNil()
114 }
115
116 func BoolConst(pass *analysis.Pass, expr ast.Expr) bool {
117 val := pass.TypesInfo.ObjectOf(expr.(*ast.Ident)).(*types.Const).Val()
118 return constant.BoolVal(val)
119 }
120
121 func IsBoolConst(pass *analysis.Pass, expr ast.Expr) bool {
122 // We explicitly don't support typed bools because more often than
123 // not, custom bool types are used as binary enums and the explicit
124 // comparison is desired. We err on the side of false negatives and
125 // treat aliases like other custom types.
126
127 ident, ok := expr.(*ast.Ident)
128 if !ok {
129 return false
130 }
131 obj := pass.TypesInfo.ObjectOf(ident)
132 c, ok := obj.(*types.Const)
133 if !ok {
134 return false
135 }
136 basic, ok := c.Type().(*types.Basic)
137 if !ok {
138 return false
139 }
140 if basic.Kind() != types.UntypedBool && basic.Kind() != types.Bool {
141 return false
142 }
143 return true
144 }
145
146 func ExprToInt(pass *analysis.Pass, expr ast.Expr) (int64, bool) {
147 tv := pass.TypesInfo.Types[expr]
148 if tv.Value == nil {
149 return 0, false
150 }
151 if tv.Value.Kind() != constant.Int {
152 return 0, false
153 }
154 return constant.Int64Val(tv.Value)
155 }
156
157 func ExprToString(pass *analysis.Pass, expr ast.Expr) (string, bool) {
158 val := pass.TypesInfo.Types[expr].Value
159 if val == nil {
160 return "", false
161 }
162 if val.Kind() != constant.String {
163 return "", false
164 }
165 return constant.StringVal(val), true
166 }
167
168 func CallName(pass *analysis.Pass, call *ast.CallExpr) string {
169 // See the comment in typeutil.FuncName for why this doesn't require special handling
170 // of aliases.
171
172 fun := astutil.Unparen(call.Fun)
173
174 // Instantiating a function cannot return another generic function, so doing this once is enough
175 switch idx := fun.(type) {
176 case *ast.IndexExpr:
177 fun = idx.X
178 case *ast.IndexListExpr:
179 fun = idx.X
180 }
181
182 // (foo)[T] is not a valid instantiation, so no need to unparen again.
183
184 switch fun := fun.(type) {
185 case *ast.SelectorExpr:
186 fn, ok := pass.TypesInfo.ObjectOf(fun.Sel).(*types.Func)
187 if !ok {
188 return ""
189 }
190 return typeutil.FuncName(fn)
191 case *ast.Ident:
192 obj := pass.TypesInfo.ObjectOf(fun)
193 switch obj := obj.(type) {
194 case *types.Func:
195 return typeutil.FuncName(obj)
196 case *types.Builtin:
197 return obj.Name()
198 default:
199 return ""
200 }
201 default:
202 return ""
203 }
204 }
205
206 func IsCallTo(pass *analysis.Pass, node ast.Node, name string) bool {
207 // See the comment in typeutil.FuncName for why this doesn't require special handling
208 // of aliases.
209
210 call, ok := node.(*ast.CallExpr)
211 if !ok {
212 return false
213 }
214 return CallName(pass, call) == name
215 }
216
217 func IsCallToAny(pass *analysis.Pass, node ast.Node, names ...string) bool {
218 // See the comment in typeutil.FuncName for why this doesn't require special handling
219 // of aliases.
220
221 call, ok := node.(*ast.CallExpr)
222 if !ok {
223 return false
224 }
225 q := CallName(pass, call)
226 return slices.Contains(names, q)
227 }
228
229 func File(pass *analysis.Pass, node Positioner) *ast.File {
230 m := pass.ResultOf[tokenfile.Analyzer].(map[*token.File]*ast.File)
231 return m[pass.Fset.File(node.Pos())]
232 }
233
234 // BuildConstraints returns the build constraints for file f. It considers both //go:build lines as well as
235 // GOOS and GOARCH in file names.
236 func BuildConstraints(pass *analysis.Pass, f *ast.File) (constraint.Expr, bool) {
237 var expr constraint.Expr
238 for _, cmt := range f.Comments {
239 if len(cmt.List) == 0 {
240 continue
241 }
242 for _, el := range cmt.List {
243 if el.Pos() > f.Package {
244 break
245 }
246 if line := el.Text; strings.HasPrefix(line, "//go:build") {
247 var err error
248 expr, err = constraint.Parse(line)
249 if err != nil {
250 expr = nil
251 }
252 break
253 }
254 }
255 }
256
257 name := pass.Fset.PositionFor(f.Pos(), false).Filename
258 oexpr := constraintsFromName(name)
259 if oexpr != nil {
260 if expr == nil {
261 expr = oexpr
262 } else {
263 expr = &constraint.AndExpr{X: expr, Y: oexpr}
264 }
265 }
266
267 return expr, expr != nil
268 }
269
270 func constraintsFromName(name string) constraint.Expr {
271 name = filepath.Base(name)
272 name = strings.TrimSuffix(name, ".go")
273 name = strings.TrimSuffix(name, "_test")
274 var goos, goarch string
275 switch strings.Count(name, "_") {
276 case 0:
277 // No GOOS or GOARCH in the file name.
278 case 1:
279 _, c, _ := strings.Cut(name, "_")
280 if _, ok := knowledge.KnownGOOS[c]; ok {
281 goos = c
282 } else if _, ok := knowledge.KnownGOARCH[c]; ok {
283 goarch = c
284 }
285 default:
286 n := strings.LastIndex(name, "_")
287 if _, ok := knowledge.KnownGOOS[name[n+1:]]; ok {
288 // The file name is *_stuff_GOOS.go
289 goos = name[n+1:]
290 } else if _, ok := knowledge.KnownGOARCH[name[n+1:]]; ok {
291 // The file name is *_GOOS_GOARCH.go or *_stuff_GOARCH.go
292 goarch = name[n+1:]
293 _, c, _ := strings.Cut(name[:n], "_")
294 if _, ok := knowledge.KnownGOOS[c]; ok {
295 // The file name is *_GOOS_GOARCH.go
296 goos = c
297 }
298 } else {
299 // The file name could also be something like foo_windows_nonsense.go — and because nonsense
300 // isn't a known GOARCH, "windows" won't be interpreted as a GOOS, either.
301 }
302 }
303
304 var expr constraint.Expr
305 if goos != "" {
306 expr = &constraint.TagExpr{Tag: goos}
307 }
308 if goarch != "" {
309 if expr == nil {
310 expr = &constraint.TagExpr{Tag: goarch}
311 } else {
312 expr = &constraint.AndExpr{X: expr, Y: &constraint.TagExpr{Tag: goarch}}
313 }
314 }
315 return expr
316 }
317
318 // IsGenerated reports whether pos is in a generated file. It ignores
319 // //line directives.
320 func IsGenerated(pass *analysis.Pass, pos token.Pos) bool {
321 _, ok := Generator(pass, pos)
322 return ok
323 }
324
325 // Generator returns the generator that generated the file containing
326 // pos. It ignores //line directives.
327 func Generator(pass *analysis.Pass, pos token.Pos) (generated.Generator, bool) {
328 file := pass.Fset.PositionFor(pos, false).Filename
329 m := pass.ResultOf[generated.Analyzer].(map[string]generated.Generator)
330 g, ok := m[file]
331 return g, ok
332 }
333
334 // MayHaveSideEffects reports whether expr may have side effects. If
335 // the purity argument is nil, this function implements a purely
336 // syntactic check, meaning that any function call may have side
337 // effects, regardless of the called function's body. Otherwise,
338 // purity will be consulted to determine the purity of function calls.
339 func MayHaveSideEffects(pass *analysis.Pass, expr ast.Expr, purity purity.Result) bool {
340 switch expr := expr.(type) {
341 case *ast.BadExpr:
342 return true
343 case *ast.Ellipsis:
344 return MayHaveSideEffects(pass, expr.Elt, purity)
345 case *ast.FuncLit:
346 // the literal itself cannot have side effects, only calling it
347 // might, which is handled by CallExpr.
348 return false
349 case *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType:
350 // types cannot have side effects
351 return false
352 case *ast.BasicLit:
353 return false
354 case *ast.BinaryExpr:
355 return MayHaveSideEffects(pass, expr.X, purity) || MayHaveSideEffects(pass, expr.Y, purity)
356 case *ast.CallExpr:
357 if purity == nil {
358 return true
359 }
360 switch obj := typeutil.Callee(pass.TypesInfo, expr).(type) {
361 case *types.Func:
362 if _, ok := purity[obj]; !ok {
363 return true
364 }
365 case *types.Builtin:
366 switch obj.Name() {
367 case "len", "cap":
368 default:
369 return true
370 }
371 default:
372 return true
373 }
374 for _, arg := range expr.Args {
375 if MayHaveSideEffects(pass, arg, purity) {
376 return true
377 }
378 }
379 return false
380 case *ast.CompositeLit:
381 if MayHaveSideEffects(pass, expr.Type, purity) {
382 return true
383 }
384 for _, elt := range expr.Elts {
385 if MayHaveSideEffects(pass, elt, purity) {
386 return true
387 }
388 }
389 return false
390 case *ast.Ident:
391 return false
392 case *ast.IndexExpr:
393 return MayHaveSideEffects(pass, expr.X, purity) || MayHaveSideEffects(pass, expr.Index, purity)
394 case *ast.IndexListExpr:
395 // In theory, none of the checks are necessary, as IndexListExpr only involves types. But there is no harm in
396 // being safe.
397 if MayHaveSideEffects(pass, expr.X, purity) {
398 return true
399 }
400 for _, idx := range expr.Indices {
401 if MayHaveSideEffects(pass, idx, purity) {
402 return true
403 }
404 }
405 return false
406 case *ast.KeyValueExpr:
407 return MayHaveSideEffects(pass, expr.Key, purity) || MayHaveSideEffects(pass, expr.Value, purity)
408 case *ast.SelectorExpr:
409 return MayHaveSideEffects(pass, expr.X, purity)
410 case *ast.SliceExpr:
411 return MayHaveSideEffects(pass, expr.X, purity) ||
412 MayHaveSideEffects(pass, expr.Low, purity) ||
413 MayHaveSideEffects(pass, expr.High, purity) ||
414 MayHaveSideEffects(pass, expr.Max, purity)
415 case *ast.StarExpr:
416 return MayHaveSideEffects(pass, expr.X, purity)
417 case *ast.TypeAssertExpr:
418 return MayHaveSideEffects(pass, expr.X, purity)
419 case *ast.UnaryExpr:
420 if MayHaveSideEffects(pass, expr.X, purity) {
421 return true
422 }
423 return expr.Op == token.ARROW || expr.Op == token.AND
424 case *ast.ParenExpr:
425 return MayHaveSideEffects(pass, expr.X, purity)
426 case nil:
427 return false
428 default:
429 panic(fmt.Sprintf("internal error: unhandled type %T", expr))
430 }
431 }
432
433 // LanguageVersion returns the version of the Go language that node has access to. This
434 // might differ from the version of the Go standard library.
435 func LanguageVersion(pass *analysis.Pass, node Positioner) string {
436 // As of Go 1.21, two places can specify the minimum Go version:
437 // - 'go' directives in go.mod and go.work files
438 // - individual files by using '//go:build'
439 //
440 // Individual files can upgrade to a higher version than the module version. Individual files
441 // can also downgrade to a lower version, but only if the module version is at least Go 1.21.
442 //
443 // The restriction on downgrading doesn't matter to us. All language changes before Go 1.22 will
444 // not type-check on versions that are too old, and thus never reach our analyzes. In practice,
445 // such ineffective downgrading will always be useless, as the compiler will not restrict the
446 // language features used, and doesn't ever rely on minimum versions to restrict the use of the
447 // standard library. However, for us, both choices (respecting or ignoring ineffective
448 // downgrading) have equal complexity, but only respecting it has a non-zero chance of reducing
449 // noisy positives.
450 //
451 // The minimum Go versions are exposed via go/ast.File.GoVersion and go/types.Package.GoVersion.
452 // ast.File's version is populated by the parser, whereas types.Package's version is populated
453 // from the Go version specified in the types.Config, which is set by our package loader, based
454 // on the module information provided by go/packages, via 'go list -json'.
455 //
456 // As of Go 1.21, standard library packages do not present themselves as modules, and thus do
457 // not have a version set on their types.Package. In this case, we fall back to the version
458 // provided by our '-go' flag. In most cases, '-go' defaults to 'module', which falls back to
459 // the Go version that Staticcheck was built with when no module information exists. In the
460 // future, the standard library will hopefully be a proper module (see
461 // https://github.com/golang/go/issues/61174#issuecomment-1622471317). In that case, the version
462 // of standard library packages will match that of the used Go version. At that point,
463 // Staticcheck will refuse to work with Go versions that are too new, to avoid misinterpreting
464 // code due to language changes.
465 //
466 // We also lack module information when building in GOPATH mode. In this case, the implied
467 // language version is at most Go 1.21, as per https://github.com/golang/go/issues/60915. We
468 // don't handle this yet, and it will not matter until Go 1.22.
469 //
470 // It is not clear how per-file downgrading behaves in GOPATH mode. On the one hand, no module
471 // version at all is provided, which should preclude per-file downgrading. On the other hand,
472 // https://github.com/golang/go/issues/60915 suggests that the language version is at most 1.21
473 // in GOPATH mode, which would allow per-file downgrading. Again it doesn't affect us, as all
474 // relevant language changes before Go 1.22 will lead to type-checking failures and never reach
475 // us.
476 //
477 // Per-file upgrading is permitted in GOPATH mode.
478
479 // If the file has its own Go version, we will return that. Otherwise, we default to
480 // the type checker's GoVersion, which is populated from either the Go module, or from
481 // our '-go' flag.
482 return pass.TypesInfo.FileVersions[File(pass, node)]
483 }
484
485 // StdlibVersion returns the version of the Go standard library that node can expect to
486 // have access to. This might differ from the language version for versions of Go older
487 // than 1.21.
488 func StdlibVersion(pass *analysis.Pass, node Positioner) string {
489 // The Go version as specified in go.mod or via the '-go' flag
490 n := pass.Pkg.GoVersion()
491
492 f := File(pass, node)
493 if f == nil {
494 panic(fmt.Sprintf("no file found for node with position %s", pass.Fset.PositionFor(node.Pos(), false)))
495 }
496
497 if nf := f.GoVersion; nf != "" {
498 if version.Compare(n, "go1.21") == -1 {
499 // Before Go 1.21, the Go version set in go.mod specified the maximum language
500 // version available to the module. It wasn't uncommon to set the version to
501 // Go 1.20 but restrict usage of 1.20 functionality (both language and stdlib)
502 // to files tagged for 1.20, and supporting a lower version overall. As such,
503 // a file tagged lower than the module version couldn't expect to have access
504 // to the standard library of the version set in go.mod.
505 //
506 // At the same time, a file tagged higher than the module version, while not
507 // able to use newer language features, would still have been able to use a
508 // newer standard library.
509 //
510 // While Go 1.21's behavior has been backported to 1.19.11 and 1.20.6, users'
511 // expectations have not.
512 return nf
513 } else {
514 // Go 1.21 and newer refuse to build modules that depend on versions newer
515 // than the used version of the Go toolchain. This means that in a 1.22 module
516 // with a file tagged as 1.17, the file can expect to have access to 1.22's
517 // standard library (but not to 1.22 language features). A file tagged with a
518 // version higher than the minimum version has access to the newer standard
519 // library (and language features.)
520 //
521 // Do note that strictly speaking we're conflating the Go version and the
522 // module version in our check. Nothing is stopping a user from using Go 1.17
523 // (which didn't implement the new rules for versions in go.mod) to build a Go
524 // 1.22 module, in which case a file tagged with go1.17 will not have access to the 1.22
525 // standard library. However, we believe that if a module requires 1.21 or
526 // newer, then the author clearly expects the new behavior, and doesn't care
527 // for the old one. Otherwise they would've specified an older version.
528 //
529 // In other words, the module version also specifies what it itself actually means, with
530 // >=1.21 being a minimum version for the toolchain, and <1.21 being a maximum version for
531 // the language.
532
533 if version.Compare(nf, n) == 1 {
534 return nf
535 }
536 }
537 }
538
539 return n
540 }
541
542 var integerLiteralQ = pattern.MustParse(`(IntegerLiteral tv)`)
543
544 func IntegerLiteral(pass *analysis.Pass, node ast.Node) (types.TypeAndValue, bool) {
545 m, ok := Match(pass, integerLiteralQ, node)
546 if !ok {
547 return types.TypeAndValue{}, false
548 }
549 return m.State["tv"].(types.TypeAndValue), true
550 }
551
552 func IsIntegerLiteral(pass *analysis.Pass, node ast.Node, value constant.Value) bool {
553 tv, ok := IntegerLiteral(pass, node)
554 if !ok {
555 return false
556 }
557 return constant.Compare(tv.Value, token.EQL, value)
558 }
559
560 // IsMethod reports whether expr is a method call of a named method with signature meth.
561 // If name is empty, it is not checked.
562 // For now, method expressions (Type.Method(recv, ..)) are not considered method calls.
563 func IsMethod(pass *analysis.Pass, expr *ast.SelectorExpr, name string, meth *types.Signature) bool {
564 if name != "" && expr.Sel.Name != name {
565 return false
566 }
567 sel, ok := pass.TypesInfo.Selections[expr]
568 if !ok || sel.Kind() != types.MethodVal {
569 return false
570 }
571 return types.Identical(sel.Type(), meth)
572 }
573
574 func RefersTo(pass *analysis.Pass, expr ast.Expr, ident types.Object) bool {
575 found := false
576 fn := func(node ast.Node) bool {
577 ident2, ok := node.(*ast.Ident)
578 if !ok {
579 return true
580 }
581 if ident == pass.TypesInfo.ObjectOf(ident2) {
582 found = true
583 return false
584 }
585 return true
586 }
587 ast.Inspect(expr, fn)
588 return found
589 }