Debian Codegraph @

gopls/internal/golang/rename.go

raw symbols SCIP
1 // Copyright 2019 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 // TODO(adonovan):
8 //
9 // - method of generic concrete type -> arbitrary instances of same
10 //
11 // - make satisfy work across packages.
12 //
13 // - tests, tests, tests:
14 // - play with renamings in the k8s tree.
15 // - generics
16 // - error cases (e.g. conflicts)
17 // - renaming a symbol declared in the module cache
18 // (currently proceeds with half of the renaming!)
19 // - make sure all tests have both a local and a cross-package analogue.
20 // - look at coverage
21 // - special cases: embedded fields, interfaces, test variants,
22 // function-local things with uppercase names;
23 // packages with type errors (currently 'satisfy' rejects them),
24 // package with missing imports;
25 //
26 // - measure performance in k8s.
27 //
28 // - The original gorename tool assumed well-typedness, but the gopls feature
29 // does no such check (which actually makes it much more useful).
30 // Audit to ensure it is safe on ill-typed code.
31 //
32 // - Generics support was no doubt buggy before but incrementalization
33 // may have exacerbated it. If the problem were just about objects,
34 // defs and uses it would be fairly simple, but type assignability
35 // comes into play in the 'satisfy' check for method renamings.
36 // De-instantiating Vector[int] to Vector[T] changes its type.
37 // We need to come up with a theory for the satisfy check that
38 // works with generics, and across packages. We currently have no
39 // simple way to pass types between packages (think: objectpath for
40 // types), though presumably exportdata could be pressed into service.
41 //
42 // - FileID-based de-duplication of edits to different URIs for the same file.
43
44 import (
45 "bytes"
46 "context"
47 "errors"
48 "fmt"
49 "go/ast"
50 "go/parser"
51 "go/printer"
52 "go/token"
53 "go/types"
54 "maps"
55 "os"
56 "path/filepath"
57 "regexp"
58 "slices"
59 "sort"
60 "strconv"
61 "strings"
62
63 "golang.org/x/mod/modfile"
64 goastutil "golang.org/x/tools/go/ast/astutil"
65 "golang.org/x/tools/go/ast/inspector"
66 "golang.org/x/tools/go/types/objectpath"
67 "golang.org/x/tools/go/types/typeutil"
68 "golang.org/x/tools/gopls/internal/cache"
69 "golang.org/x/tools/gopls/internal/cache/metadata"
70 "golang.org/x/tools/gopls/internal/cache/parsego"
71 "golang.org/x/tools/gopls/internal/file"
72 "golang.org/x/tools/gopls/internal/protocol"
73 "golang.org/x/tools/gopls/internal/util/bug"
74 "golang.org/x/tools/gopls/internal/util/cursorutil"
75 "golang.org/x/tools/gopls/internal/util/pathutil"
76 "golang.org/x/tools/gopls/internal/util/safetoken"
77 "golang.org/x/tools/internal/astutil"
78 "golang.org/x/tools/internal/diff"
79 "golang.org/x/tools/internal/event"
80 "golang.org/x/tools/internal/typesinternal"
81 "golang.org/x/tools/refactor/satisfy"
82 )
83
84 // A renamer holds state of a single call to renameObj, which renames
85 // an object (or several coupled objects) within a single type-checked
86 // syntax package.
87 type renamer struct {
88 pkg *cache.Package // the syntax package in which the renaming is applied
89 objsToUpdate map[types.Object]bool // records progress of calls to check
90 conflicts []string
91 from, to string
92 satisfyConstraints map[satisfy.Constraint]bool
93 msets typeutil.MethodSetCache
94 changeMethods bool
95 }
96
97 // A PrepareItem holds the result of a "prepare rename" operation:
98 // the source range and value of a selected identifier.
99 type PrepareItem struct {
100 Range protocol.Range
101 Text string
102 }
103
104 // PrepareRename searches for a valid renaming at position pp.
105 //
106 // The returned usererr is intended to be displayed to the user to explain why
107 // the prepare fails. Probably we could eliminate the redundancy in returning
108 // two errors, but for now this is done defensively.
109 func PrepareRename(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, rng protocol.Range) (_ *PrepareItem, usererr, err error) {
110 ctx, done := event.Start(ctx, "golang.PrepareRename")
111 defer done()
112
113 // Is the cursor within the package name declaration?
114 if pgf, inPackageName, err := parsePackageNameDecl(ctx, snapshot, f, rng); err != nil {
115 return nil, err, err
116 } else if inPackageName {
117 item, err := prepareRenamePackageName(ctx, snapshot, pgf)
118 return item, err, err
119 }
120
121 // Ordinary (non-package) renaming.
122 //
123 // Type-check the current package, locate the reference at the position,
124 // validate the object, and report its name and range.
125 //
126 // TODO(adonovan): in all cases below, we return usererr=nil,
127 // which means we return (nil, nil) at the protocol
128 // layer. This seems like a bug, or at best an exploitation of
129 // knowledge of VSCode-specific behavior. Can we avoid that?
130 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, f.URI())
131 if err != nil {
132 return nil, nil, err
133 }
134 start, end, err := pgf.RangePos(rng)
135 if err != nil {
136 return nil, nil, err
137 }
138 cur, _ := pgf.Cursor().FindByPos(start, end) // can't fail
139
140 // Check if we're in a 'func' keyword. If so, we hijack the renaming to
141 // change the function signature.
142 if item, err := prepareRenameFuncSignature(pgf, start, end, cur); err != nil {
143 return nil, nil, err
144 } else if item != nil {
145 return item, nil, nil
146 }
147
148 targets, err := objectsAt(pkg.TypesInfo(), cur)
149 if err != nil {
150 // Check if we are renaming an ident inside its doc comment. The call to
151 // objectsAt will have returned an error in this case.
152 // TODO(adonovan): move this logic into objectsAt.
153 var ok bool
154 cur, ok = docCommentPosToIdent(pgf, start, end, cur)
155 if !ok {
156 return nil, nil, err
157 }
158 id := cur.Node().(*ast.Ident)
159 obj := pkg.TypesInfo().Defs[id]
160 if obj == nil {
161 return nil, nil, fmt.Errorf("error fetching Object for ident %q", id.Name)
162 }
163 // Change rename target to the ident.
164 targets = []objectAt{{obj, cur}}
165 }
166
167 // Pick a representative object arbitrarily.
168 // (All share the same name, pos, and kind.)
169 obj, node := targets[0].obj, targets[0].cur.Node()
170 if err := checkRenamable(obj, node); err != nil {
171 return nil, nil, err
172 }
173 nodeRng, err := pgf.NodeRange(node)
174 if err != nil {
175 return nil, nil, err
176 }
177 if _, isImport := node.(*ast.ImportSpec); isImport {
178 // We're not really renaming the import path.
179 nodeRng.End = nodeRng.Start
180 }
181 return &PrepareItem{
182 Range: nodeRng,
183 Text: obj.Name(),
184 }, nil, nil
185 }
186
187 func prepareRenamePackageName(ctx context.Context, snapshot *cache.Snapshot, pgf *parsego.File) (*PrepareItem, error) {
188 // Does the client support file renaming?
189 if !slices.Contains(snapshot.Options().SupportedResourceOperations, protocol.Rename) {
190 return nil, errors.New("can't rename package: LSP client does not support file renaming")
191 }
192
193 // Check validity of the metadata for the file's containing package.
194 meta, err := snapshot.NarrowestMetadataForFile(ctx, pgf.URI)
195 if err != nil {
196 return nil, err
197 }
198 if meta.Name == "main" {
199 return nil, fmt.Errorf("can't rename package \"main\"")
200 }
201 // TODO(mkalil): support renaming x_test packages.
202 if strings.HasSuffix(string(meta.Name), "_test") {
203 return nil, fmt.Errorf("can't rename x_test packages")
204 }
205 if meta.Module == nil {
206 return nil, fmt.Errorf("can't rename package: missing module information for package %q", meta.PkgPath)
207 }
208 // TODO(mkalil): why is renaming the root package of a module unsupported?
209 if meta.Module.Path == string(meta.PkgPath) {
210 return nil, fmt.Errorf("can't rename package: package path %q is the same as module path %q", meta.PkgPath, meta.Module.Path)
211 }
212
213 // Return the location of the package declaration.
214 rng, err := pgf.NodeRange(pgf.File.Name)
215 if err != nil {
216 return nil, err
217 }
218
219 return &PrepareItem{
220 Range: rng,
221 Text: string(meta.PkgPath),
222 }, nil
223 }
224
225 // prepareRenameFuncSignature prepares a change signature refactoring initiated
226 // through invoking a rename request at the 'func' keyword of a function
227 // declaration.
228 //
229 // The resulting text is the signature of the function, which may be edited to
230 // the new signature.
231 func prepareRenameFuncSignature(pgf *parsego.File, start, end token.Pos, cursor inspector.Cursor) (*PrepareItem, error) {
232 fdecl := funcKeywordDecl(start, end, cursor)
233 if fdecl == nil {
234 return nil, nil
235 }
236 ftyp := nameBlankParams(fdecl.Type)
237 var buf bytes.Buffer
238 if err := printer.Fprint(&buf, token.NewFileSet(), ftyp); err != nil { // use a new fileset so that the signature is formatted on a single line
239 return nil, err
240 }
241 rng, err := pgf.PosRange(ftyp.Func, ftyp.Func+token.Pos(len("func")))
242 if err != nil {
243 return nil, err
244 }
245 text := buf.String()
246 return &PrepareItem{
247 Range: rng,
248 Text: text,
249 }, nil
250 }
251
252 // nameBlankParams returns a copy of ftype with blank or unnamed params
253 // assigned a unique name.
254 func nameBlankParams(ftype *ast.FuncType) *ast.FuncType {
255 ftype = astutil.CloneNode(ftype)
256
257 // First, collect existing names.
258 scope := make(map[string]bool)
259 for name := range astutil.FlatFields(ftype.Params) {
260 if name != nil {
261 scope[name.Name] = true
262 }
263 }
264 blanks := 0
265 for name, field := range astutil.FlatFields(ftype.Params) {
266 if name == nil {
267 name = ast.NewIdent("_")
268 field.Names = append(field.Names, name) // ok to append
269 }
270 if name.Name == "" || name.Name == "_" {
271 for {
272 newName := fmt.Sprintf("_%d", blanks)
273 blanks++
274 if !scope[newName] {
275 name.Name = newName
276 break
277 }
278 }
279 }
280 }
281 return ftype
282 }
283
284 // renameFuncSignature computes and applies the effective change signature
285 // operation resulting from a 'renamed' (=rewritten) signature.
286 func renameFuncSignature(ctx context.Context, pkg *cache.Package, pgf *parsego.File, start, end token.Pos, snapshot *cache.Snapshot, cursor inspector.Cursor, newName string) (map[protocol.DocumentURI][]protocol.TextEdit, error) {
287 fdecl := funcKeywordDecl(start, end, cursor)
288 if fdecl == nil {
289 return nil, nil
290 }
291 ftyp := nameBlankParams(fdecl.Type)
292
293 // Parse the user's requested new signature.
294 parsed, err := parser.ParseExpr(newName)
295 if err != nil {
296 return nil, err
297 }
298 newType, _ := parsed.(*ast.FuncType)
299 if newType == nil {
300 return nil, fmt.Errorf("parsed signature is %T, not a function type", parsed)
301 }
302
303 // Check results, before we get into handling permutations of parameters.
304 if got, want := newType.Results.NumFields(), ftyp.Results.NumFields(); got != want {
305 return nil, fmt.Errorf("changing results not yet supported (got %d results, want %d)", got, want)
306 }
307 var resultTypes []string
308 for _, field := range astutil.FlatFields(ftyp.Results) {
309 resultTypes = append(resultTypes, FormatNode(token.NewFileSet(), field.Type))
310 }
311 resultIndex := 0
312 for _, field := range astutil.FlatFields(newType.Results) {
313 if FormatNode(token.NewFileSet(), field.Type) != resultTypes[resultIndex] {
314 return nil, fmt.Errorf("changing results not yet supported")
315 }
316 resultIndex++
317 }
318
319 type paramInfo struct {
320 idx int
321 typ string
322 }
323 oldParams := make(map[string]paramInfo)
324 for name, field := range astutil.FlatFields(ftyp.Params) {
325 oldParams[name.Name] = paramInfo{
326 idx: len(oldParams),
327 typ: types.ExprString(field.Type),
328 }
329 }
330
331 var newParams []int
332 for name, field := range astutil.FlatFields(newType.Params) {
333 if name == nil {
334 return nil, fmt.Errorf("need named fields")
335 }
336 info, ok := oldParams[name.Name]
337 if !ok {
338 return nil, fmt.Errorf("couldn't find name %s: adding parameters not yet supported", name)
339 }
340 if newType := types.ExprString(field.Type); newType != info.typ {
341 return nil, fmt.Errorf("changing types (%s to %s) not yet supported", info.typ, newType)
342 }
343 newParams = append(newParams, info.idx)
344 }
345
346 funcRng, err := pgf.PosRange(ftyp.Func, ftyp.Func)
347 if err != nil {
348 return nil, err
349 }
350 changes, err := ChangeSignature(ctx, snapshot, pkg, pgf, funcRng, newParams)
351 if err != nil {
352 return nil, err
353 }
354 transposed := make(map[protocol.DocumentURI][]protocol.TextEdit)
355 for _, change := range changes {
356 transposed[change.TextDocumentEdit.TextDocument.URI] = protocol.AsTextEdits(change.TextDocumentEdit.Edits)
357 }
358 return transposed, nil
359 }
360
361 // funcKeywordDecl returns the FuncDecl for which pos is in the 'func' keyword,
362 // if any.
363 func funcKeywordDecl(start, end token.Pos, cursor inspector.Cursor) *ast.FuncDecl {
364 fdecl, _ := cursorutil.FirstEnclosing[*ast.FuncDecl](cursor)
365 if fdecl == nil {
366 return nil
367 }
368 ftyp := fdecl.Type
369 if start < ftyp.Func || end > ftyp.Func+token.Pos(len("func")) { // tolerate renaming immediately after 'func'
370 return nil
371 }
372 return fdecl
373 }
374
375 // checkRenamable returns an error if the object cannot be renamed.
376 // node is the name-like syntax node from which the renaming originated.
377 func checkRenamable(obj types.Object, node ast.Node) error {
378 switch obj := obj.(type) {
379 case *types.Var:
380 // Allow renaming an embedded field only at its declaration.
381 if obj.Embedded() && node.Pos() != obj.Pos() {
382 return errors.New("an embedded field must be renamed at its declaration (since it renames the type too)")
383
384 }
385 case *types.Builtin, *types.Nil:
386 return fmt.Errorf("%s is built in and cannot be renamed", obj.Name())
387 }
388 if obj.Pkg() == nil || obj.Pkg().Path() == "unsafe" {
389 // e.g. error.Error, unsafe.Pointer
390 return fmt.Errorf("%s is built in and cannot be renamed", obj.Name())
391 }
392 if obj.Name() == "_" {
393 return errors.New("can't rename \"_\"")
394 }
395 return nil
396 }
397
398 // editsToDocChanges converts a map of uris to arrays of text edits to a list of document changes.
399 func editsToDocChanges(ctx context.Context, snapshot *cache.Snapshot, edits map[protocol.DocumentURI][]protocol.TextEdit) ([]protocol.DocumentChange, error) {
400 var changes []protocol.DocumentChange
401 for uri, e := range edits {
402 fh, err := snapshot.ReadFile(ctx, uri)
403 if err != nil {
404 return nil, err
405 }
406 changes = append(changes, protocol.DocumentChangeEdit(fh, e))
407 }
408 return changes, nil
409 }
410
411 // Rename returns a map of TextEdits for each file modified when renaming a
412 // given identifier within a package.
413 func Rename(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, rng protocol.Range, newName string) ([]protocol.DocumentChange, error) {
414 ctx, done := event.Start(ctx, "golang.Rename")
415 defer done()
416
417 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, f.URI())
418 if err != nil {
419 return nil, err
420 }
421 start, end, err := pgf.RangePos(rng)
422 if err != nil {
423 return nil, err
424 }
425
426 cur, ok := pgf.Cursor().FindByPos(start, end)
427 if !ok {
428 return nil, fmt.Errorf("can't find cursor for selection")
429 }
430
431 if edits, err := renameFuncSignature(ctx, pkg, pgf, start, end, snapshot, cur, newName); err != nil {
432 return nil, err
433 } else if edits != nil {
434 return editsToDocChanges(ctx, snapshot, edits)
435 }
436
437 // Cursor within package name declaration?
438 _, inPackageName, err := parsePackageNameDecl(ctx, snapshot, f, rng)
439 if err != nil {
440 return nil, err
441 }
442
443 var (
444 editMap map[protocol.DocumentURI][]diff.Edit
445 newPkgDir string // declared here so it can be used later to move the package's contents to the new directory
446 )
447 if inPackageName {
448 countRenamePackage.Inc()
449 var (
450 newPkgName PackageName
451 newPkgPath PackagePath
452 err error
453 )
454 moveSubpackages := snapshot.Options().RenameMovesSubpackages
455 if newPkgDir, newPkgName, newPkgPath, err = checkPackageRename(pkg, f, newName, moveSubpackages); err != nil {
456 return nil, err
457 }
458 editMap, err = renamePackage(ctx, snapshot, f, newPkgName, newPkgPath, newPkgDir, moveSubpackages)
459 if err != nil {
460 return nil, err
461 }
462 } else {
463 if !isValidIdentifier(newName) {
464 return nil, fmt.Errorf("invalid identifier to rename: %q", newName)
465 }
466 editMap, err = renameOrdinary(ctx, snapshot, f.URI(), rng, newName)
467 if err != nil {
468 return nil, err
469 }
470 }
471
472 // Convert edits to protocol form.
473 result := make(map[protocol.DocumentURI][]protocol.TextEdit)
474 for uri, edits := range editMap {
475 // Sort and de-duplicate edits.
476 //
477 // Overlapping edits may arise in local renamings (due
478 // to type switch implicits) and globals ones (due to
479 // processing multiple package variants).
480 //
481 // We assume renaming produces diffs that are all
482 // replacements (no adjacent insertions that might
483 // become reordered) and that are either identical or
484 // non-overlapping.
485 diff.SortEdits(edits)
486 edits = slices.Compact(edits)
487
488 // TODO(adonovan): the logic above handles repeat edits to the
489 // same file URI (e.g. as a member of package p and p_test) but
490 // is not sufficient to handle file-system level aliasing arising
491 // from symbolic or hard links. For that, we should use a
492 // robustio-FileID-keyed map.
493 // See https://go.dev/cl/457615 for example.
494 // This really occurs in practice, e.g. kubernetes has
495 // vendor/k8s.io/kubectl -> ../../staging/src/k8s.io/kubectl.
496 fh, err := snapshot.ReadFile(ctx, uri)
497 if err != nil {
498 return nil, err
499 }
500 data, err := fh.Content()
501 if err != nil {
502 return nil, err
503 }
504 m := protocol.NewMapper(uri, data)
505 textedits, err := protocol.EditsFromDiffEdits(m, edits)
506 if err != nil {
507 return nil, err
508 }
509 result[uri] = textedits
510 }
511
512 changes, err := editsToDocChanges(ctx, snapshot, result)
513 if err != nil {
514 return nil, err
515 }
516 if inPackageName {
517 oldDir := f.URI().DirPath()
518 if snapshot.Options().RenameMovesSubpackages {
519 // Update the last component of the file's enclosing directory.
520 changes = append(changes, protocol.DocumentChangeRename(
521 protocol.URIFromPath(oldDir),
522 protocol.URIFromPath(newPkgDir)))
523 } else {
524 // Not moving subpackages, so we need to move the files individually
525 // Move each file from oldDir to newPkgDir
526 files, err := os.ReadDir(oldDir)
527 if err != nil {
528 return nil, err
529 }
530 hasNestedDir := false
531 for _, f := range files {
532 if !f.IsDir() {
533 changes = append(changes,
534 protocol.DocumentChangeRename(
535 protocol.URIFromPath(filepath.Join(oldDir, f.Name())),
536 protocol.URIFromPath(filepath.Join(newPkgDir, f.Name()))),
537 )
538 } else {
539 hasNestedDir = true
540 }
541 }
542 // Delete oldPkgDir if it is now empty and newPkgDir is not a subdirectory of oldPkgDir.
543 // protocol.DeleteFile, when used with a directory, will only delete the directory
544 // if it is empty as long as the "recursive" option is set to its default value, false.
545 // TODO(mkalil): The above should be true according to the LSP spec but in VSCode
546 // we could get "Renamed failed to apply edits" errors when we include the edit
547 // to delete a directory that can't be deleted. For now, check if the oldDir has
548 // any nested directories before trying to delete it.
549 // TODO(mkalil): We could be deleting more directories. For example, if
550 // we have a package at a/b/c/d and we move it to a/z, it only deletes
551 // directory d and would leave directories b and c even if they are now
552 // empty.
553 oldPkgDir := f.URI().DirPath()
554 if !pathutil.InDir(oldPkgDir, newPkgDir) && !hasNestedDir {
555 changes = append(changes,
556 protocol.DocumentChangeDelete(protocol.URIFromPath(oldPkgDir)))
557 }
558 }
559 }
560 return changes, nil
561 }
562
563 // renameOrdinary renames an ordinary (non-package) name throughout the workspace.
564 func renameOrdinary(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI, rng protocol.Range, newName string) (map[protocol.DocumentURI][]diff.Edit, error) {
565 // Type-check the referring package and locate the object(s).
566 //
567 // Unlike NarrowestPackageForFile, this operation prefers the
568 // widest variant as, for non-exported identifiers, it is the
569 // only package we need. (In case you're wondering why
570 // 'references' doesn't also want the widest variant: it
571 // computes the union across all variants.)
572 mps, err := snapshot.MetadataForFile(ctx, uri, true)
573 if err != nil {
574 return nil, err
575 }
576 if len(mps) == 0 {
577 return nil, fmt.Errorf("no package metadata for file %s", uri)
578 }
579 widest := mps[len(mps)-1] // widest variant may include _test.go files
580 pkgs, err := snapshot.TypeCheck(ctx, widest.ID)
581 if err != nil {
582 return nil, err
583 }
584 pkg := pkgs[0]
585 pgf, err := pkg.File(uri)
586 if err != nil {
587 return nil, err // "can't happen"
588 }
589 start, end, err := pgf.RangePos(rng)
590 if err != nil {
591 return nil, err
592 }
593 cur, _ := pgf.Cursor().FindByPos(start, end) // cannot fail
594
595 targets, err := objectsAt(pkg.TypesInfo(), cur)
596 if err != nil {
597 // Check if we are renaming an ident inside its doc comment. The call to
598 // objectsAt will have returned an error in this case.
599 // TODO(adonovan): move this logic into objectsAt.
600 var ok bool
601 cur, ok = docCommentPosToIdent(pgf, start, end, cur)
602 if !ok {
603 return nil, err
604 }
605 id := cur.Node().(*ast.Ident)
606 obj := pkg.TypesInfo().Defs[id]
607 if obj == nil {
608 return nil, fmt.Errorf("error fetching types.Object for ident %q", id.Name)
609 }
610 // Change rename target to the ident.
611 targets = []objectAt{{obj, cur}}
612 }
613
614 // Pick a representative object arbitrarily.
615 // (All share the same name, pos, and kind.)
616 obj, node := targets[0].obj, targets[0].cur.Node()
617 if obj.Name() == newName {
618 return nil, fmt.Errorf("old and new names are the same: %s", newName)
619 }
620 if err := checkRenamable(obj, node); err != nil {
621 return nil, err
622 }
623
624 // This covers the case where we are renaming an embedded field at its
625 // declaration (see golang/go#45199). Perform the rename on the field's type declaration.
626 if is[*types.Var](obj) && obj.(*types.Var).Embedded() {
627 if id, ok := node.(*ast.Ident); ok {
628 // TypesInfo.Uses contains the embedded field's *types.TypeName.
629 if typeName := pkg.TypesInfo().Uses[id]; typeName != nil {
630 loc, err := ObjectLocation(ctx, pkg.FileSet(), snapshot, typeName)
631 if err != nil {
632 return nil, err
633 }
634 return renameOrdinary(ctx, snapshot, loc.URI, loc.Range, newName)
635 }
636 }
637 }
638
639 // Find objectpath, if object is exported ("" otherwise).
640 var declObjPath objectpath.Path
641 if obj.Exported() {
642 // objectpath.For requires the origin of a generic function or type, not an
643 // instantiation (a bug?).
644 //
645 // Note that unlike Funcs, TypeNames are always canonical (they are "left"
646 // of the type parameters, unlike methods).
647 switch obj0 := obj.(type) { // avoid "obj :=" since cases reassign the var
648 case *types.TypeName:
649 if _, ok := types.Unalias(obj.Type()).(*types.TypeParam); ok {
650 // As with capitalized function parameters below, type parameters are
651 // local.
652 goto skipObjectPath
653 }
654 case *types.Func:
655 obj = obj0.Origin()
656 case *types.Var:
657 // TODO(adonovan): do vars need the origin treatment too? (issue #58462)
658
659 // Function parameter and result vars that are (unusually)
660 // capitalized are technically exported, even though they
661 // cannot be referenced, because they may affect downstream
662 // error messages. But we can safely treat them as local.
663 //
664 // This is not merely an optimization: the renameExported
665 // operation gets confused by such vars. It finds them from
666 // objectpath, the classifies them as local vars, but as
667 // they came from export data they lack syntax and the
668 // correct scope tree (issue #61294).
669 if !obj0.IsField() && !typesinternal.IsPackageLevel(obj) {
670 goto skipObjectPath
671 }
672 }
673 if path, err := objectpath.For(obj); err == nil {
674 declObjPath = path
675 }
676 skipObjectPath:
677 }
678
679 // Nonexported? Search locally.
680 if declObjPath == "" {
681 var objects []types.Object
682 for _, o := range targets {
683 objects = append(objects, o.obj)
684 }
685
686 editMap, _, err := renameObjects(newName, pkg, objects...)
687 if err != nil {
688 return nil, err
689 }
690
691 // If the selected identifier is a receiver declaration,
692 // also rename receivers of other methods of the same type
693 // that don't already have the desired name.
694 // Quietly discard edits from any that can't be renamed.
695 //
696 // We interpret renaming the receiver declaration as
697 // intent for the broader renaming; renaming a use of
698 // the receiver effects only the local renaming.
699 if id, ok := cur.Node().(*ast.Ident); ok && id.Pos() == obj.Pos() {
700 // enclosing func
701 if decl, _ := cursorutil.FirstEnclosing[*ast.FuncDecl](cur); decl != nil {
702 if decl.Recv != nil &&
703 len(decl.Recv.List) > 0 &&
704 len(decl.Recv.List[0].Names) > 0 {
705 recv := pkg.TypesInfo().Defs[decl.Recv.List[0].Names[0]]
706 if recv == obj {
707 // TODO(adonovan): simplify the above 7 lines to
708 // to "if obj.(*Var).Kind==Recv" in go1.25.
709 renameReceivers(pkg, recv.(*types.Var), newName, editMap)
710 }
711 }
712 }
713 }
714 return editMap, nil
715 }
716
717 // Exported: search globally.
718 //
719 // For exported package-level var/const/func/type objects, the
720 // search scope is just the direct importers.
721 //
722 // For exported fields and methods, the scope is the
723 // transitive rdeps. (The exportedness of the field's struct
724 // or method's receiver is irrelevant.)
725 transitive := false
726 switch obj := obj.(type) {
727 case *types.TypeName:
728 // Renaming an exported package-level type
729 // requires us to inspect all transitive rdeps
730 // in the event that the type is embedded.
731 //
732 // TODO(adonovan): opt: this is conservative
733 // but inefficient. Instead, expand the scope
734 // of the search only if we actually encounter
735 // an embedding of the type, and only then to
736 // the rdeps of the embedding package.
737 if obj.Parent() == obj.Pkg().Scope() {
738 transitive = true
739 }
740
741 case *types.Var:
742 if obj.IsField() {
743 transitive = true // field
744 }
745
746 // TODO(adonovan): opt: process only packages that
747 // contain a reference (xrefs) to the target field.
748
749 case *types.Func:
750 if obj.Signature().Recv() != nil {
751 transitive = true // method
752 }
753
754 // It's tempting to optimize by skipping
755 // packages that don't contain a reference to
756 // the method in the xrefs index, but we still
757 // need to apply the satisfy check to those
758 // packages to find assignment statements that
759 // might expands the scope of the renaming.
760 }
761
762 // Type-check all the packages to inspect.
763 declURI := protocol.URIFromPath(pkg.FileSet().File(obj.Pos()).Name())
764 pkgs, err = typeCheckReverseDependencies(ctx, snapshot, declURI, transitive)
765 if err != nil {
766 return nil, err
767 }
768
769 // Apply the renaming to the (initial) object.
770 declPkgPath := PackagePath(obj.Pkg().Path())
771 return renameExported(pkgs, declPkgPath, declObjPath, newName)
772 }
773
774 // renameReceivers renames all receivers of methods of the same named
775 // type as recv. The edits of each successful renaming are added to
776 // editMap; the failed ones are quietly discarded.
777 func renameReceivers(pkg *cache.Package, recv *types.Var, newName string, editMap map[protocol.DocumentURI][]diff.Edit) {
778 _, named := typesinternal.ReceiverNamed(recv)
779 if named == nil {
780 return
781 }
782
783 // Find receivers of other methods of the same named type.
784 for m := range named.Origin().Methods() {
785 recv2 := m.Signature().Recv()
786 if recv2 == recv {
787 continue // don't re-rename original receiver
788 }
789 if recv2.Name() == newName {
790 continue // no renaming needed
791 }
792 editMap2, _, err := renameObjects(newName, pkg, recv2)
793 if err != nil {
794 continue // ignore secondary failures
795 }
796
797 // Since all methods (and their comments)
798 // are disjoint, and don't affect imports,
799 // we can safely assume that all edits are
800 // nonconflicting and disjoint.
801 for uri, edits := range editMap2 {
802 editMap[uri] = append(editMap[uri], edits...)
803 }
804 }
805 }
806
807 // typeCheckReverseDependencies returns the type-checked packages for
808 // the reverse dependencies of all packages variants containing
809 // file declURI. The packages are in some topological order.
810 //
811 // It includes all variants (even intermediate test variants) for the
812 // purposes of computing reverse dependencies, but discards ITVs for
813 // the actual renaming work.
814 //
815 // (This neglects obscure edge cases where a _test.go file changes the
816 // selectors used only in an ITV, but life is short. Also sin must be
817 // punished.)
818 func typeCheckReverseDependencies(ctx context.Context, snapshot *cache.Snapshot, declURI protocol.DocumentURI, transitive bool) ([]*cache.Package, error) {
819 variants, err := snapshot.MetadataForFile(ctx, declURI, false)
820 if err != nil {
821 return nil, err
822 }
823 // variants must include ITVs for the reverse dependency
824 // computation, but they are filtered out before we typecheck.
825 allRdeps := make(map[PackageID]*metadata.Package)
826 for _, variant := range variants {
827 rdeps, err := snapshot.ReverseDependencies(ctx, variant.ID, transitive)
828 if err != nil {
829 return nil, err
830 }
831 allRdeps[variant.ID] = variant // include self
832 maps.Copy(allRdeps, rdeps)
833 }
834 var ids []PackageID
835 for id, meta := range allRdeps {
836 if meta.IsIntermediateTestVariant() {
837 continue
838 }
839 ids = append(ids, id)
840 }
841
842 // Sort the packages into some topological order of the
843 // (unfiltered) metadata graph.
844 metadata.SortPostOrder(snapshot, ids)
845
846 // Dependencies must be visited first since they can expand
847 // the search set. Ideally we would process the (filtered) set
848 // of packages in the parallel postorder of the snapshot's
849 // (unfiltered) metadata graph, but this is quite tricky
850 // without a good graph abstraction.
851 //
852 // For now, we visit packages sequentially in order of
853 // ascending height, like an inverted breadth-first search.
854 //
855 // Type checking is by far the dominant cost, so
856 // overlapping it with renaming may not be worthwhile.
857 return snapshot.TypeCheck(ctx, ids...)
858 }
859
860 // renameExported renames the object denoted by (pkgPath, objPath)
861 // within the specified packages, along with any other objects that
862 // must be renamed as a consequence. The slice of packages must be
863 // topologically ordered.
864 func renameExported(pkgs []*cache.Package, declPkgPath PackagePath, declObjPath objectpath.Path, newName string) (map[protocol.DocumentURI][]diff.Edit, error) {
865
866 // A target is a name for an object that is stable across types.Packages.
867 type target struct {
868 pkg PackagePath
869 obj objectpath.Path
870 }
871
872 // Populate the initial set of target objects.
873 // This set may grow as we discover the consequences of each renaming.
874 //
875 // TODO(adonovan): strictly, each cone of reverse dependencies
876 // of a single variant should have its own target map that
877 // monotonically expands as we go up the import graph, because
878 // declarations in test files can alter the set of
879 // package-level names and change the meaning of field and
880 // method selectors. So if we parallelize the graph
881 // visitation (see above), we should also compute the targets
882 // as a union of dependencies.
883 //
884 // Or we could decide that the logic below is fast enough not
885 // to need parallelism. In small measurements so far the
886 // type-checking step is about 95% and the renaming only 5%.
887 targets := map[target]bool{{declPkgPath, declObjPath}: true}
888
889 // Apply the renaming operation to each package.
890 allEdits := make(map[protocol.DocumentURI][]diff.Edit)
891 for _, pkg := range pkgs {
892
893 // Resolved target objects within package pkg.
894 var objects []types.Object
895 for t := range targets {
896 p := pkg.DependencyTypes(t.pkg)
897 if p == nil {
898 continue // indirect dependency of no consequence
899 }
900 obj, err := objectpath.Object(p, t.obj)
901 if err != nil {
902 // Possibly a method or an unexported type
903 // that is not reachable through export data?
904 // See https://github.com/golang/go/issues/60789.
905 //
906 // TODO(adonovan): it seems unsatisfactory that Object
907 // should return an error for a "valid" path. Perhaps
908 // we should define such paths as invalid and make
909 // objectpath.For compute reachability?
910 // Would that be a compatible change?
911 continue
912 }
913 objects = append(objects, obj)
914 }
915 if len(objects) == 0 {
916 continue // no targets of consequence to this package
917 }
918
919 // Apply the renaming.
920 editMap, moreObjects, err := renameObjects(newName, pkg, objects...)
921 if err != nil {
922 return nil, err
923 }
924
925 // It is safe to concatenate the edits as they are non-overlapping
926 // (or identical, in which case they will be de-duped by Rename).
927 for uri, edits := range editMap {
928 allEdits[uri] = append(allEdits[uri], edits...)
929 }
930
931 // Expand the search set?
932 for obj := range moreObjects {
933 objpath, err := objectpath.For(obj)
934 if err != nil {
935 continue // not exported
936 }
937 target := target{PackagePath(obj.Pkg().Path()), objpath}
938 targets[target] = true
939
940 // TODO(adonovan): methods requires dynamic
941 // programming of the product targets x
942 // packages as any package might add a new
943 // target (from a forward dep) as a
944 // consequence, and any target might imply a
945 // new set of rdeps. See golang/go#58461.
946 }
947 }
948
949 return allEdits, nil
950 }
951
952 // renamePackage renames package declarations, imports, and go.mod files.
953 //
954 // f is the file originating the rename, and therefore f.URI().Dir() is the
955 // current package directory. newName, newPath, and newDir describe the renaming.
956 func renamePackage(ctx context.Context, s *cache.Snapshot, f file.Handle, newName PackageName, newPath PackagePath, newDir string, moveSubpackages bool) (map[protocol.DocumentURI][]diff.Edit, error) {
957 // Rename the package decl and all imports.
958 renamingEdits := make(map[protocol.DocumentURI][]diff.Edit)
959 err := updatePackageDeclsAndImports(ctx, s, f, newName, newPath, renamingEdits, moveSubpackages)
960 if err != nil {
961 return nil, err
962 }
963
964 err = updateModFiles(ctx, s, f.URI().DirPath(), newDir, renamingEdits, moveSubpackages)
965 if err != nil {
966 return nil, err
967 }
968
969 return renamingEdits, nil
970 }
971
972 // Update any affected replace directives in go.mod files.
973 // TODO(adonovan): should this operate on all go.mod files,
974 // irrespective of whether they are included in the workspace?
975 func updateModFiles(ctx context.Context, s *cache.Snapshot, oldDir string, newPkgDir string, renamingEdits map[protocol.DocumentURI][]diff.Edit, moveSubpackages bool) error {
976 modFiles := s.View().ModFiles()
977 for _, m := range modFiles {
978 fh, err := s.ReadFile(ctx, m)
979 if err != nil {
980 return err
981 }
982 pm, err := s.ParseMod(ctx, fh)
983 if err != nil {
984 return err
985 }
986
987 modFileDir := pm.URI.DirPath()
988 affectedReplaces := []*modfile.Replace{}
989
990 // Check if any replace directives need to be fixed
991 for _, r := range pm.File.Replace {
992 if !strings.HasPrefix(r.New.Path, "/") && !strings.HasPrefix(r.New.Path, "./") && !strings.HasPrefix(r.New.Path, "../") {
993 continue
994 }
995 replacedDir := r.New.Path
996 if strings.HasPrefix(r.New.Path, "./") || strings.HasPrefix(r.New.Path, "../") {
997 replacedDir = filepath.Join(modFileDir, r.New.Path)
998 }
999
1000 // TODO: Is there a risk of converting a '\' delimited replacement to a '/' delimited replacement?
1001
1002 if moveSubpackages && !strings.HasPrefix(filepath.ToSlash(replacedDir)+"/", filepath.ToSlash(oldDir)+"/") ||
1003 !moveSubpackages && !(filepath.ToSlash(replacedDir) == filepath.ToSlash(oldDir)) {
1004 continue //not affected by the package renanming
1005 }
1006
1007 affectedReplaces = append(affectedReplaces, r)
1008 }
1009
1010 if len(affectedReplaces) == 0 {
1011 continue
1012 }
1013 copied, err := modfile.Parse("", pm.Mapper.Content, nil)
1014 if err != nil {
1015 return err
1016 }
1017
1018 for _, r := range affectedReplaces {
1019 replacedDir := r.New.Path
1020 if strings.HasPrefix(r.New.Path, "./") || strings.HasPrefix(r.New.Path, "../") {
1021 replacedDir = filepath.Join(modFileDir, r.New.Path)
1022 }
1023
1024 suffix := strings.TrimPrefix(replacedDir, oldDir)
1025
1026 newReplacedPath, err := filepath.Rel(modFileDir, newPkgDir+suffix)
1027 if err != nil {
1028 return err
1029 }
1030
1031 newReplacedPath = filepath.ToSlash(newReplacedPath)
1032
1033 if !strings.HasPrefix(newReplacedPath, "/") && !strings.HasPrefix(newReplacedPath, "../") {
1034 newReplacedPath = "./" + newReplacedPath
1035 }
1036
1037 if err := copied.AddReplace(r.Old.Path, "", newReplacedPath, ""); err != nil {
1038 return err
1039 }
1040 }
1041
1042 copied.Cleanup()
1043 newContent, err := copied.Format()
1044 if err != nil {
1045 return err
1046 }
1047
1048 // Calculate the edits to be made due to the change.
1049 edits := diff.Bytes(pm.Mapper.Content, newContent)
1050 renamingEdits[pm.URI] = append(renamingEdits[pm.URI], edits...)
1051 }
1052 return nil
1053 }
1054
1055 // updatePackageDeclsAndImports computes all workspace edits required to rename the package
1056 // described by the given metadata, to newName, by renaming its package
1057 // directory.
1058 //
1059 // It updates package clauses and import paths for the renamed package as well
1060 // as any other packages affected by the directory renaming among all packages
1061 // known to the snapshot.
1062 func updatePackageDeclsAndImports(ctx context.Context, s *cache.Snapshot, f file.Handle, newName PackageName, newPkgPath PackagePath, renamingEdits map[protocol.DocumentURI][]diff.Edit, moveSubpackages bool) error {
1063 if strings.HasSuffix(string(newName), "_test") {
1064 return fmt.Errorf("cannot rename to _test package")
1065 }
1066
1067 // We need metadata for the relevant package and module paths.
1068 // These should be the same for all packages containing the file.
1069 meta, err := s.NarrowestMetadataForFile(ctx, f.URI())
1070 if err != nil {
1071 return err
1072 }
1073
1074 oldPkgPath := meta.PkgPath
1075 if meta.Module == nil {
1076 return fmt.Errorf("cannot rename package: missing module information for package %q", meta.PkgPath)
1077 }
1078 modulePath := PackagePath(meta.Module.Path)
1079 if modulePath == oldPkgPath {
1080 return fmt.Errorf("cannot rename package: module path %q is the same as the package path, so renaming the package directory would have no effect", modulePath)
1081 }
1082
1083 // We must inspect all packages, not just direct importers,
1084 // because we might also rename subpackages, which may be unrelated.
1085 // (If the renamed package imports a subpackage it may require
1086 // edits to both its package and import decls.)
1087 allMetadata, err := s.AllMetadata(ctx)
1088 if err != nil {
1089 return err
1090 }
1091 // Rename package and import declarations in all relevant packages.
1092 for _, mp := range allMetadata {
1093 // Special case: x_test packages for the renamed package will not have the
1094 // package path as a dir prefix, but still need their package clauses
1095 // renamed.
1096 if mp.PkgPath == oldPkgPath+"_test" {
1097 if err := renamePackageClause(ctx, mp, s, newName+"_test", renamingEdits); err != nil {
1098 return err
1099 }
1100 continue
1101 }
1102
1103 // Subtle: check this condition before checking for valid module info
1104 // below, because we should not fail this operation if unrelated packages
1105 // lack module info.
1106 if moveSubpackages && !pathutil.InDir(filepath.FromSlash(string(oldPkgPath)), filepath.FromSlash(string(mp.PkgPath))) ||
1107 !moveSubpackages && mp.PkgPath != oldPkgPath {
1108 continue // not affected by the package renaming
1109 }
1110
1111 if mp.Module == nil {
1112 // This check will always fail under Bazel.
1113 return fmt.Errorf("cannot rename package: missing module information for package %q", mp.PkgPath)
1114 }
1115
1116 if modulePath != PackagePath(mp.Module.Path) {
1117 continue // don't edit imports if nested package and renaming package have different module paths
1118 }
1119
1120 // Renaming a package consists of changing its import path and package name.
1121 suffix := strings.TrimPrefix(string(mp.PkgPath), string(oldPkgPath))
1122 newImportPath := string(newPkgPath) + suffix
1123
1124 pkgName := mp.Name
1125 if mp.PkgPath == oldPkgPath {
1126 pkgName = newName
1127
1128 if err := renamePackageClause(ctx, mp, s, newName, renamingEdits); err != nil {
1129 return err
1130 }
1131 }
1132 imp := ImportPath(newImportPath) // TODO(adonovan): what if newImportPath has vendor/ prefix?
1133 if err := renameImports(ctx, s, mp, imp, pkgName, renamingEdits); err != nil {
1134 return err
1135 }
1136 }
1137
1138 return nil
1139 }
1140
1141 // renamePackageClause computes edits renaming the package clause of files in
1142 // the package described by the given metadata, to newName.
1143 //
1144 // Edits are written into the edits map.
1145 func renamePackageClause(ctx context.Context, mp *metadata.Package, snapshot *cache.Snapshot, newName PackageName, edits map[protocol.DocumentURI][]diff.Edit) error {
1146 // Rename internal references to the package in the renaming package.
1147 for _, uri := range mp.CompiledGoFiles {
1148 fh, err := snapshot.ReadFile(ctx, uri)
1149 if err != nil {
1150 return err
1151 }
1152 f, err := snapshot.ParseGo(ctx, fh, parsego.Header)
1153 if err != nil {
1154 return err
1155 }
1156 if f.File.Name == nil {
1157 continue // no package declaration
1158 }
1159
1160 edit, err := posEdit(f.Tok, f.File.Name.Pos(), f.File.Name.End(), string(newName))
1161 if err != nil {
1162 return err
1163 }
1164 edits[f.URI] = append(edits[f.URI], edit)
1165 }
1166
1167 return nil
1168 }
1169
1170 // renameImports computes the set of edits to imports resulting from renaming
1171 // the package described by the given metadata, to a package with import path
1172 // newPath and name newName.
1173 //
1174 // Edits are written into the edits map.
1175 func renameImports(ctx context.Context, snapshot *cache.Snapshot, mp *metadata.Package, newPath ImportPath, newName PackageName, allEdits map[protocol.DocumentURI][]diff.Edit) error {
1176 rdeps, err := snapshot.ReverseDependencies(ctx, mp.ID, false) // find direct importers
1177 if err != nil {
1178 return err
1179 }
1180
1181 // Pass 1: rename import paths in import declarations.
1182 needsTypeCheck := make(map[PackageID][]protocol.DocumentURI)
1183 for _, rdep := range rdeps {
1184 if rdep.IsIntermediateTestVariant() {
1185 continue // for renaming, these variants are redundant
1186 }
1187
1188 for _, uri := range rdep.CompiledGoFiles {
1189 fh, err := snapshot.ReadFile(ctx, uri)
1190 if err != nil {
1191 return err
1192 }
1193 f, err := snapshot.ParseGo(ctx, fh, parsego.Header)
1194 if err != nil {
1195 return err
1196 }
1197 if f.File.Name == nil {
1198 continue // no package declaration
1199 }
1200 for _, imp := range f.File.Imports {
1201 if rdep.DepsByImpPath[metadata.UnquoteImportPath(imp)] != mp.ID {
1202 continue // not the import we're looking for
1203 }
1204
1205 // If we are moving a package from a non-internal directory to
1206 // an internal directory, and there is an importer located in a
1207 // different module, then it is an invalid import.
1208 //
1209 // We do not prevent moves from an internal directory to a
1210 // non-internal directory.
1211 if !metadata.IsValidImport(rdep.PkgPath, metadata.PackagePath(newPath), snapshot.View().Type() != cache.GoPackagesDriverView) {
1212 return fmt.Errorf("invalid: package move would result in illegal internal import")
1213 }
1214
1215 // If the import does not explicitly specify
1216 // a local name, then we need to invoke the
1217 // type checker to locate references to update.
1218 //
1219 // TODO(adonovan): is this actually true?
1220 // Renaming an import with a local name can still
1221 // cause conflicts: shadowing of built-ins, or of
1222 // package-level decls in the same or another file.
1223 if imp.Name == nil {
1224 needsTypeCheck[rdep.ID] = append(needsTypeCheck[rdep.ID], uri)
1225 }
1226
1227 // Create text edit for the import path (string literal).
1228 edit, err := posEdit(f.Tok, imp.Path.Pos(), imp.Path.End(), strconv.Quote(string(newPath)))
1229 if err != nil {
1230 return err
1231 }
1232 allEdits[uri] = append(allEdits[uri], edit)
1233 }
1234 }
1235 }
1236
1237 // If the imported package's name hasn't changed,
1238 // we don't need to rename references within each file.
1239 if newName == mp.Name {
1240 return nil
1241 }
1242
1243 // Pass 2: rename local name (types.PkgName) of imported
1244 // package throughout one or more files of the package.
1245 ids := make([]PackageID, 0, len(needsTypeCheck))
1246 for id := range needsTypeCheck {
1247 ids = append(ids, id)
1248 }
1249 pkgs, err := snapshot.TypeCheck(ctx, ids...)
1250 if err != nil {
1251 return err
1252 }
1253 for i, id := range ids {
1254 pkg := pkgs[i]
1255 for _, uri := range needsTypeCheck[id] {
1256 f, err := pkg.File(uri)
1257 if err != nil {
1258 return err
1259 }
1260 for _, imp := range f.File.Imports {
1261 if imp.Name != nil {
1262 continue // has explicit local name
1263 }
1264 if rdeps[id].DepsByImpPath[metadata.UnquoteImportPath(imp)] != mp.ID {
1265 continue // not the import we're looking for
1266 }
1267
1268 pkgname, ok := pkg.TypesInfo().Implicits[imp].(*types.PkgName)
1269 if !ok {
1270 // "can't happen", but be defensive (#71656)
1271 return fmt.Errorf("internal error: missing type information for %s import at %s",
1272 imp.Path.Value, safetoken.StartPosition(pkg.FileSet(), imp.Pos()))
1273 }
1274
1275 pkgScope := pkg.Types().Scope()
1276 fileScope := pkg.TypesInfo().Scopes[f.File]
1277
1278 localName := string(newName)
1279 try := 0
1280
1281 // Keep trying with fresh names until one succeeds.
1282 //
1283 // TODO(adonovan): fix: this loop is not sufficient to choose a name
1284 // that is guaranteed to be conflict-free; renameObj may still fail.
1285 // So the retry loop should be around renameObj, and we shouldn't
1286 // bother with scopes here.
1287 for fileScope.Lookup(localName) != nil || pkgScope.Lookup(localName) != nil {
1288 try++
1289 localName = fmt.Sprintf("%s%d", newName, try)
1290 }
1291
1292 // renameObj detects various conflicts, including:
1293 // - new name conflicts with a package-level decl in this file;
1294 // - new name hides a package-level decl in another file that
1295 // is actually referenced in this file;
1296 // - new name hides a built-in that is actually referenced
1297 // in this file;
1298 // - a reference in this file to the old package name would
1299 // become shadowed by an intervening declaration that
1300 // uses the new name.
1301 // It returns the edits if no conflict was detected.
1302 editMap, _, err := renameObjects(localName, pkg, pkgname)
1303 if err != nil {
1304 return err
1305 }
1306
1307 // If the chosen local package name matches the package's
1308 // new name, delete the change that would have inserted
1309 // an explicit local name, which is always the lexically
1310 // first change.
1311 if localName == string(newName) {
1312 edits, ok := editMap[uri]
1313 if !ok {
1314 return fmt.Errorf("internal error: no changes for %s", uri)
1315 }
1316 diff.SortEdits(edits)
1317 editMap[uri] = edits[1:]
1318 }
1319 for uri, edits := range editMap {
1320 allEdits[uri] = append(allEdits[uri], edits...)
1321 }
1322 }
1323 }
1324 }
1325 return nil
1326 }
1327
1328 // renameObjects computes the edits to the type-checked syntax package pkg
1329 // required to rename a set of target objects to newName.
1330 //
1331 // It also returns the set of objects that were found (due to
1332 // corresponding methods and embedded fields) to require renaming as a
1333 // consequence of the requested renamings.
1334 //
1335 // It returns an error if the renaming would cause a conflict.
1336 func renameObjects(newName string, pkg *cache.Package, targets ...types.Object) (map[protocol.DocumentURI][]diff.Edit, map[types.Object]bool, error) {
1337 r := renamer{
1338 pkg: pkg,
1339 objsToUpdate: make(map[types.Object]bool),
1340 from: targets[0].Name(),
1341 to: newName,
1342 }
1343
1344 // A renaming initiated at an interface method indicates the
1345 // intention to rename abstract and concrete methods as needed
1346 // to preserve assignability.
1347 // TODO(adonovan): pull this into the caller.
1348 for _, obj := range targets {
1349 if obj, ok := obj.(*types.Func); ok {
1350 recv := obj.Signature().Recv()
1351 if recv != nil && types.IsInterface(recv.Type().Underlying()) {
1352 r.changeMethods = true
1353 break
1354 }
1355 }
1356 }
1357
1358 // Check that the renaming of the identifier is ok.
1359 for _, obj := range targets {
1360 r.check(obj)
1361 if len(r.conflicts) > 0 {
1362 // Stop at first error.
1363 return nil, nil, fmt.Errorf("%s", strings.Join(r.conflicts, "\n"))
1364 }
1365 }
1366
1367 editMap, err := r.update()
1368 if err != nil {
1369 return nil, nil, err
1370 }
1371
1372 // Remove initial targets so that only 'consequences' remain.
1373 for _, obj := range targets {
1374 delete(r.objsToUpdate, obj)
1375 }
1376 return editMap, r.objsToUpdate, nil
1377 }
1378
1379 // Rename all references to the target objects.
1380 func (r *renamer) update() (map[protocol.DocumentURI][]diff.Edit, error) {
1381 result := make(map[protocol.DocumentURI][]diff.Edit)
1382
1383 // shouldUpdate reports whether obj is one of (or an
1384 // instantiation of one of) the target objects.
1385 shouldUpdate := func(obj types.Object) bool {
1386 return containsOrigin(r.objsToUpdate, obj)
1387 }
1388
1389 // Find all identifiers in the package that define or use a
1390 // renamed object. We iterate over info as it is more efficient
1391 // than calling ast.Inspect for each of r.pkg.CompiledGoFiles().
1392 type item struct {
1393 node ast.Node // Ident, ImportSpec (obj=PkgName), or CaseClause (obj=Var)
1394 obj types.Object
1395 isDef bool
1396 }
1397 var items []item
1398 info := r.pkg.TypesInfo()
1399 for id, obj := range info.Uses {
1400 if shouldUpdate(obj) {
1401 items = append(items, item{id, obj, false})
1402 }
1403 }
1404 for id, obj := range info.Defs {
1405 if shouldUpdate(obj) {
1406 items = append(items, item{id, obj, true})
1407 }
1408 }
1409 for node, obj := range info.Implicits {
1410 if shouldUpdate(obj) {
1411 switch node.(type) {
1412 case *ast.ImportSpec, *ast.CaseClause:
1413 items = append(items, item{node, obj, true})
1414 }
1415 }
1416 }
1417 sort.Slice(items, func(i, j int) bool {
1418 return items[i].node.Pos() < items[j].node.Pos()
1419 })
1420
1421 // Update each identifier, and its doc comment if it is a declaration.
1422 for _, item := range items {
1423 pgf, err := r.pkg.FileEnclosing(item.node.Pos())
1424 if err != nil {
1425 bug.Reportf("edit does not belong to syntax of package %q: %v", r.pkg, err)
1426 continue
1427 }
1428
1429 // Renaming a types.PkgName may result in the addition or removal of an identifier,
1430 // so we deal with this separately.
1431 if pkgName, ok := item.obj.(*types.PkgName); ok && item.isDef {
1432 edit, err := r.updatePkgName(pgf, pkgName)
1433 if err != nil {
1434 return nil, err
1435 }
1436 result[pgf.URI] = append(result[pgf.URI], edit)
1437 continue
1438 }
1439
1440 // Workaround the unfortunate lack of a Var object
1441 // for x in "switch x := expr.(type) {}" by adjusting
1442 // the case clause to the switch ident.
1443 // This may result in duplicate edits, but we de-dup later.
1444 if _, ok := item.node.(*ast.CaseClause); ok {
1445 path, _ := goastutil.PathEnclosingInterval(pgf.File, item.obj.Pos(), item.obj.Pos())
1446 item.node = path[0].(*ast.Ident)
1447 }
1448
1449 // Replace the identifier with r.to.
1450 edit, err := posEdit(pgf.Tok, item.node.Pos(), item.node.End(), r.to)
1451 if err != nil {
1452 return nil, err
1453 }
1454
1455 result[pgf.URI] = append(result[pgf.URI], edit)
1456
1457 if !item.isDef { // uses do not have doc comments to update.
1458 continue
1459 }
1460
1461 cur, _ := pgf.Cursor().FindNode(item.node) // can't fail
1462 doc := docComment(pgf, cur)
1463 if doc == nil {
1464 continue
1465 }
1466
1467 // Perform the rename in doc comments declared in the original package.
1468 // go/parser strips out \r\n returns from the comment text, so go
1469 // line-by-line through the comment text to get the correct positions.
1470 docRegexp := regexp.MustCompile(`\b` + r.from + `\b`) // valid identifier => valid regexp
1471 for _, comment := range doc.List {
1472 if isDirective(comment.Text) {
1473 continue
1474 }
1475 // TODO(adonovan): why are we looping over lines?
1476 // Just run the loop body once over the entire multiline comment.
1477 lines := strings.Split(comment.Text, "\n")
1478 tokFile := pgf.Tok
1479 commentLine := safetoken.Line(tokFile, comment.Pos())
1480 uri := protocol.URIFromPath(tokFile.Name())
1481 for i, line := range lines {
1482 lineStart := comment.Pos()
1483 if i > 0 {
1484 lineStart = tokFile.LineStart(commentLine + i)
1485 }
1486 for _, locs := range docRegexp.FindAllIndex([]byte(line), -1) {
1487 edit, err := posEdit(tokFile, lineStart+token.Pos(locs[0]), lineStart+token.Pos(locs[1]), r.to)
1488 if err != nil {
1489 return nil, err // can't happen
1490 }
1491 result[uri] = append(result[uri], edit)
1492 }
1493 }
1494 }
1495 }
1496
1497 docLinkEdits, err := r.updateCommentDocLinks()
1498 if err != nil {
1499 return nil, err
1500 }
1501 for uri, edits := range docLinkEdits {
1502 result[uri] = append(result[uri], edits...)
1503 }
1504
1505 return result, nil
1506 }
1507
1508 // updateCommentDocLinks updates each doc comment in the package
1509 // that refers to one of the renamed objects using a doc link
1510 // (https://golang.org/doc/comment#doclinks) such as "[pkg.Type.Method]".
1511 func (r *renamer) updateCommentDocLinks() (map[protocol.DocumentURI][]diff.Edit, error) {
1512 result := make(map[protocol.DocumentURI][]diff.Edit)
1513 var docRenamers []*docLinkRenamer
1514 for obj := range r.objsToUpdate {
1515 if _, ok := obj.(*types.PkgName); ok {
1516 // The dot package name will not be referenced
1517 if obj.Name() == "." {
1518 continue
1519 }
1520
1521 docRenamers = append(docRenamers, &docLinkRenamer{
1522 isDep: false,
1523 isPkgOrType: true,
1524 file: r.pkg.FileSet().File(obj.Pos()),
1525 regexp: docLinkPattern("", "", obj.Name(), true),
1526 to: r.to,
1527 })
1528 continue
1529 }
1530 if !obj.Exported() {
1531 continue
1532 }
1533 recvName := ""
1534 // Doc links can reference only exported package-level objects
1535 // and methods of exported package-level named types.
1536 if !typesinternal.IsPackageLevel(obj) {
1537 obj, isFunc := obj.(*types.Func)
1538 if !isFunc {
1539 continue
1540 }
1541 recv := obj.Signature().Recv()
1542 if recv == nil {
1543 continue
1544 }
1545 _, named := typesinternal.ReceiverNamed(recv)
1546 if named == nil {
1547 continue
1548 }
1549 // Doc links can't reference interface methods.
1550 if types.IsInterface(named.Underlying()) {
1551 continue
1552 }
1553 name := named.Origin().Obj()
1554 if !name.Exported() || !typesinternal.IsPackageLevel(name) {
1555 continue
1556 }
1557 recvName = name.Name()
1558 }
1559
1560 // Qualify objects from other packages.
1561 pkgName := ""
1562 if r.pkg.Types() != obj.Pkg() {
1563 pkgName = obj.Pkg().Name()
1564 }
1565 _, isTypeName := obj.(*types.TypeName)
1566 docRenamers = append(docRenamers, &docLinkRenamer{
1567 isDep: r.pkg.Types() != obj.Pkg(),
1568 isPkgOrType: isTypeName,
1569 packagePath: obj.Pkg().Path(),
1570 packageName: pkgName,
1571 recvName: recvName,
1572 objName: obj.Name(),
1573 regexp: docLinkPattern(pkgName, recvName, obj.Name(), isTypeName),
1574 to: r.to,
1575 })
1576 }
1577 for _, pgf := range r.pkg.CompiledGoFiles() {
1578 for _, d := range docRenamers {
1579 edits, err := d.update(pgf)
1580 if err != nil {
1581 return nil, err
1582 }
1583 if len(edits) > 0 {
1584 result[pgf.URI] = append(result[pgf.URI], edits...)
1585 }
1586 }
1587 }
1588 return result, nil
1589 }
1590
1591 // docLinkPattern returns a regular expression that matches doclinks in comments.
1592 // It has one submatch that indicates the symbol to be updated.
1593 func docLinkPattern(pkgName, recvName, objName string, isPkgOrType bool) *regexp.Regexp {
1594 // The doc link may contain a leading star, e.g. [*bytes.Buffer].
1595 pattern := `\[\*?`
1596 if pkgName != "" {
1597 pattern += pkgName + `\.`
1598 }
1599 if recvName != "" {
1600 pattern += recvName + `\.`
1601 }
1602 // The first submatch is object name.
1603 pattern += `(` + objName + `)`
1604 // If the object is a *types.TypeName or *types.PkgName, also need
1605 // match the objects referenced by them, so add `(\.\w+)*`.
1606 if isPkgOrType {
1607 pattern += `(?:\.\w+)*`
1608 }
1609 // There are two type of link in comments:
1610 // 1. url link. e.g. [text]: url
1611 // 2. doc link. e.g. [pkg.Name]
1612 // in order to only match the doc link, add `([^:]|$)` in the end.
1613 pattern += `\](?:[^:]|$)`
1614
1615 return regexp.MustCompile(pattern)
1616 }
1617
1618 // A docLinkRenamer renames doc links of forms such as these:
1619 //
1620 // [Func]
1621 // [pkg.Func]
1622 // [RecvType.Method]
1623 // [*Type]
1624 // [*pkg.Type]
1625 // [*pkg.RecvType.Method]
1626 type docLinkRenamer struct {
1627 isDep bool // object is from a dependency package
1628 isPkgOrType bool // object is *types.PkgName or *types.TypeName
1629 packagePath string
1630 packageName string // e.g. "pkg"
1631 recvName string // e.g. "RecvType"
1632 objName string // e.g. "Func", "Type", "Method"
1633 to string // new name
1634 regexp *regexp.Regexp
1635
1636 file *token.File // enclosing file, if renaming *types.PkgName
1637 }
1638
1639 // update updates doc links in the package level comments.
1640 func (r *docLinkRenamer) update(pgf *parsego.File) (result []diff.Edit, err error) {
1641 if r.file != nil && r.file != pgf.Tok {
1642 return nil, nil
1643 }
1644 pattern := r.regexp
1645 // If the object is in dependency package,
1646 // the imported name in the file may be different from the original package name
1647 if r.isDep {
1648 for _, spec := range pgf.File.Imports {
1649 importPath, _ := strconv.Unquote(spec.Path.Value)
1650 if importPath == r.packagePath {
1651 // Ignore blank imports
1652 if spec.Name == nil || spec.Name.Name == "_" || spec.Name.Name == "." {
1653 continue
1654 }
1655 if spec.Name.Name != r.packageName {
1656 pattern = docLinkPattern(spec.Name.Name, r.recvName, r.objName, r.isPkgOrType)
1657 }
1658 break
1659 }
1660 }
1661 }
1662
1663 var edits []diff.Edit
1664 updateDocLinks := func(doc *ast.CommentGroup) error {
1665 if doc != nil {
1666 for _, c := range doc.List {
1667 for _, locs := range pattern.FindAllStringSubmatchIndex(c.Text, -1) {
1668 // The first submatch is the object name, so the locs[2:4] is the index of object name.
1669 edit, err := posEdit(pgf.Tok, c.Pos()+token.Pos(locs[2]), c.Pos()+token.Pos(locs[3]), r.to)
1670 if err != nil {
1671 return err
1672 }
1673 edits = append(edits, edit)
1674 }
1675 }
1676 }
1677 return nil
1678 }
1679
1680 // Update package doc comments.
1681 err = updateDocLinks(pgf.File.Doc)
1682 if err != nil {
1683 return nil, err
1684 }
1685 for _, decl := range pgf.File.Decls {
1686 var doc *ast.CommentGroup
1687 switch decl := decl.(type) {
1688 case *ast.GenDecl:
1689 doc = decl.Doc
1690 case *ast.FuncDecl:
1691 doc = decl.Doc
1692 }
1693 err = updateDocLinks(doc)
1694 if err != nil {
1695 return nil, err
1696 }
1697 }
1698 return edits, nil
1699 }
1700
1701 // docComment returns the doc for an identifier within the specified file.
1702 func docComment(pgf *parsego.File, curId inspector.Cursor) *ast.CommentGroup {
1703 // (Strictly it needn't be an identifier; only its Pos is used.)
1704 id := curId.Node().(*ast.Ident)
1705 for cur := range curId.Enclosing() {
1706 switch decl := cur.Node().(type) {
1707 case *ast.FuncDecl:
1708 return decl.Doc
1709 case *ast.Field:
1710 return decl.Doc
1711 case *ast.GenDecl:
1712 return decl.Doc
1713 // For {Type,Value}Spec, if the doc on the spec is absent,
1714 // search for the enclosing GenDecl
1715 case *ast.TypeSpec:
1716 if decl.Doc != nil {
1717 return decl.Doc
1718 }
1719 case *ast.ValueSpec:
1720 if decl.Doc != nil {
1721 return decl.Doc
1722 }
1723 case *ast.Ident:
1724 case *ast.AssignStmt:
1725 // *ast.AssignStmt doesn't have an associated comment group.
1726 // So, we try to find a comment just before the identifier.
1727
1728 // Try to find a comment group only for short variable declarations (:=).
1729 if decl.Tok != token.DEFINE {
1730 return nil
1731 }
1732
1733 identLine := safetoken.Line(pgf.Tok, id.Pos())
1734 for _, comment := range pgf.File.Comments {
1735 if comment.Pos() > id.Pos() {
1736 // Comment is after the identifier.
1737 continue
1738 }
1739
1740 lastCommentLine := safetoken.Line(pgf.Tok, comment.End())
1741 if lastCommentLine+1 == identLine {
1742 return comment
1743 }
1744 }
1745 default:
1746 return nil
1747 }
1748 }
1749 return nil
1750 }
1751
1752 // docCommentPosToIdent returns a cursor for the identifier whose doc
1753 // comment contains pos, if any. The pos must be within an occurrence
1754 // of the identifier's name, otherwise it returns zero.
1755 func docCommentPosToIdent(pgf *parsego.File, start, end token.Pos, cur inspector.Cursor) (inspector.Cursor, bool) {
1756 for curId := range cur.Preorder((*ast.Ident)(nil)) {
1757 id := curId.Node().(*ast.Ident)
1758 if start > id.Pos() {
1759 continue // Doc comments are not located after an ident.
1760 }
1761 doc := docComment(pgf, curId)
1762 if doc == nil || !(doc.Pos() <= start && end < doc.End()) {
1763 continue
1764 }
1765
1766 docRegexp := regexp.MustCompile(`\b` + id.Name + `\b`)
1767 for _, comment := range doc.List {
1768 if isDirective(comment.Text) || !(comment.Pos() <= start && end < comment.End()) {
1769 continue
1770 }
1771 commentStart := comment.Pos()
1772 text, err := pgf.NodeText(comment)
1773 if err != nil {
1774 return inspector.Cursor{}, false
1775 }
1776 for _, locs := range docRegexp.FindAllIndex(text, -1) {
1777 matchStart := commentStart + token.Pos(locs[0])
1778 matchEnd := commentStart + token.Pos(locs[1])
1779 if matchStart <= start && end <= matchEnd {
1780 return curId, true
1781 }
1782 }
1783 }
1784 }
1785 return inspector.Cursor{}, false
1786 }
1787
1788 // updatePkgName returns the updates to rename a pkgName in the import spec by
1789 // only modifying the package name portion of the import declaration.
1790 func (r *renamer) updatePkgName(pgf *parsego.File, pkgName *types.PkgName) (diff.Edit, error) {
1791 // Modify ImportSpec syntax to add or remove the Name as needed.
1792 path, _ := goastutil.PathEnclosingInterval(pgf.File, pkgName.Pos(), pkgName.Pos())
1793 if len(path) < 2 {
1794 return diff.Edit{}, fmt.Errorf("no path enclosing interval for %s", pkgName.Name())
1795 }
1796 spec, ok := path[1].(*ast.ImportSpec)
1797 if !ok {
1798 return diff.Edit{}, fmt.Errorf("failed to update PkgName for %s", pkgName.Name())
1799 }
1800
1801 newText := ""
1802 if pkgName.Imported().Name() != r.to {
1803 newText = r.to + " "
1804 }
1805
1806 // Replace the portion (possibly empty) of the spec before the path:
1807 // local "path" or "path"
1808 // -> <- -><-
1809 return posEdit(pgf.Tok, spec.Pos(), spec.Path.Pos(), newText)
1810 }
1811
1812 // parsePackageNameDecl is a convenience function that parses and
1813 // returns the package name declaration of file fh, and reports
1814 // whether the position ppos lies within it.
1815 //
1816 // Note: also used by references.
1817 func parsePackageNameDecl(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) (*parsego.File, bool, error) {
1818 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Header)
1819 if err != nil {
1820 return nil, false, err
1821 }
1822 // Careful: because we used parsego.Header,
1823 // pgf.Pos(ppos) may be beyond EOF => (0, err).
1824 start, end, _ := pgf.RangePos(rng)
1825 return pgf, astutil.NodeContains(pgf.File.Name, astutil.RangeOf(start, end)), nil
1826 }
1827
1828 // posEdit returns an edit to replace the (start, end) range of tf with 'new'.
1829 func posEdit(tf *token.File, start, end token.Pos, new string) (diff.Edit, error) {
1830 startOffset, endOffset, err := safetoken.Offsets(tf, start, end)
1831 if err != nil {
1832 return diff.Edit{}, err
1833 }
1834 return diff.Edit{Start: startOffset, End: endOffset, New: new}, nil
1835 }