Debian Codegraph @

gopls/internal/golang/inline.go

raw symbols SCIP
1 // Copyright 2023 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 golang
6
7 // This file defines the refactor.inline code action.
8
9 import (
10 "context"
11 "fmt"
12 "go/ast"
13 "go/token"
14 "go/types"
15
16 "golang.org/x/tools/go/analysis"
17 goastutil "golang.org/x/tools/go/ast/astutil"
18 "golang.org/x/tools/go/ast/edge"
19 "golang.org/x/tools/go/ast/inspector"
20 "golang.org/x/tools/go/types/typeutil"
21 "golang.org/x/tools/gopls/internal/cache"
22 "golang.org/x/tools/gopls/internal/cache/parsego"
23 "golang.org/x/tools/gopls/internal/util/safetoken"
24 "golang.org/x/tools/internal/astutil"
25 "golang.org/x/tools/internal/event"
26 "golang.org/x/tools/internal/refactor/inline"
27 )
28
29 // enclosingStaticCall returns the innermost function call enclosing
30 // the selected range, along with the callee.
31 func enclosingStaticCall(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*ast.CallExpr, *types.Func, error) {
32 // TODO(adonovan): simplify using pgf.Cursor
33 path, _ := goastutil.PathEnclosingInterval(pgf.File, start, end)
34
35 var call *ast.CallExpr
36 loop:
37 for _, n := range path {
38 switch n := n.(type) {
39 case *ast.FuncLit:
40 break loop
41 case *ast.CallExpr:
42 call = n
43 break loop
44 }
45 }
46 if call == nil {
47 return nil, nil, fmt.Errorf("no enclosing call")
48 }
49 if safetoken.Line(pgf.Tok, call.Lparen) != safetoken.Line(pgf.Tok, start) {
50 return nil, nil, fmt.Errorf("enclosing call is not on this line")
51 }
52 fn := typeutil.StaticCallee(pkg.TypesInfo(), call)
53 if fn == nil {
54 return nil, nil, fmt.Errorf("not a static call to a Go function")
55 }
56 return call, fn, nil
57 }
58
59 func inlineCall(ctx context.Context, snapshot *cache.Snapshot, callerPkg *cache.Package, callerPGF *parsego.File, start, end token.Pos) (_ *token.FileSet, _ *analysis.SuggestedFix, err error) {
60 countInlineCall.Inc()
61 // Find enclosing static call.
62 call, fn, err := enclosingStaticCall(callerPkg, callerPGF, start, end)
63 if err != nil {
64 return nil, nil, err
65 }
66
67 calleePkg, calleePGF, calleePos, err := NarrowestDeclaringPackage(ctx, snapshot, callerPkg, fn)
68 if err != nil {
69 return nil, nil, err
70 }
71
72 var calleeDecl *ast.FuncDecl
73 for _, decl := range calleePGF.File.Decls {
74 funcDecl, ok := decl.(*ast.FuncDecl)
75 if !ok {
76 continue
77 }
78 if funcDecl.Name.Pos() == calleePos {
79 calleeDecl = funcDecl
80 break
81 }
82 }
83 if calleeDecl == nil {
84 return nil, nil, fmt.Errorf("can't find callee")
85 }
86
87 // The inliner assumes that input is well-typed,
88 // but that is frequently not the case within gopls.
89 // Until we are able to harden the inliner,
90 // report panics as errors to avoid crashing the server.
91 bad := func(p *cache.Package) bool { return len(p.ParseErrors())+len(p.TypeErrors()) > 0 }
92 if bad(calleePkg) || bad(callerPkg) {
93 defer func() {
94 if x := recover(); x != nil {
95 err = fmt.Errorf("inlining failed (%q), likely because inputs were ill-typed", x)
96 }
97 }()
98 }
99
100 // Users can consult the gopls event log to see
101 // why a particular inlining strategy was chosen.
102 logf := logger(ctx, "inliner", snapshot.Options().VerboseOutput)
103
104 callee, err := inline.AnalyzeCallee(logf, calleePkg.FileSet(), calleePkg.Types(), calleePkg.TypesInfo(), calleeDecl, calleePGF.Src)
105 if err != nil {
106 return nil, nil, err
107 }
108
109 // Inline the call.
110 caller := &inline.Caller{
111 Fset: callerPkg.FileSet(),
112 Types: callerPkg.Types(),
113 Info: callerPkg.TypesInfo(),
114 File: callerPGF.File,
115 Call: call,
116 CountUses: nil, // (use inefficient default implementation)
117 }
118
119 res, err := inline.Inline(caller, callee, &inline.Options{Logf: logf})
120 if err != nil {
121 return nil, nil, err
122 }
123
124 return callerPkg.FileSet(), &analysis.SuggestedFix{
125 Message: fmt.Sprintf("inline call of %v", callee),
126 TextEdits: res.Edits,
127 }, nil
128 }
129
130 // TODO(adonovan): change the inliner to instead accept an io.Writer.
131 func logger(ctx context.Context, name string, verbose bool) func(format string, args ...any) {
132 if verbose {
133 return func(format string, args ...any) {
134 event.Log(ctx, name+": "+fmt.Sprintf(format, args...))
135 }
136 } else {
137 return func(string, ...any) {}
138 }
139 }
140
141 // canInlineVariable reports whether the selection is within an
142 // identifier that is a use of a variable that has an initializer
143 // expression. If so, it returns cursors for the identifier and the
144 // initializer expression.
145 func canInlineVariable(info *types.Info, curFile inspector.Cursor, start, end token.Pos) (_, _ inspector.Cursor, ok bool) {
146 if curUse, ok := curFile.FindByPos(start, end); ok {
147 if id, ok := curUse.Node().(*ast.Ident); ok && !isLvalueUse(curUse, info) {
148 if v, ok := info.Uses[id].(*types.Var); ok && v.Kind() == types.LocalVar {
149 if curIdent, ok := curFile.FindByPos(v.Pos(), v.Pos()); ok {
150 curParent := curIdent.Parent()
151 kind, index := curIdent.ParentEdge()
152 switch kind {
153 case edge.ValueSpec_Names:
154 // var v = expr
155 spec := curParent.Node().(*ast.ValueSpec)
156 if len(spec.Names) == len(spec.Values) {
157 return curUse, curParent.ChildAt(edge.ValueSpec_Values, index), true
158 }
159 case edge.AssignStmt_Lhs:
160 // v := expr
161 stmt := curParent.Node().(*ast.AssignStmt)
162 if len(stmt.Lhs) == len(stmt.Rhs) {
163 return curUse, curParent.ChildAt(edge.AssignStmt_Rhs, index), true
164 }
165 }
166 }
167 }
168 }
169 }
170 return
171 }
172
173 // isLvalueUse reports whether the "use" identifier represented by cur
174 // appears in an l-value context such as:
175 //
176 // - v=...
177 // - v++
178 // - &v
179 // - v.f(), when this implicitly takes the address of v.
180 func isLvalueUse(cur inspector.Cursor, info *types.Info) bool {
181 cur = unparenEnclosing(cur)
182
183 switch cur.ParentEdgeKind() {
184 case edge.AssignStmt_Lhs, edge.IncDecStmt_X:
185 return true // v=..., v++
186
187 case edge.UnaryExpr_X:
188 return cur.Parent().Node().(*ast.UnaryExpr).Op == token.AND // &v
189
190 case edge.SelectorExpr_X:
191 sel := cur.Parent().Node().(*ast.SelectorExpr)
192 isPointer := func(t types.Type) bool {
193 return is[*types.Pointer](t)
194 }
195 if seln, ok := info.Selections[sel]; ok && seln.Kind() == types.MethodVal {
196 // Have: recv.f() method call
197 methodRecv := seln.Obj().(*types.Func).Signature().Recv().Type()
198 return !seln.Indirect() && isPointer(methodRecv) && !isPointer(info.TypeOf(sel.X))
199 }
200 }
201
202 return false
203 }
204
205 // unparenEnclosing removes enclosing parens from cur in
206 // preparation for a call to [Cursor.ParentEdge].
207 func unparenEnclosing(cur inspector.Cursor) inspector.Cursor {
208 for cur.ParentEdgeKind() == edge.ParenExpr_X {
209 cur = cur.Parent()
210 }
211 return cur
212 }
213
214 // inlineVariableOne computes a fix to replace the selected variable by
215 // its initialization expression.
216 func inlineVariableOne(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) {
217 countInlineVariable.Inc()
218 info := pkg.TypesInfo()
219 curUse, curRHS, ok := canInlineVariable(info, pgf.Cursor(), start, end)
220 if !ok {
221 return nil, nil, fmt.Errorf("cannot inline variable here")
222 }
223
224 // Check that free symbols of rhs are unshadowed at curUse.
225 var (
226 use = curUse.Node().(*ast.Ident)
227 rhs = curRHS.Node().(ast.Expr)
228 pos = use.Pos()
229 scope = info.Scopes[pgf.File].Innermost(pos)
230 )
231 for curIdent := range curRHS.Preorder((*ast.Ident)(nil)) {
232 if curIdent.ParentEdgeKind() == edge.SelectorExpr_Sel {
233 continue // ignore f in x.f
234 }
235 id := curIdent.Node().(*ast.Ident)
236 obj1 := info.Uses[id]
237 if obj1 == nil {
238 continue // undefined; or a def, not a use
239 }
240 if v, ok := obj1.(*types.Var); ok && v.IsField() {
241 continue // a field reference T{F: 0} is non-lexical
242 }
243 if astutil.NodeContainsPos(rhs, obj1.Pos()) {
244 continue // not free (id is defined within RHS)
245 }
246 _, obj2 := scope.LookupParent(id.Name, pos)
247 // Inv: obj2 is non-nil.
248 if obj1 != obj2 {
249 return nil, nil, fmt.Errorf("cannot inline variable: its initializer expression refers to %q, which is shadowed by the declaration at line %d", id.Name, safetoken.Position(pgf.Tok, obj2.Pos()).Line)
250 }
251 }
252
253 // TODO(adonovan): also reject variables that are updated by assignments?
254
255 // Add parens to 'new' as needed by the 'use' context.
256 rhs = astutil.MaybeParenthesize(curUse.Parent().Node(), use, rhs)
257
258 return pkg.FileSet(), &analysis.SuggestedFix{
259 Message: fmt.Sprintf("Replace variable %q by its initializer expression", use.Name),
260 TextEdits: []analysis.TextEdit{
261 {
262 Pos: use.Pos(),
263 End: use.End(),
264 NewText: []byte(FormatNode(pkg.FileSet(), rhs)),
265 },
266 },
267 }, nil
268 }