Debian Codegraph @

go/analysis/passes/modernize/modernize.go

raw symbols SCIP
1 // Copyright 2024 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 package modernize
6
7 import (
8 _ "embed"
9 "go/ast"
10 "go/constant"
11 "go/format"
12 "go/token"
13 "go/types"
14 "iter"
15 "regexp"
16 "strings"
17
18 "golang.org/x/tools/go/analysis"
19 "golang.org/x/tools/go/analysis/passes/inspect"
20 "golang.org/x/tools/go/ast/inspector"
21 "golang.org/x/tools/internal/analysis/analyzerutil"
22 "golang.org/x/tools/internal/refactor"
23 "golang.org/x/tools/internal/typesinternal/typeindex"
24
25 "golang.org/x/tools/internal/moreiters"
26 "golang.org/x/tools/internal/packagepath"
27 "golang.org/x/tools/internal/stdlib"
28 "golang.org/x/tools/internal/typesinternal"
29 )
30
31 //go:embed doc.go
32 var doc string
33
34 // Suite lists all modernize analyzers.
35 var Suite = []*analysis.Analyzer{
36 AnyAnalyzer,
37 AtomicTypesAnalyzer,
38 EmbedLitAnalyzer,
39 ErrorsAsTypeAnalyzer,
40 ForVarAnalyzer,
41 MapsLoopAnalyzer,
42 MinMaxAnalyzer,
43 NewExprAnalyzer,
44 OmitZeroAnalyzer,
45 PlusBuildAnalyzer,
46 RangeIntAnalyzer,
47 ReflectTypeForAnalyzer,
48 slicesBackwardAnalyzer, // awaiting public symbol
49 SlicesContainsAnalyzer,
50 SlicesSortAnalyzer,
51 StdIteratorsAnalyzer,
52 StringsCutAnalyzer,
53 StringsCutPrefixAnalyzer,
54 StringsSeqAnalyzer,
55 StringsBuilderAnalyzer,
56 TestingContextAnalyzer,
57 unsafeFuncsAnalyzer, // awaiting public symbol
58 WaitGroupGoAnalyzer,
59
60 // Not included:
61 //
62 // AppendClippedAnalyzer, // not nil-preserving
63 // BLoopAnalyzer, // may skew benchmark results, see golang/go#74967
64 // FmtAppendfAnalyzer, // makes code less clear, see golang/go#77581
65 // SlicesDeleteAnalyzer, // not nil-preserving
66 }
67
68 // -- helpers --
69
70 // formatExprs formats a comma-separated list of expressions.
71 func formatExprs(fset *token.FileSet, exprs []ast.Expr) string {
72 var buf strings.Builder
73 for i, e := range exprs {
74 if i > 0 {
75 buf.WriteString(", ")
76 }
77 format.Node(&buf, fset, e) // ignore errors
78 }
79 return buf.String()
80 }
81
82 // isZeroIntConst reports whether e is an integer whose value is 0.
83 func isZeroIntConst(info *types.Info, e ast.Expr) bool {
84 return isIntLiteral(info, e, 0)
85 }
86
87 // isIntLiteral reports whether e is an integer with given value.
88 func isIntLiteral(info *types.Info, e ast.Expr, n int64) bool {
89 return info.Types[e].Value == constant.MakeInt64(n)
90 }
91
92 // isInteger reports whether t is an integer type.
93 func isInteger(t types.Type) bool {
94 basic, ok := t.Underlying().(*types.Basic)
95 return ok && basic.Info()&types.IsInteger != 0
96 }
97
98 // filesUsingGoVersion returns a cursor for each *ast.File in the inspector
99 // that uses at least the specified version of Go (e.g. "go1.24").
100 //
101 // The pass's analyzer must require [inspect.Analyzer].
102 //
103 // TODO(adonovan): opt: eliminate this function, instead following the
104 // approach of [fmtappendf], which uses typeindex and
105 // [analyzerutil.FileUsesGoVersion]; see "Tip" documented at the
106 // latter function for motivation.
107 func filesUsingGoVersion(pass *analysis.Pass, version string) iter.Seq[inspector.Cursor] {
108 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
109
110 return func(yield func(inspector.Cursor) bool) {
111 for curFile := range inspect.Root().Children() {
112 file := curFile.Node().(*ast.File)
113 if analyzerutil.FileUsesGoVersion(pass, file, version) && !yield(curFile) {
114 break
115 }
116 }
117 }
118 }
119
120 // within reports whether the current pass is analyzing one of the
121 // specified standard packages or their dependencies.
122 func within(pass *analysis.Pass, pkgs ...string) bool {
123 path := pass.Pkg.Path()
124 return packagepath.IsStdPackage(path) &&
125 moreiters.Contains(stdlib.Dependencies(pkgs...), path)
126 }
127
128 var (
129 builtinAny = types.Universe.Lookup("any")
130 builtinAppend = types.Universe.Lookup("append")
131 builtinBool = types.Universe.Lookup("bool")
132 builtinInt = types.Universe.Lookup("int")
133 builtinFalse = types.Universe.Lookup("false")
134 builtinLen = types.Universe.Lookup("len")
135 builtinMake = types.Universe.Lookup("make")
136 builtinNew = types.Universe.Lookup("new")
137 builtinNil = types.Universe.Lookup("nil")
138 builtinString = types.Universe.Lookup("string")
139 builtinTrue = types.Universe.Lookup("true")
140 byteSliceType = types.NewSlice(types.Typ[types.Byte])
141 omitemptyRegex = regexp.MustCompile(`(?:^json| json):"[^"]*(,omitempty)(?:"|,[^"]*")\s?`)
142 )
143
144 // lookup returns the symbol denoted by name at the position of the cursor.
145 func lookup(info *types.Info, cur inspector.Cursor, name string) types.Object {
146 scope := typesinternal.EnclosingScope(info, cur)
147 _, obj := scope.LookupParent(name, cur.Node().Pos())
148 return obj
149 }
150
151 func first[T any](x T, _ any) T { return x }
152
153 // freshName returns a fresh name at the given pos and scope based on preferredName.
154 // It generates a new name using refactor.FreshName only if:
155 // (a) the preferred name is already defined at definedCur, and
156 // (b) there are references to it from within usedCur.
157 // If useAfterPos.IsValid(), the references must be after
158 // useAfterPos within usedCur in order to warrant a fresh name.
159 // Otherwise, it returns preferredName, since shadowing is valid in this case.
160 // (declaredCur and usedCur may be identical in some use cases).
161 func freshName(info *types.Info, index *typeindex.Index, scope *types.Scope, pos token.Pos, defCur inspector.Cursor, useCur inspector.Cursor, useAfterPos token.Pos, preferredName string) string {
162 obj := lookup(info, defCur, preferredName)
163 if obj == nil {
164 // preferredName has not been declared here.
165 return preferredName
166 }
167 for use := range index.Uses(obj) {
168 if useCur.Contains(use) && use.Node().Pos() >= useAfterPos {
169 return refactor.FreshName(scope, pos, preferredName)
170 }
171 }
172 // Name is taken but not used in the given block; shadowing is acceptable.
173 return preferredName
174 }
175
176 // isLocal reports whether obj is local to some function.
177 // Precondition: not a struct field or interface method.
178 func isLocal(obj types.Object) bool {
179 // [... 5=stmt 4=func 3=file 2=pkg 1=universe]
180 var depth int
181 for scope := obj.Parent(); scope != nil; scope = scope.Parent() {
182 depth++
183 }
184 return depth >= 4
185 }