Debian Codegraph @

gopls/internal/golang/change_signature.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 "bytes"
9 "context"
10 "fmt"
11 "go/ast"
12 "go/format"
13 "go/parser"
14 "go/token"
15 "go/types"
16 "regexp"
17
18 goastutil "golang.org/x/tools/go/ast/astutil"
19 "golang.org/x/tools/gopls/internal/cache"
20 "golang.org/x/tools/gopls/internal/cache/parsego"
21 "golang.org/x/tools/gopls/internal/file"
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/gopls/internal/util/bug"
24 "golang.org/x/tools/gopls/internal/util/safetoken"
25 "golang.org/x/tools/gopls/internal/util/tokeninternal"
26 "golang.org/x/tools/imports"
27 "golang.org/x/tools/internal/astutil"
28 "golang.org/x/tools/internal/diff"
29 "golang.org/x/tools/internal/refactor/inline"
30 "golang.org/x/tools/internal/typesinternal"
31 )
32
33 // Changing a signature works as follows, supposing we have the following
34 // original function declaration:
35 //
36 // func Foo(a, b, c int)
37 //
38 // Step 1: Write the declaration according to the given signature change. For
39 // example, given the parameter transformation [2, 0, 1], we construct a new
40 // ast.FuncDecl for the signature:
41 //
42 // func Foo0(c, a, b int)
43 //
44 // Step 2: Build a wrapper function that delegates to the new function.
45 // With this example, the wrapper would look like this:
46 //
47 // func Foo1(a, b, c int) {
48 // Foo0(c, a, b int)
49 // }
50 //
51 // Step 3: Swap in the wrapper for the original, and inline all calls. The
52 // trick here is to rename Foo1 to Foo, inline all calls (replacing them with
53 // a call to Foo0), and then rename Foo0 back to Foo, using a simple string
54 // replacement.
55 //
56 // For example, given a call
57 //
58 // func _() {
59 // Foo(1, 2, 3)
60 // }
61 //
62 // The inlining results in
63 //
64 // func _() {
65 // Foo0(3, 1, 2)
66 // }
67 //
68 // And then renaming results in
69 //
70 // func _() {
71 // Foo(3, 1, 2)
72 // }
73 //
74 // And the desired signature rewriting has occurred! Note: in practice, we
75 // don't use the names Foo0 and Foo1, as they are too likely to conflict with
76 // an existing declaration name. (Instead, we use the prefix G_o_ + p_l_s)
77 //
78 // The advantage of going through the inliner is that we get all of the
79 // semantic considerations for free: the inliner will check for side effects
80 // of arguments, check if the last use of a variable is being removed, check
81 // for unnecessary imports, etc.
82 //
83 // Furthermore, by running the change signature rewriting through the inliner,
84 // we ensure that the inliner gets better to the point that it can handle a
85 // change signature rewrite just as well as if we had implemented change
86 // signature as its own operation. For example, suppose we support reordering
87 // the results of a function. In that case, the wrapper would be:
88 //
89 // func Foo1() (int, int) {
90 // y, x := Foo0()
91 // return x, y
92 // }
93 //
94 // And a call would be rewritten from
95 //
96 // x, y := Foo()
97 //
98 // To
99 //
100 // r1, r2 := Foo()
101 // x, y := r2, r1
102 //
103 // In order to make this idiomatic, we'd have to teach the inliner to rewrite
104 // this as y, x := Foo(). The simplest and most general way to achieve this is
105 // to teach the inliner to recognize when a variable is redundant (r1 and r2,
106 // in this case), lifting declarations. That's probably a very useful skill for
107 // the inliner to have.
108
109 // removeParam computes a refactoring to remove the parameter indicated by the
110 // given range.
111 func removeParam(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.DocumentChange, error) {
112 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
113 if err != nil {
114 return nil, err
115 }
116 // Find the unused parameter to remove.
117 info := findParam(pgf, rng)
118 if info == nil || info.paramIndex == -1 {
119 return nil, fmt.Errorf("no param found")
120 }
121 // Write a transformation to remove the param.
122 var newParams []int
123 for i := 0; i < info.decl.Type.Params.NumFields(); i++ {
124 if i != info.paramIndex {
125 newParams = append(newParams, i)
126 }
127 }
128 return ChangeSignature(ctx, snapshot, pkg, pgf, rng, newParams)
129 }
130
131 // ChangeSignature computes a refactoring to update the signature according to
132 // the provided parameter transformation, for the signature definition
133 // surrounding rng.
134 //
135 // newParams expresses the new parameters for the signature in terms of the old
136 // parameters. Each entry in newParams is the index of the new parameter in the
137 // original parameter list. For example, given func Foo(a, b, c int) and newParams
138 // [2, 0, 1], the resulting changed signature is Foo(c, a, b int). If newParams
139 // omits an index of the original signature, that parameter is removed.
140 //
141 // This operation is a work in progress. Remaining TODO:
142 // - Handle adding parameters.
143 // - Handle adding/removing/reordering results.
144 // - Improve the extra newlines in output.
145 // - Stream type checking via ForEachPackage.
146 // - Avoid unnecessary additional type checking.
147 func ChangeSignature(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, rng protocol.Range, newParams []int) ([]protocol.DocumentChange, error) {
148 // Changes to our heuristics for whether we can remove a parameter must also
149 // be reflected in the canRemoveParameter helper.
150 if perrors, terrors := pkg.ParseErrors(), pkg.TypeErrors(); len(perrors) > 0 || len(terrors) > 0 {
151 var sample string
152 if len(perrors) > 0 {
153 sample = perrors[0].Error()
154 } else {
155 sample = terrors[0].Error()
156 }
157 return nil, fmt.Errorf("can't change signatures for packages with parse or type errors: (e.g. %s)", sample)
158 }
159
160 info := findParam(pgf, rng)
161 if info == nil || info.decl == nil {
162 return nil, fmt.Errorf("failed to find declaration")
163 }
164
165 // Step 1: create the new declaration, which is a copy of the original decl
166 // with the rewritten signature.
167
168 // Flatten, transform and regroup fields, using the flatField intermediate
169 // representation. A flatField is the result of flattening an *ast.FieldList
170 // along with type information.
171 type flatField struct {
172 name string // empty if the field is unnamed
173 typeExpr ast.Expr
174 typ types.Type
175 }
176
177 var newParamFields []flatField
178 for id, field := range astutil.FlatFields(info.decl.Type.Params) {
179 typ := pkg.TypesInfo().TypeOf(field.Type)
180 if typ == nil {
181 return nil, fmt.Errorf("missing field type for field #%d", len(newParamFields))
182 }
183 field := flatField{
184 typeExpr: field.Type,
185 typ: typ,
186 }
187 if id != nil {
188 field.name = id.Name
189 }
190 newParamFields = append(newParamFields, field)
191 }
192
193 // Select the new parameter fields.
194 newParamFields, ok := selectElements(newParamFields, newParams)
195 if !ok {
196 return nil, fmt.Errorf("failed to apply parameter transformation %v", newParams)
197 }
198
199 // writeFields performs the regrouping of named fields.
200 writeFields := func(flatFields []flatField) *ast.FieldList {
201 list := new(ast.FieldList)
202 for i, f := range flatFields {
203 var field *ast.Field
204 if i > 0 && f.name != "" && flatFields[i-1].name != "" && types.Identical(f.typ, flatFields[i-1].typ) {
205 // Group named fields if they have the same type.
206 field = list.List[len(list.List)-1]
207 } else {
208 // Otherwise, create a new field.
209 field = &ast.Field{
210 Type: astutil.CloneNode(f.typeExpr),
211 }
212 list.List = append(list.List, field)
213 }
214 if f.name != "" {
215 field.Names = append(field.Names, ast.NewIdent(f.name))
216 }
217 }
218 return list
219 }
220
221 newDecl := astutil.CloneNode(info.decl)
222 newDecl.Type.Params = writeFields(newParamFields)
223
224 // Step 2: build a wrapper function calling the new declaration.
225
226 var (
227 params = astutil.CloneNode(info.decl.Type.Params) // parameters of wrapper func: "_" names must be modified
228 args = make([]ast.Expr, len(newParams)) // arguments to the delegated call
229 variadic = false // whether the signature is variadic
230 )
231 {
232 // Record names used by non-blank parameters, just in case the user had a
233 // parameter named 'blank0', which would conflict with the synthetic names
234 // we construct below.
235 // TODO(rfindley): add an integration test for this behavior.
236 nonBlankNames := make(map[string]bool) // for detecting conflicts with renamed blanks
237 for _, fld := range params.List {
238 for _, n := range fld.Names {
239 if n.Name != "_" {
240 nonBlankNames[n.Name] = true
241 }
242 }
243 if len(fld.Names) == 0 {
244 // All parameters must have a non-blank name. For convenience, give
245 // this field a blank name.
246 fld.Names = append(fld.Names, ast.NewIdent("_")) // will be named below
247 }
248 }
249 // oldParams maps parameters to their argument in the delegated call.
250 // In other words, it is the inverse of newParams, but it is represented as
251 // a map rather than a slice, as not every old param need exist in
252 // newParams.
253 oldParams := make(map[int]int)
254 for new, old := range newParams {
255 oldParams[old] = new
256 }
257 blanks := 0
258 paramIndex := 0 // global param index.
259 for id, field := range astutil.FlatFields(params) {
260 argIndex, ok := oldParams[paramIndex]
261 paramIndex++
262 if !ok {
263 continue // parameter is removed
264 }
265 if id.Name == "_" { // from above: every field has names
266 // Create names for blank (_) parameters so the delegating wrapper
267 // can refer to them.
268 for {
269 // These names will not be seen by the user, so give them an
270 // arbitrary name.
271 newName := fmt.Sprintf("blank%d", blanks)
272 blanks++
273 if !nonBlankNames[newName] {
274 id.Name = newName
275 break
276 }
277 }
278 }
279 args[argIndex] = ast.NewIdent(id.Name)
280 // Record whether the call has an ellipsis.
281 // (Only the last loop iteration matters.)
282 _, variadic = field.Type.(*ast.Ellipsis)
283 }
284 }
285
286 // Step 3: Rewrite all referring calls, by swapping in the wrapper and
287 // inlining all.
288
289 newContent, err := rewriteCalls(ctx, signatureRewrite{
290 snapshot: snapshot,
291 pkg: pkg,
292 pgf: pgf,
293 origDecl: info.decl,
294 newDecl: newDecl,
295 params: params,
296 callArgs: args,
297 variadic: variadic,
298 })
299 if err != nil {
300 return nil, err
301 }
302
303 // Finally, rewrite the original declaration. We do this after inlining all
304 // calls, as there may be calls in the same file as the declaration. But none
305 // of the inlining should have changed the location of the original
306 // declaration.
307 {
308 idx := findDecl(pgf.File, info.decl)
309 if idx < 0 {
310 return nil, bug.Errorf("didn't find original decl")
311 }
312
313 src, ok := newContent[pgf.URI]
314 if !ok {
315 src = pgf.Src
316 }
317 fset := tokeninternal.FileSetFor(pgf.Tok)
318 src, err := rewriteSignature(fset, idx, src, newDecl)
319 if err != nil {
320 return nil, err
321 }
322 newContent[pgf.URI] = src
323 }
324
325 // Translate the resulting state into document changes.
326 var changes []protocol.DocumentChange
327 for uri, after := range newContent {
328 fh, err := snapshot.ReadFile(ctx, uri)
329 if err != nil {
330 return nil, err
331 }
332 before, err := fh.Content()
333 if err != nil {
334 return nil, err
335 }
336 edits := diff.Bytes(before, after)
337 mapper := protocol.NewMapper(uri, before)
338 textedits, err := protocol.EditsFromDiffEdits(mapper, edits)
339 if err != nil {
340 return nil, fmt.Errorf("computing edits for %s: %v", uri, err)
341 }
342 change := protocol.DocumentChangeEdit(fh, textedits)
343 changes = append(changes, change)
344 }
345 return changes, nil
346 }
347
348 // rewriteSignature rewrites the signature of the declIdx'th declaration in src
349 // to use the signature of newDecl (described by fset).
350 //
351 // TODO(rfindley): I think this operation could be generalized, for example by
352 // using a concept of a 'nodepath' to correlate nodes between two related
353 // files.
354 //
355 // Note that with its current application, rewriteSignature is expected to
356 // succeed. Separate bug.Errorf calls are used below (rather than one call at
357 // the callsite) in order to have greater precision.
358 func rewriteSignature(fset *token.FileSet, declIdx int, src0 []byte, newDecl *ast.FuncDecl) ([]byte, error) {
359 // Parse the new file0 content, to locate the original params.
360 file0, err := parser.ParseFile(fset, "", src0, parser.ParseComments|parser.SkipObjectResolution)
361 if err != nil {
362 return nil, bug.Errorf("re-parsing declaring file failed: %v", err)
363 }
364 decl0, _ := file0.Decls[declIdx].(*ast.FuncDecl)
365 // Inlining shouldn't have changed the location of any declarations, but do
366 // a sanity check.
367 if decl0 == nil || decl0.Name.Name != newDecl.Name.Name {
368 return nil, bug.Errorf("inlining affected declaration order: found %v, not func %s", decl0, newDecl.Name.Name)
369 }
370 opening0, closing0, err := safetoken.Offsets(fset.File(decl0.Pos()), decl0.Type.Params.Opening, decl0.Type.Params.Closing)
371 if err != nil {
372 return nil, bug.Errorf("can't find params: %v", err)
373 }
374
375 // Format the modified signature and apply a textual replacement. This
376 // minimizes comment disruption.
377 formattedType := FormatNode(fset, newDecl.Type)
378 expr, err := parser.ParseExprFrom(fset, "", []byte(formattedType), 0)
379 if err != nil {
380 return nil, bug.Errorf("parsing modified signature: %v", err)
381 }
382 newType := expr.(*ast.FuncType)
383 opening1, closing1, err := safetoken.Offsets(fset.File(newType.Pos()), newType.Params.Opening, newType.Params.Closing)
384 if err != nil {
385 return nil, bug.Errorf("param offsets: %v", err)
386 }
387 newParams := formattedType[opening1 : closing1+1]
388
389 // Splice.
390 var buf bytes.Buffer
391 buf.Write(src0[:opening0])
392 buf.WriteString(newParams)
393 buf.Write(src0[closing0+1:])
394 newSrc := buf.Bytes()
395 if len(file0.Imports) > 0 {
396 formatted, err := imports.Process("output", newSrc, nil)
397 if err != nil {
398 return nil, bug.Errorf("imports.Process failed: %v", err)
399 }
400 newSrc = formatted
401 }
402 return newSrc, nil
403 }
404
405 // paramInfo records information about a param identified by a position.
406 type paramInfo struct {
407 decl *ast.FuncDecl // enclosing func decl (non-nil)
408 paramIndex int // index of param among all params, or -1
409 field *ast.Field // enclosing field of Decl, or nil if range not among parameters
410 name *ast.Ident // indicated name (either enclosing, or Field.Names[0] if len(Field.Names) == 1)
411 }
412
413 // findParam finds the parameter information spanned by the given range.
414 func findParam(pgf *parsego.File, rng protocol.Range) *paramInfo {
415 info := paramInfo{paramIndex: -1}
416 start, end, err := pgf.RangePos(rng)
417 if err != nil {
418 return nil
419 }
420
421 path, _ := goastutil.PathEnclosingInterval(pgf.File, start, end)
422 var (
423 id *ast.Ident
424 field *ast.Field
425 )
426 // Find the outermost enclosing node of each kind, whether or not they match
427 // the semantics described in the docstring.
428 for _, n := range path {
429 switch n := n.(type) {
430 case *ast.Ident:
431 id = n
432 case *ast.Field:
433 field = n
434 case *ast.FuncDecl:
435 info.decl = n
436 }
437 }
438 if info.decl == nil {
439 return nil
440 }
441 if field == nil {
442 return &info
443 }
444 pi := 0
445 // Search for field and id among parameters of decl.
446 // This search may fail, even if one or both of id and field are non nil:
447 // field could be from a result or local declaration, and id could be part of
448 // the field type rather than names.
449 for _, f := range info.decl.Type.Params.List {
450 if f == field {
451 info.paramIndex = pi // may be modified later
452 info.field = f
453 for _, n := range f.Names {
454 if n == id {
455 info.paramIndex = pi
456 info.name = n
457 break
458 }
459 pi++
460 }
461 if info.name == nil && len(info.field.Names) == 1 {
462 info.name = info.field.Names[0]
463 }
464 break
465 } else {
466 m := len(f.Names)
467 if m == 0 {
468 m = 1
469 }
470 pi += m
471 }
472 }
473 return &info
474 }
475
476 // signatureRewrite defines a rewritten function signature.
477 //
478 // See rewriteCalls for more details.
479 type signatureRewrite struct {
480 snapshot *cache.Snapshot
481 pkg *cache.Package
482 pgf *parsego.File
483 origDecl, newDecl *ast.FuncDecl
484 params *ast.FieldList
485 callArgs []ast.Expr
486 variadic bool
487 }
488
489 // rewriteCalls returns the document changes required to rewrite the
490 // signature of origDecl to that of newDecl.
491 //
492 // This is a rather complicated factoring of the rewrite operation, but is able
493 // to describe arbitrary rewrites. Specifically, rewriteCalls creates a
494 // synthetic copy of pkg, where the original function declaration is changed to
495 // be a trivial wrapper around the new declaration. params and callArgs are
496 // used to perform this delegation: params must have the same type as origDecl,
497 // but may have renamed parameters (such as is required for delegating blank
498 // parameters). callArgs are the arguments of the delegated call (i.e. using
499 // params).
500 //
501 // For example, consider removing the unused 'b' parameter below, rewriting
502 //
503 // func Foo(a, b, c, _ int) int {
504 // return a+c
505 // }
506 //
507 // To
508 //
509 // func Foo(a, c, _ int) int {
510 // return a+c
511 // }
512 //
513 // In this case, rewriteCalls is parameterized as follows:
514 // - origDecl is the original declaration
515 // - newDecl is the new declaration, which is a copy of origDecl less the 'b'
516 // parameter.
517 // - params is a new parameter list (a, b, c, blank0 int) to be used for the
518 // new wrapper.
519 // - callArgs is the argument list (a, c, blank0), to be used to call the new
520 // delegate.
521 //
522 // rewriting is expressed this way so that rewriteCalls can own the details
523 // of *how* this rewriting is performed. For example, as of writing it names
524 // the synthetic delegate G_o_p_l_s_foo, but the caller need not know this.
525 //
526 // By passing an entirely new declaration, rewriteCalls may be used for
527 // signature refactorings that may affect the function body, such as removing
528 // or adding return values.
529 func rewriteCalls(ctx context.Context, rw signatureRewrite) (map[protocol.DocumentURI][]byte, error) {
530 // tag is a unique prefix that is added to the delegated declaration.
531 //
532 // It must have a ~0% probability of causing collisions with existing names.
533 const tag = "G_o_p_l_s_"
534
535 var (
536 modifiedSrc []byte
537 modifiedFile *ast.File
538 modifiedDecl *ast.FuncDecl
539 )
540 {
541 delegate := astutil.CloneNode(rw.newDecl) // clone before modifying
542 delegate.Name.Name = tag + delegate.Name.Name
543 if obj := rw.pkg.Types().Scope().Lookup(delegate.Name.Name); obj != nil {
544 return nil, fmt.Errorf("synthetic name %q conflicts with an existing declaration", delegate.Name.Name)
545 }
546
547 wrapper := astutil.CloneNode(rw.origDecl)
548 wrapper.Type.Params = rw.params
549
550 // Get the receiver name, creating it if necessary.
551 var recv string // nonempty => call is a method call with receiver recv
552 if wrapper.Recv.NumFields() > 0 {
553 if len(wrapper.Recv.List[0].Names) > 0 {
554 recv = wrapper.Recv.List[0].Names[0].Name
555 } else {
556 // Create unique name for the temporary receiver, which will be inlined away.
557 //
558 // We use the lexical scope of the original function to avoid conflicts
559 // with (e.g.) named result variables. However, since the parameter syntax
560 // may have been modified/renamed from the original function, we must
561 // reject those names too.
562 usedParams := make(map[string]bool)
563 for _, fld := range wrapper.Type.Params.List {
564 for _, name := range fld.Names {
565 usedParams[name.Name] = true
566 }
567 }
568 scope := rw.pkg.TypesInfo().Scopes[rw.origDecl.Type]
569 if scope == nil {
570 return nil, bug.Errorf("missing function scope for %v", rw.origDecl.Name.Name)
571 }
572 for i := 0; ; i++ {
573 recv = fmt.Sprintf("r%d", i)
574 _, obj := scope.LookupParent(recv, token.NoPos)
575 if obj == nil && !usedParams[recv] {
576 break
577 }
578 }
579 wrapper.Recv.List[0].Names = []*ast.Ident{{Name: recv}}
580 }
581 }
582
583 name := &ast.Ident{Name: delegate.Name.Name}
584 var fun ast.Expr = name
585 if recv != "" {
586 fun = &ast.SelectorExpr{
587 X: &ast.Ident{Name: recv},
588 Sel: name,
589 }
590 }
591 call := &ast.CallExpr{
592 Fun: fun,
593 Args: rw.callArgs,
594 }
595 if rw.variadic {
596 call.Ellipsis = 1 // must not be token.NoPos
597 }
598
599 var stmt ast.Stmt
600 if delegate.Type.Results.NumFields() > 0 {
601 stmt = &ast.ReturnStmt{
602 Results: []ast.Expr{call},
603 }
604 } else {
605 stmt = &ast.ExprStmt{
606 X: call,
607 }
608 }
609 wrapper.Body = &ast.BlockStmt{
610 List: []ast.Stmt{stmt},
611 }
612
613 fset := tokeninternal.FileSetFor(rw.pgf.Tok)
614 var err error
615 modifiedSrc, err = replaceFileDecl(rw.pgf, rw.origDecl, delegate)
616 if err != nil {
617 return nil, err
618 }
619 // TODO(rfindley): we can probably get away with one fewer parse operations
620 // by returning the modified AST from replaceDecl. Investigate if that is
621 // accurate.
622 modifiedSrc = append(modifiedSrc, []byte("\n\n"+FormatNode(fset, wrapper))...)
623 modifiedFile, err = parser.ParseFile(rw.pkg.FileSet(), rw.pgf.URI.Path(), modifiedSrc, parser.ParseComments|parser.SkipObjectResolution)
624 if err != nil {
625 return nil, err
626 }
627 modifiedDecl = modifiedFile.Decls[len(modifiedFile.Decls)-1].(*ast.FuncDecl)
628 }
629
630 // Type check pkg again with the modified file, to compute the synthetic
631 // callee.
632 logf := logger(ctx, "change signature", rw.snapshot.Options().VerboseOutput)
633 pkg2, info, err := reTypeCheck(logf, rw.pkg, map[protocol.DocumentURI]*ast.File{rw.pgf.URI: modifiedFile}, false)
634 if err != nil {
635 return nil, err
636 }
637 calleeInfo, err := inline.AnalyzeCallee(logf, rw.pkg.FileSet(), pkg2, info, modifiedDecl, modifiedSrc)
638 if err != nil {
639 return nil, fmt.Errorf("analyzing callee: %v", err)
640 }
641
642 post := func(got []byte) []byte { return bytes.ReplaceAll(got, []byte(tag), nil) }
643 opts := &inline.Options{
644 Logf: logf,
645 IgnoreEffects: true,
646 }
647 return inlineAllCalls(ctx, rw.snapshot, rw.pkg, rw.pgf, rw.origDecl, calleeInfo, post, opts)
648 }
649
650 // reTypeCheck re-type checks orig with new file contents defined by fileMask.
651 //
652 // It expects that any newly added imports are already present in the
653 // transitive imports of orig.
654 //
655 // If expectErrors is true, reTypeCheck allows errors in the new package.
656 // TODO(rfindley): perhaps this should be a filter to specify which errors are
657 // acceptable.
658 func reTypeCheck(logf func(string, ...any), orig *cache.Package, fileMask map[protocol.DocumentURI]*ast.File, expectErrors bool) (*types.Package, *types.Info, error) {
659 pkg := types.NewPackage(string(orig.Metadata().PkgPath), string(orig.Metadata().Name))
660 info := &types.Info{
661 Types: make(map[ast.Expr]types.TypeAndValue),
662 Defs: make(map[*ast.Ident]types.Object),
663 Uses: make(map[*ast.Ident]types.Object),
664 Implicits: make(map[ast.Node]types.Object),
665 Selections: make(map[*ast.SelectorExpr]*types.Selection),
666 Scopes: make(map[ast.Node]*types.Scope),
667 Instances: make(map[*ast.Ident]types.Instance),
668 FileVersions: make(map[*ast.File]string),
669 }
670 {
671 var files []*ast.File
672 for _, pgf := range orig.CompiledGoFiles() {
673 if mask, ok := fileMask[pgf.URI]; ok {
674 files = append(files, mask)
675 } else {
676 files = append(files, pgf.File)
677 }
678 }
679
680 // Implement a BFS for imports in the transitive package graph.
681 //
682 // Note that this only works if any newly added imports are expected to be
683 // present among transitive imports. In general we cannot assume this to
684 // be the case, but in the special case of removing a parameter it works
685 // because any parameter types must be present in export data.
686 var importer func(importPath string) (*types.Package, error)
687 {
688 var (
689 importsByPath = make(map[string]*types.Package) // cached imports
690 toSearch = []*types.Package{orig.Types()} // packages to search
691 searched = make(map[string]bool) // path -> (false, if present in toSearch; true, if already searched)
692 )
693 importer = func(path string) (*types.Package, error) {
694 if p, ok := importsByPath[path]; ok {
695 return p, nil
696 }
697 for len(toSearch) > 0 {
698 pkg := toSearch[0]
699 toSearch = toSearch[1:]
700 searched[pkg.Path()] = true
701 for _, p := range pkg.Imports() {
702 // TODO(rfindley): this is incorrect: p.Path() is a package path,
703 // whereas path is an import path. We can fix this by reporting any
704 // newly added imports from inlining, or by using the ImporterFrom
705 // interface and package metadata.
706 //
707 // TODO(rfindley): can't the inliner also be wrong here? It's
708 // possible that an import path means different things depending on
709 // the location.
710 importsByPath[p.Path()] = p
711 if _, ok := searched[p.Path()]; !ok {
712 searched[p.Path()] = false
713 toSearch = append(toSearch, p)
714 }
715 }
716 if p, ok := importsByPath[path]; ok {
717 return p, nil
718 }
719 }
720 return nil, fmt.Errorf("missing import")
721 }
722 }
723 cfg := &types.Config{
724 Sizes: orig.Metadata().TypesSizes,
725 Importer: ImporterFunc(importer),
726 }
727
728 // Copied from cache/check.go.
729 // TODO(rfindley): factor this out and fix goVersionRx.
730 // Set Go dialect.
731 if module := orig.Metadata().Module; module != nil && module.GoVersion != "" {
732 goVersion := "go" + module.GoVersion
733 // types.NewChecker panics if GoVersion is invalid.
734 // An unparsable mod file should probably stop us
735 // before we get here, but double check just in case.
736 if goVersionRx.MatchString(goVersion) {
737 cfg.GoVersion = goVersion
738 }
739 }
740 if expectErrors {
741 cfg.Error = func(err error) {
742 logf("re-type checking: expected error: %v", err)
743 }
744 }
745 typesinternal.SetUsesCgo(cfg)
746 checker := types.NewChecker(cfg, orig.FileSet(), pkg, info)
747 if err := checker.Files(files); err != nil && !expectErrors {
748 return nil, nil, fmt.Errorf("type checking rewritten package: %v", err)
749 }
750 }
751 return pkg, info, nil
752 }
753
754 // TODO(golang/go#63472): this looks wrong with the new Go version syntax.
755 var goVersionRx = regexp.MustCompile(`^go([1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
756
757 // selectElements returns a new array of elements of s indicated by the
758 // provided list of indices. It returns false if any index was out of bounds.
759 //
760 // For example, given the slice []string{"a", "b", "c", "d"}, the
761 // indices []int{3, 0, 1} results in the slice []string{"d", "a", "b"}.
762 func selectElements[T any](s []T, indices []int) ([]T, bool) {
763 res := make([]T, len(indices))
764 for i, index := range indices {
765 if index < 0 || index >= len(s) {
766 return nil, false
767 }
768 res[i] = s[index]
769 }
770 return res, true
771 }
772
773 // replaceFileDecl replaces old with new in the file described by pgf.
774 //
775 // TODO(rfindley): generalize, and combine with rewriteSignature.
776 func replaceFileDecl(pgf *parsego.File, old, new ast.Decl) ([]byte, error) {
777 i := findDecl(pgf.File, old)
778 if i == -1 {
779 return nil, bug.Errorf("didn't find old declaration")
780 }
781 start, end, err := safetoken.Offsets(pgf.Tok, old.Pos(), old.End())
782 if err != nil {
783 return nil, err
784 }
785 var out bytes.Buffer
786 out.Write(pgf.Src[:start])
787 fset := tokeninternal.FileSetFor(pgf.Tok)
788 if err := format.Node(&out, fset, new); err != nil {
789 return nil, bug.Errorf("formatting new node: %v", err)
790 }
791 out.Write(pgf.Src[end:])
792 return out.Bytes(), nil
793 }
794
795 // findDecl finds the index of decl in file.Decls.
796 //
797 // TODO: use slices.Index when it is available.
798 func findDecl(file *ast.File, decl ast.Decl) int {
799 for i, d := range file.Decls {
800 if d == decl {
801 return i
802 }
803 }
804 return -1
805 }