Debian Codegraph @

go/analysis/passes/modernize/errorsastype.go

raw symbols SCIP
1 // Copyright 2025 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 "go/ast"
9 "go/token"
10 "go/types"
11
12 "fmt"
13
14 "golang.org/x/tools/go/analysis"
15 "golang.org/x/tools/go/ast/edge"
16 "golang.org/x/tools/go/ast/inspector"
17 "golang.org/x/tools/internal/analysis/analyzerutil"
18 typeindexanalyzer "golang.org/x/tools/internal/analysis/typeindex"
19 "golang.org/x/tools/internal/astutil"
20 "golang.org/x/tools/internal/moreiters"
21 "golang.org/x/tools/internal/refactor"
22 "golang.org/x/tools/internal/typesinternal"
23 "golang.org/x/tools/internal/typesinternal/typeindex"
24 "golang.org/x/tools/internal/versions"
25 )
26
27 var ErrorsAsTypeAnalyzer = &analysis.Analyzer{
28 Name: "errorsastype",
29 Doc: analyzerutil.MustExtractDoc(doc, "errorsastype"),
30 URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize#errorsastype",
31 Requires: []*analysis.Analyzer{typeindexanalyzer.Analyzer},
32 Run: errorsastype,
33 }
34
35 // errorsastype offers a fix to replace error.As with the newer
36 // errors.AsType[T] following this pattern:
37 //
38 // var myerr *MyErr
39 // if errors.As(err, &myerr) { ... }
40 //
41 // =>
42 //
43 // if myerr, ok := errors.AsType[*MyErr](err); ok { ... }
44 //
45 // (In principle several of these can then be chained using if/else,
46 // but we don't attempt that.)
47 //
48 // We offer the fix only within an if statement, but not within a
49 // switch case such as:
50 //
51 // var myerr *MyErr
52 // switch {
53 // case errors.As(err, &myerr):
54 // }
55 //
56 // because the transformation in that case would be ungainly.
57 //
58 // For the negated case (!errors.As), we use !ok instead.
59 //
60 // Note that the cmd/vet suite includes the "errorsas" analyzer, which
61 // detects actual mistakes in the use of errors.As. This logic does
62 // not belong in errorsas because the problems it fixes are merely
63 // stylistic.
64 //
65 // TODO(adonovan): support more cases:
66 // - if myerr := new(E); errors.As(err, myerr); { ... }
67 // - if errors.As(err, myerr) && othercond { ... }
68 func errorsastype(pass *analysis.Pass) (any, error) {
69 var (
70 index = pass.ResultOf[typeindexanalyzer.Analyzer].(*typeindex.Index)
71 info = pass.TypesInfo
72 )
73
74 for curCall := range index.Calls(index.Object("errors", "As")) {
75 call := curCall.Node().(*ast.CallExpr)
76 if len(call.Args) < 2 {
77 continue // spread call: errors.As(pair())
78 }
79
80 v, curDeclStmt, curIfStmt := canUseErrorsAsType(info, index, curCall)
81 if v == nil {
82 continue
83 }
84
85 file := astutil.EnclosingFile(curDeclStmt)
86 if !analyzerutil.FileUsesGoVersion(pass, file, versions.Go1_26) {
87 continue // errors.AsType is too new
88 }
89
90 // Locate identifier "As" in errors.As.
91 var asIdent *ast.Ident
92 switch n := ast.Unparen(call.Fun).(type) {
93 case *ast.Ident:
94 asIdent = n // "errors" was dot-imported
95 case *ast.SelectorExpr:
96 asIdent = n.Sel
97 default:
98 panic("no Ident for errors.As")
99 }
100
101 // Format the type as valid Go syntax.
102 // TODO(adonovan): fix: FileQualifier needs to respect
103 // visibility at the current point, and either fail
104 // or edit the imports as needed.
105 // TODO(adonovan): fix: TypeString is not a sound way
106 // to print types as Go syntax as it does not respect
107 // symbol visibility, etc. We need something loosely
108 // integrated with FileQualifier that accumulates
109 // import edits, and may fail (e.g. for unexported
110 // type or field names from other packages).
111 // See https://go.dev/issues/75604.
112 qual := typesinternal.FileQualifier(file, pass.Pkg)
113 errtype := types.TypeString(v.Type(), qual)
114
115 // Choose a name for the "ok" variable.
116 // We generate a new name only if 'ok' is already declared at
117 // curCall and it also used within the if-statement.
118 ifScope := info.Scopes[curIfStmt.Node().(*ast.IfStmt)]
119 negated := curCall.ParentEdgeKind() == edge.UnaryExpr_X // bool => Tok==NOT
120 okName := freshName(info, index, ifScope, v.Pos(), curCall, curIfStmt, token.NoPos, "ok")
121 // Because we reject any use of v outside the if statement, any use besides
122 // the argument in errors.As must lie inside the if statement.
123 usesV := moreiters.Len(index.Uses(v)) > 1
124
125 edits := append(
126 // delete "var myerr *MyErr"
127 refactor.DeleteStmt(pass.Fset.File(call.Fun.Pos()), curDeclStmt),
128 // if errors.As (err, &myerr) { ... }
129 // ------------- -------------- -------- ----
130 // if myerr, ok := errors.AsType[*MyErr](err ); ok { ... }
131 analysis.TextEdit{
132 // Insert "myerr, ok := " if myerr is used inside the if statement.
133 // Otherwise insert "_, ok := ".
134 Pos: call.Pos(),
135 End: call.Pos(),
136 NewText: fmt.Appendf(nil, "%s, %s := ", cond(usesV, v.Name(), "_"), okName),
137 },
138 analysis.TextEdit{
139 // replace As with AsType[T]
140 Pos: asIdent.Pos(),
141 End: asIdent.End(),
142 NewText: fmt.Appendf(nil, "AsType[%s]", errtype),
143 },
144 analysis.TextEdit{
145 // delete ", &myerr"
146 Pos: call.Args[0].End(),
147 End: call.Args[1].End(),
148 },
149 analysis.TextEdit{
150 // insert "; ok" for errors.AsType or "; !ok" for !errors.AsType
151 Pos: call.End(),
152 End: call.End(),
153 NewText: fmt.Appendf(nil, "; %s%s", cond(negated, "!", ""), okName),
154 },
155 )
156 if negated {
157 unaryExpr := curCall.Parent().Node().(*ast.UnaryExpr)
158 // delete "!"
159 edits = append(edits, analysis.TextEdit{
160 Pos: unaryExpr.OpPos,
161 End: unaryExpr.X.Pos(),
162 })
163 }
164
165 pass.Report(analysis.Diagnostic{
166 Pos: call.Fun.Pos(),
167 End: call.Fun.End(),
168 Message: fmt.Sprintf("errors.As can be simplified using AsType[%s]", errtype),
169 SuggestedFixes: []analysis.SuggestedFix{{
170 Message: fmt.Sprintf("Replace errors.As with AsType[%s]", errtype),
171 TextEdits: edits,
172 }},
173 })
174 }
175 return nil, nil
176 }
177
178 // canUseErrorsAsType reports whether curCall is a call to errors.As beneath an
179 // if statement, preceded by a declaration of the typed error var. The var must
180 // not be used outside the if statement.
181 // If the conditions are met, it returns the error var, the cursor for its
182 // DeclStmt, and the cursor for the IfStmt that contains the call to errors.As.
183 // Otherwise it returns a nil error var.
184 func canUseErrorsAsType(info *types.Info, index *typeindex.Index, curCall inspector.Cursor) (_ *types.Var, curDeclStmt, curIfStmt inspector.Cursor) {
185 curCond := curCall
186 if curCond.ParentEdgeKind() == edge.UnaryExpr_X { // if !errors.As(err, &v)
187 curCond = curCond.Parent()
188 }
189 if curCond.ParentEdgeKind() != edge.IfStmt_Cond {
190 return // not beneath if or unaryexpr
191 }
192 curIfStmt = curCond.Parent()
193 ifStmt := curIfStmt.Node().(*ast.IfStmt)
194 if ifStmt.Init != nil {
195 return // if statement already has an init part
196 }
197 unary, ok := curCall.Node().(*ast.CallExpr).Args[1].(*ast.UnaryExpr)
198 if !ok || unary.Op != token.AND {
199 return // 2nd arg is not &var
200 }
201 id, ok := unary.X.(*ast.Ident)
202 if !ok {
203 return // not a simple ident (local var)
204 }
205 v := info.Uses[id].(*types.Var)
206 curDef, ok := index.Def(v)
207 if !ok {
208 return // var is not local (e.g. dot-imported)
209 }
210 // Have: if errors.As(err, &v) { ... }
211
212 // Reject if v is used outside (before or after) the
213 // IfStmt, since that will become its new scope.
214 for curUse := range index.Uses(v) {
215 if !curIfStmt.Contains(curUse) {
216 return // v used before/after if statement
217 }
218 }
219 if curDef.ParentEdgeKind() != edge.ValueSpec_Names {
220 return // v not declared by "var v T"
221 }
222 var (
223 curSpec = curDef.Parent() // ValueSpec
224 curDecl = curSpec.Parent() // GenDecl
225 spec = curSpec.Node().(*ast.ValueSpec)
226 )
227 if len(spec.Names) != 1 || len(spec.Values) != 0 ||
228 len(curDecl.Node().(*ast.GenDecl).Specs) != 1 {
229 return // not a simple "var v T" decl
230 }
231
232 // Have:
233 // var v *MyErr
234 // ...
235 // if errors.As(err, &v) { ... }
236 // with no uses of v outside the IfStmt.
237 return v, curDecl.Parent(), curIfStmt // curDecl.Parent() is a DeclStmt
238 }