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