Debian Codegraph @

gopls/internal/golang/inline_all.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 import (
8 "context"
9 "fmt"
10 "go/ast"
11 "go/parser"
12 "go/types"
13
14 "golang.org/x/tools/go/ast/astutil"
15 "golang.org/x/tools/go/types/typeutil"
16 "golang.org/x/tools/gopls/internal/cache"
17 "golang.org/x/tools/gopls/internal/cache/parsego"
18 "golang.org/x/tools/gopls/internal/protocol"
19 "golang.org/x/tools/gopls/internal/util/bug"
20 "golang.org/x/tools/internal/analysis/driverutil"
21 "golang.org/x/tools/internal/diff"
22 "golang.org/x/tools/internal/refactor"
23 "golang.org/x/tools/internal/refactor/inline"
24 )
25
26 // inlineAllCalls inlines all calls to the original function declaration
27 // described by callee, returning the resulting modified file content.
28 //
29 // inlining everything is currently an expensive operation: it involves re-type
30 // checking every package that contains a potential call, as reported by
31 // References. In cases where there are multiple calls per file, inlineAllCalls
32 // must type check repeatedly for each additional call.
33 //
34 // The provided post processing function is applied to the resulting source
35 // after each transformation. This is necessary because we are using this
36 // function to inline synthetic wrappers for the purpose of signature
37 // rewriting. The delegated function has a fake name that doesn't exist in the
38 // snapshot, and so we can't re-type check until we replace this fake name.
39 //
40 // TODO(rfindley): this only works because removing a parameter is a very
41 // narrow operation. A better solution would be to allow for ad-hoc snapshots
42 // that expose the full machinery of real snapshots: minimal invalidation,
43 // batched type checking, etc. Then we could actually rewrite the declaring
44 // package in this snapshot (and so 'post' would not be necessary), and could
45 // robustly re-type check for the purpose of iterative inlining, even if the
46 // inlined code pulls in new imports that weren't present in export data.
47 //
48 // The code below notes where are assumptions are made that only hold true in
49 // the case of parameter removal (annotated with 'Assumption:')
50 func inlineAllCalls(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, origDecl *ast.FuncDecl, callee *inline.Callee, post func([]byte) []byte, opts *inline.Options) (_ map[protocol.DocumentURI][]byte, inlineErr error) {
51 // Collect references.
52 var refs []protocol.Location
53 {
54 funcRng, err := pgf.Mapper.PosRange(pgf.Tok, origDecl.Name.NamePos, origDecl.Name.NamePos)
55 if err != nil {
56 return nil, err
57 }
58 fh, err := snapshot.ReadFile(ctx, pgf.URI)
59 if err != nil {
60 return nil, err
61 }
62 refs, err = References(ctx, snapshot, fh, funcRng, false)
63 if err != nil {
64 return nil, fmt.Errorf("finding references to rewrite: %v", err)
65 }
66 }
67
68 // Type-check the narrowest package containing each reference.
69 // TODO(rfindley): we should expose forEachPackage in order to operate in
70 // parallel and to reduce peak memory for this operation.
71 var (
72 pkgForRef = make(map[protocol.Location]PackageID)
73 pkgs = make(map[PackageID]*cache.Package)
74 // The inliner assumes that input is well-typed, but that is frequently not
75 // the case within gopls.
76 // Until we're able to harden the inliner, report panics as errors to avoid
77 // crashing the server.
78 badPkg = false
79 )
80 {
81 needPkgs := make(map[PackageID]struct{})
82 for _, ref := range refs {
83 md, err := snapshot.NarrowestMetadataForFile(ctx, ref.URI)
84 if err != nil {
85 return nil, fmt.Errorf("finding ref metadata: %v", err)
86 }
87 pkgForRef[ref] = md.ID
88 needPkgs[md.ID] = struct{}{}
89 }
90 var pkgIDs []PackageID
91 for id := range needPkgs { // TODO: use maps.Keys once it is available to us
92 pkgIDs = append(pkgIDs, id)
93 }
94
95 refPkgs, err := snapshot.TypeCheck(ctx, pkgIDs...)
96 if err != nil {
97 return nil, fmt.Errorf("type checking reference packages: %v", err)
98 }
99
100 for _, p := range refPkgs {
101 pkgs[p.Metadata().ID] = p
102 if len(p.ParseErrors())+len(p.TypeErrors()) > 0 {
103 badPkg = true
104 }
105 }
106 }
107
108 if badPkg {
109 defer func() {
110 if x := recover(); x != nil {
111 inlineErr = fmt.Errorf("inlining failed (%q), likely because inputs were ill-typed", x)
112 }
113 }()
114 }
115
116 // Organize calls by top file declaration. Calls within a single file may
117 // affect each other, as the inlining edit may affect the surrounding scope
118 // or imports Therefore, when inlining subsequent calls in the same
119 // declaration, we must re-type check.
120
121 type fileCalls struct {
122 pkg *cache.Package
123 pgf *parsego.File
124 calls []*ast.CallExpr
125 }
126
127 refsByFile := make(map[protocol.DocumentURI]*fileCalls)
128 for _, ref := range refs {
129 refpkg := pkgs[pkgForRef[ref]]
130 pgf, err := refpkg.File(ref.URI)
131 if err != nil {
132 return nil, bug.Errorf("finding %s in %s: %v", ref.URI, refpkg.Metadata().ID, err)
133 }
134
135 start, end, err := pgf.RangePos(ref.Range)
136 if err != nil {
137 return nil, err // e.g. invalid range
138 }
139
140 // Look for the surrounding call expression.
141 var (
142 name *ast.Ident
143 call *ast.CallExpr
144 )
145 path, _ := astutil.PathEnclosingInterval(pgf.File, start, end)
146 name, _ = path[0].(*ast.Ident)
147
148 // TODO(rfindley): handle method expressions correctly.
149 if _, ok := path[1].(*ast.SelectorExpr); ok {
150 call, _ = path[2].(*ast.CallExpr)
151 } else {
152 call, _ = path[1].(*ast.CallExpr)
153 }
154 if name == nil || call == nil {
155 // TODO(rfindley): handle this case with eta-abstraction:
156 // a reference to the target function f in a non-call position
157 // use(f)
158 // is replaced by
159 // use(func(...) { f(...) })
160 return nil, fmt.Errorf("cannot inline: found non-call function reference %v", ref)
161 }
162
163 // Heuristic: ignore references that overlap with type checker errors, as they may
164 // lead to invalid results (see golang/go#70268).
165 hasTypeErrors := false
166 for _, typeErr := range refpkg.TypeErrors() {
167 if call.Lparen <= typeErr.Pos && typeErr.Pos <= call.Rparen {
168 hasTypeErrors = true
169 }
170 }
171
172 if hasTypeErrors {
173 continue
174 }
175
176 if typeutil.StaticCallee(refpkg.TypesInfo(), call) == nil {
177 continue // dynamic call
178 }
179
180 // Sanity check.
181 if obj := refpkg.TypesInfo().ObjectOf(name); obj == nil ||
182 obj.Name() != origDecl.Name.Name ||
183 obj.Pkg() == nil ||
184 obj.Pkg().Path() != string(pkg.Metadata().PkgPath) {
185
186 return nil, bug.Errorf("cannot inline: corrupted reference %v", ref)
187 }
188
189 callInfo, ok := refsByFile[ref.URI]
190 if !ok {
191 callInfo = &fileCalls{
192 pkg: refpkg,
193 pgf: pgf,
194 }
195 refsByFile[ref.URI] = callInfo
196 }
197 callInfo.calls = append(callInfo.calls, call)
198 }
199
200 // Inline each call within the same decl in sequence, re-typechecking after
201 // each one. If there is only a single call within the decl, we can avoid
202 // additional type checking.
203 //
204 // Assumption: inlining does not affect the package scope, so we can operate
205 // on separate files independently.
206 result := make(map[protocol.DocumentURI][]byte)
207 for uri, callInfo := range refsByFile {
208 var (
209 calls = callInfo.calls
210 fset = callInfo.pkg.FileSet()
211 tpkg = callInfo.pkg.Types()
212 tinfo = callInfo.pkg.TypesInfo()
213 file = callInfo.pgf.File
214 content = callInfo.pgf.Src
215 )
216
217 // Check for overlapping calls (such as Foo(Foo())). We can't handle these
218 // because inlining may change the source order of the inner call with
219 // respect to the inlined outer call, and so the heuristic we use to find
220 // the next call (counting from top-to-bottom) does not work.
221 for i := range calls {
222 if i > 0 && calls[i-1].End() > calls[i].Pos() {
223 return nil, fmt.Errorf("%s: can't inline overlapping call %s", uri, types.ExprString(calls[i-1]))
224 }
225 }
226
227 currentCall := 0
228 for currentCall < len(calls) {
229 caller := &inline.Caller{
230 Fset: fset,
231 Types: tpkg,
232 Info: tinfo,
233 File: file,
234 Call: calls[currentCall],
235 CountUses: nil, // TODO(adonovan): opt: amortize across callInfo.pkg
236 }
237 res, err := inline.Inline(caller, callee, opts)
238 if err != nil {
239 return nil, fmt.Errorf("inlining failed: %v", err)
240 }
241
242 // applyEdits transforms content by applying the specified edits
243 // (whose positions are defined by fset), reformatting the file, and
244 // removing unused imports (using pkg for names of imported packages).
245 // (Adapted from inline_test.applyEdits.)
246 applyEdits := func(content []byte, edits []refactor.Edit) ([]byte, error) {
247 dedits := make([]diff.Edit, len(edits))
248 for i, edit := range edits {
249 dedits[i] = diff.Edit{
250 Start: int(edit.Pos - file.FileStart),
251 End: int(edit.End - file.FileStart),
252 New: string(edit.NewText),
253 }
254 }
255 got, err := diff.ApplyBytes(content, dedits)
256 if err != nil {
257 return nil, err // inliner produced invalid edits
258 }
259 got, err = driverutil.FormatSourceRemoveImports(tpkg, got)
260 if err != nil {
261 return nil, err // failed to parse+print
262 }
263 return []byte(got), nil
264 }
265
266 content, err = applyEdits(content, res.Edits)
267 if err != nil {
268 return nil, fmt.Errorf("applying inliner edits failed: %v", err)
269 }
270
271 if post != nil {
272 content = post(content)
273 }
274 if len(calls) <= 1 {
275 // No need to re-type check, as we've inlined all calls.
276 break
277 }
278
279 // TODO(rfindley): develop a theory of "trivial" inlining, which are
280 // inlinings that don't require re-type checking.
281 //
282 // In principle, if the inlining only involves replacing one call with
283 // another, the scope of the caller is unchanged and there is no need to
284 // type check again before inlining subsequent calls (edits should not
285 // overlap, and should not affect each other semantically). However, it
286 // feels sufficiently complicated that, to be safe, this optimization is
287 // deferred until later.
288
289 file, err = parser.ParseFile(fset, uri.Path(), content, parser.ParseComments|parser.SkipObjectResolution)
290 if err != nil {
291 return nil, bug.Errorf("inlined file failed to parse: %v", err)
292 }
293
294 // After inlining one call with a removed parameter, the package will
295 // fail to type check due to "not enough arguments". Therefore, we must
296 // allow type errors here.
297 //
298 // Assumption: the resulting type errors do not affect the correctness of
299 // subsequent inlining, because invalid arguments to a call do not affect
300 // anything in the surrounding scope.
301 //
302 // TODO(rfindley): improve this.
303 logf := func(string, ...any) {}
304 if opts != nil {
305 logf = opts.Logf
306 }
307 tpkg, tinfo, err = reTypeCheck(logf, callInfo.pkg, map[protocol.DocumentURI]*ast.File{uri: file}, true)
308 if err != nil {
309 return nil, bug.Errorf("type checking after inlining failed: %v", err)
310 }
311
312 // Collect calls to the target function in the modified declaration.
313 var calls2 []*ast.CallExpr
314 ast.Inspect(file, func(n ast.Node) bool {
315 if call, ok := n.(*ast.CallExpr); ok {
316 fn := typeutil.StaticCallee(tinfo, call)
317 if fn != nil && fn.Pkg().Path() == string(pkg.Metadata().PkgPath) && fn.Name() == origDecl.Name.Name {
318 calls2 = append(calls2, call)
319 }
320 }
321 return true
322 })
323
324 // If the number of calls has increased, this process will never cease.
325 // If the number of calls has decreased, assume that inlining removed a
326 // call.
327 // If the number of calls didn't change, assume that inlining replaced
328 // a call, and move on to the next.
329 //
330 // Assumption: we're inlining a call that has at most one recursive
331 // reference (which holds for signature rewrites).
332 //
333 // TODO(rfindley): this isn't good enough. We should be able to support
334 // inlining all existing calls even if they increase calls. How do we
335 // correlate the before and after syntax?
336 switch {
337 case len(calls2) > len(calls):
338 return nil, fmt.Errorf("inlining increased calls %d->%d, possible recursive call? content:\n%s", len(calls), len(calls2), content)
339 case len(calls2) < len(calls):
340 calls = calls2
341 case len(calls2) == len(calls):
342 calls = calls2
343 currentCall++
344 }
345 }
346
347 result[callInfo.pgf.URI] = content
348 }
349 return result, nil
350 }