Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 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 source |
| 6 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 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), |
Alan Donovan | b71392a | 2023-06-13 11:47:20 -0400 | [diff] [blame] | 24 | // package with missing imports; |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 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 | |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 44 | import ( |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 45 | "context" |
| 46 | "errors" |
| 47 | "fmt" |
| 48 | "go/ast" |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 49 | "go/token" |
| 50 | "go/types" |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 51 | "path" |
Dung Le | 1a08d01 | 2022-12-27 23:06:42 +0700 | [diff] [blame] | 52 | "path/filepath" |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 53 | "regexp" |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 54 | "sort" |
| 55 | "strconv" |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 56 | "strings" |
| 57 | |
Dung Le | 1a08d01 | 2022-12-27 23:06:42 +0700 | [diff] [blame] | 58 | "golang.org/x/mod/modfile" |
Robert Findley | b15a5bc | 2023-01-31 17:38:50 -0500 | [diff] [blame] | 59 | "golang.org/x/tools/go/ast/astutil" |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 60 | "golang.org/x/tools/go/types/objectpath" |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 61 | "golang.org/x/tools/go/types/typeutil" |
Alan Donovan | 4baa3dc | 2023-04-25 10:21:06 -0400 | [diff] [blame] | 62 | "golang.org/x/tools/gopls/internal/bug" |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 63 | "golang.org/x/tools/gopls/internal/lsp/protocol" |
Alan Donovan | d96b238 | 2022-09-30 21:58:21 -0400 | [diff] [blame] | 64 | "golang.org/x/tools/gopls/internal/lsp/safetoken" |
Alan Donovan | 26a95e6 | 2022-10-07 10:40:32 -0400 | [diff] [blame] | 65 | "golang.org/x/tools/gopls/internal/span" |
Alan Donovan | 6782af0 | 2022-09-19 15:18:43 -0400 | [diff] [blame] | 66 | "golang.org/x/tools/internal/diff" |
| 67 | "golang.org/x/tools/internal/event" |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 68 | "golang.org/x/tools/internal/typeparams" |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 69 | "golang.org/x/tools/refactor/satisfy" |
| 70 | ) |
| 71 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 72 | // A renamer holds state of a single call to renameObj, which renames |
| 73 | // an object (or several coupled objects) within a single type-checked |
| 74 | // syntax package. |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 75 | type renamer struct { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 76 | pkg Package // the syntax package in which the renaming is applied |
| 77 | objsToUpdate map[types.Object]bool // records progress of calls to check |
| 78 | hadConflicts bool |
Alan Donovan | 80afb09 | 2023-02-07 15:42:30 -0500 | [diff] [blame] | 79 | conflicts []string |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 80 | from, to string |
| 81 | satisfyConstraints map[satisfy.Constraint]bool |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 82 | msets typeutil.MethodSetCache |
| 83 | changeMethods bool |
| 84 | } |
| 85 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 86 | // A PrepareItem holds the result of a "prepare rename" operation: |
| 87 | // the source range and value of a selected identifier. |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 88 | type PrepareItem struct { |
| 89 | Range protocol.Range |
| 90 | Text string |
| 91 | } |
| 92 | |
| 93 | // PrepareRename searches for a valid renaming at position pp. |
| 94 | // |
| 95 | // The returned usererr is intended to be displayed to the user to explain why |
| 96 | // the prepare fails. Probably we could eliminate the redundancy in returning |
| 97 | // two errors, but for now this is done defensively. |
| 98 | func PrepareRename(ctx context.Context, snapshot Snapshot, f FileHandle, pp protocol.Position) (_ *PrepareItem, usererr, err error) { |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 99 | ctx, done := event.Start(ctx, "source.PrepareRename") |
| 100 | defer done() |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 101 | |
Alan Donovan | d7dfffd | 2022-12-08 00:37:50 -0500 | [diff] [blame] | 102 | // Is the cursor within the package name declaration? |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 103 | if pgf, inPackageName, err := parsePackageNameDecl(ctx, snapshot, f, pp); err != nil { |
Alan Donovan | d7dfffd | 2022-12-08 00:37:50 -0500 | [diff] [blame] | 104 | return nil, err, err |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 105 | } else if inPackageName { |
| 106 | item, err := prepareRenamePackageName(ctx, snapshot, pgf) |
| 107 | return item, err, err |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 108 | } |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 109 | |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 110 | // Ordinary (non-package) renaming. |
| 111 | // |
| 112 | // Type-check the current package, locate the reference at the position, |
| 113 | // validate the object, and report its name and range. |
| 114 | // |
| 115 | // TODO(adonovan): in all cases below, we return usererr=nil, |
| 116 | // which means we return (nil, nil) at the protocol |
| 117 | // layer. This seems like a bug, or at best an exploitation of |
| 118 | // knowledge of VSCode-specific behavior. Can we avoid that? |
Alan Donovan | b35949e | 2023-04-20 14:53:41 -0400 | [diff] [blame] | 119 | pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, f.URI()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 120 | if err != nil { |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 121 | return nil, nil, err |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 122 | } |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 123 | pos, err := pgf.PositionPos(pp) |
| 124 | if err != nil { |
| 125 | return nil, nil, err |
| 126 | } |
| 127 | targets, node, err := objectsAt(pkg.GetTypesInfo(), pgf.File, pos) |
| 128 | if err != nil { |
| 129 | return nil, nil, err |
| 130 | } |
| 131 | var obj types.Object |
| 132 | for obj = range targets { |
| 133 | break // pick one arbitrarily |
| 134 | } |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 135 | if err := checkRenamable(obj); err != nil { |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 136 | return nil, nil, err |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 137 | } |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 138 | rng, err := pgf.NodeRange(node) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 139 | if err != nil { |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 140 | return nil, nil, err |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 141 | } |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 142 | if _, isImport := node.(*ast.ImportSpec); isImport { |
| 143 | // We're not really renaming the import path. |
| 144 | rng.End = rng.Start |
| 145 | } |
| 146 | return &PrepareItem{ |
| 147 | Range: rng, |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 148 | Text: obj.Name(), |
| 149 | }, nil, nil |
| 150 | } |
| 151 | |
| 152 | func prepareRenamePackageName(ctx context.Context, snapshot Snapshot, pgf *ParsedGoFile) (*PrepareItem, error) { |
| 153 | // Does the client support file renaming? |
| 154 | fileRenameSupported := false |
| 155 | for _, op := range snapshot.View().Options().SupportedResourceOperations { |
| 156 | if op == protocol.Rename { |
| 157 | fileRenameSupported = true |
| 158 | break |
| 159 | } |
| 160 | } |
| 161 | if !fileRenameSupported { |
| 162 | return nil, errors.New("can't rename package: LSP client does not support file renaming") |
| 163 | } |
| 164 | |
| 165 | // Check validity of the metadata for the file's containing package. |
Alan Donovan | b35949e | 2023-04-20 14:53:41 -0400 | [diff] [blame] | 166 | meta, err := NarrowestMetadataForFile(ctx, snapshot, pgf.URI) |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 167 | if err != nil { |
| 168 | return nil, err |
| 169 | } |
Alan Donovan | 1aa7e72 | 2023-01-27 11:02:04 -0500 | [diff] [blame] | 170 | if meta.Name == "main" { |
| 171 | return nil, fmt.Errorf("can't rename package \"main\"") |
| 172 | } |
| 173 | if strings.HasSuffix(string(meta.Name), "_test") { |
| 174 | return nil, fmt.Errorf("can't rename x_test packages") |
| 175 | } |
| 176 | if meta.Module == nil { |
| 177 | return nil, fmt.Errorf("can't rename package: missing module information for package %q", meta.PkgPath) |
| 178 | } |
| 179 | if meta.Module.Path == string(meta.PkgPath) { |
| 180 | return nil, fmt.Errorf("can't rename package: package path %q is the same as module path %q", meta.PkgPath, meta.Module.Path) |
| 181 | } |
| 182 | |
| 183 | // Return the location of the package declaration. |
| 184 | rng, err := pgf.NodeRange(pgf.File.Name) |
| 185 | if err != nil { |
| 186 | return nil, err |
| 187 | } |
| 188 | return &PrepareItem{ |
| 189 | Range: rng, |
| 190 | Text: string(meta.Name), |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 191 | }, nil |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 192 | } |
| 193 | |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 194 | func checkRenamable(obj types.Object) error { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 195 | switch obj := obj.(type) { |
| 196 | case *types.Var: |
| 197 | if obj.Embedded() { |
| 198 | return fmt.Errorf("can't rename embedded fields: rename the type directly or name the field") |
| 199 | } |
| 200 | case *types.Builtin, *types.Nil: |
| 201 | return fmt.Errorf("%s is built in and cannot be renamed", obj.Name()) |
| 202 | } |
| 203 | if obj.Pkg() == nil || obj.Pkg().Path() == "unsafe" { |
| 204 | // e.g. error.Error, unsafe.Pointer |
| 205 | return fmt.Errorf("%s is built in and cannot be renamed", obj.Name()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 206 | } |
| 207 | if obj.Name() == "_" { |
| 208 | return errors.New("can't rename \"_\"") |
| 209 | } |
| 210 | return nil |
| 211 | } |
| 212 | |
| 213 | // Rename returns a map of TextEdits for each file modified when renaming a |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 214 | // given identifier within a package and a boolean value of true for renaming |
| 215 | // package and false otherwise. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 216 | func Rename(ctx context.Context, snapshot Snapshot, f FileHandle, pp protocol.Position, newName string) (map[span.URI][]protocol.TextEdit, bool, error) { |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 217 | ctx, done := event.Start(ctx, "source.Rename") |
| 218 | defer done() |
| 219 | |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 220 | if !isValidIdentifier(newName) { |
| 221 | return nil, false, fmt.Errorf("invalid identifier to rename: %q", newName) |
| 222 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 223 | |
| 224 | // Cursor within package name declaration? |
| 225 | _, inPackageName, err := parsePackageNameDecl(ctx, snapshot, f, pp) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 226 | if err != nil { |
| 227 | return nil, false, err |
| 228 | } |
| 229 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 230 | var editMap map[span.URI][]diff.Edit |
| 231 | if inPackageName { |
| 232 | editMap, err = renamePackageName(ctx, snapshot, f, PackageName(newName)) |
| 233 | } else { |
| 234 | editMap, err = renameOrdinary(ctx, snapshot, f, pp, newName) |
| 235 | } |
| 236 | if err != nil { |
| 237 | return nil, false, err |
| 238 | } |
| 239 | |
| 240 | // Convert edits to protocol form. |
| 241 | result := make(map[span.URI][]protocol.TextEdit) |
| 242 | for uri, edits := range editMap { |
| 243 | // Sort and de-duplicate edits. |
| 244 | // |
| 245 | // Overlapping edits may arise in local renamings (due |
| 246 | // to type switch implicits) and globals ones (due to |
| 247 | // processing multiple package variants). |
| 248 | // |
| 249 | // We assume renaming produces diffs that are all |
| 250 | // replacements (no adjacent insertions that might |
| 251 | // become reordered) and that are either identical or |
| 252 | // non-overlapping. |
| 253 | diff.SortEdits(edits) |
| 254 | filtered := edits[:0] |
| 255 | for i, edit := range edits { |
| 256 | if i == 0 || edit != filtered[len(filtered)-1] { |
| 257 | filtered = append(filtered, edit) |
| 258 | } |
| 259 | } |
| 260 | edits = filtered |
| 261 | |
| 262 | // TODO(adonovan): the logic above handles repeat edits to the |
| 263 | // same file URI (e.g. as a member of package p and p_test) but |
| 264 | // is not sufficient to handle file-system level aliasing arising |
| 265 | // from symbolic or hard links. For that, we should use a |
| 266 | // robustio-FileID-keyed map. |
| 267 | // See https://go.dev/cl/457615 for example. |
| 268 | // This really occurs in practice, e.g. kubernetes has |
| 269 | // vendor/k8s.io/kubectl -> ../../staging/src/k8s.io/kubectl. |
Alan Donovan | 36ed0b1 | 2023-03-13 14:20:23 -0400 | [diff] [blame] | 270 | fh, err := snapshot.ReadFile(ctx, uri) |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 271 | if err != nil { |
| 272 | return nil, false, err |
| 273 | } |
Alan Donovan | 786752b | 2023-03-07 12:14:28 -0500 | [diff] [blame] | 274 | data, err := fh.Content() |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 275 | if err != nil { |
| 276 | return nil, false, err |
| 277 | } |
| 278 | m := protocol.NewMapper(uri, data) |
| 279 | protocolEdits, err := ToProtocolEdits(m, edits) |
| 280 | if err != nil { |
| 281 | return nil, false, err |
| 282 | } |
| 283 | result[uri] = protocolEdits |
| 284 | } |
| 285 | |
| 286 | return result, inPackageName, nil |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 287 | } |
| 288 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 289 | // renameOrdinary renames an ordinary (non-package) name throughout the workspace. |
| 290 | func renameOrdinary(ctx context.Context, snapshot Snapshot, f FileHandle, pp protocol.Position, newName string) (map[span.URI][]diff.Edit, error) { |
| 291 | // Type-check the referring package and locate the object(s). |
Alan Donovan | b35949e | 2023-04-20 14:53:41 -0400 | [diff] [blame] | 292 | // |
Alan Donovan | 660614b | 2023-04-20 16:11:13 -0400 | [diff] [blame] | 293 | // Unlike NarrowestPackageForFile, this operation prefers the |
| 294 | // widest variant as, for non-exported identifiers, it is the |
| 295 | // only package we need. (In case you're wondering why |
| 296 | // 'references' doesn't also want the widest variant: it |
| 297 | // computes the union across all variants.) |
Alan Donovan | b35949e | 2023-04-20 14:53:41 -0400 | [diff] [blame] | 298 | var targets map[types.Object]ast.Node |
| 299 | var pkg Package |
| 300 | { |
| 301 | metas, err := snapshot.MetadataForFile(ctx, f.URI()) |
| 302 | if err != nil { |
| 303 | return nil, err |
| 304 | } |
Alan Donovan | 660614b | 2023-04-20 16:11:13 -0400 | [diff] [blame] | 305 | RemoveIntermediateTestVariants(&metas) |
Alan Donovan | b35949e | 2023-04-20 14:53:41 -0400 | [diff] [blame] | 306 | if len(metas) == 0 { |
| 307 | return nil, fmt.Errorf("no package metadata for file %s", f.URI()) |
| 308 | } |
| 309 | widest := metas[len(metas)-1] // widest variant may include _test.go files |
| 310 | pkgs, err := snapshot.TypeCheck(ctx, widest.ID) |
| 311 | if err != nil { |
| 312 | return nil, err |
| 313 | } |
| 314 | pkg = pkgs[0] |
| 315 | pgf, err := pkg.File(f.URI()) |
| 316 | if err != nil { |
| 317 | return nil, err // "can't happen" |
| 318 | } |
| 319 | pos, err := pgf.PositionPos(pp) |
| 320 | if err != nil { |
| 321 | return nil, err |
| 322 | } |
| 323 | objects, _, err := objectsAt(pkg.GetTypesInfo(), pgf.File, pos) |
| 324 | if err != nil { |
| 325 | return nil, err |
| 326 | } |
| 327 | targets = objects |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 328 | } |
| 329 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 330 | // Pick a representative object arbitrarily. |
| 331 | // (All share the same name, pos, and kind.) |
| 332 | var obj types.Object |
| 333 | for obj = range targets { |
| 334 | break |
| 335 | } |
| 336 | if obj.Name() == newName { |
| 337 | return nil, fmt.Errorf("old and new names are the same: %s", newName) |
| 338 | } |
| 339 | if err := checkRenamable(obj); err != nil { |
| 340 | return nil, err |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 341 | } |
| 342 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 343 | // Find objectpath, if object is exported ("" otherwise). |
| 344 | var declObjPath objectpath.Path |
| 345 | if obj.Exported() { |
Rob Findley | 1561060 | 2023-07-28 10:34:23 -0400 | [diff] [blame] | 346 | // objectpath.For requires the origin of a generic function or type, not an |
| 347 | // instantiation (a bug?). Unfortunately we can't call Func.Origin as this |
| 348 | // is not available in go/types@go1.18. So we take a scenic route. |
| 349 | // |
| 350 | // Note that unlike Funcs, TypeNames are always canonical (they are "left" |
| 351 | // of the type parameters, unlike methods). |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 352 | switch obj.(type) { // avoid "obj :=" since cases reassign the var |
| 353 | case *types.TypeName: |
Rob Findley | 1561060 | 2023-07-28 10:34:23 -0400 | [diff] [blame] | 354 | if _, ok := obj.Type().(*typeparams.TypeParam); ok { |
Rob Findley | fe58b07 | 2023-07-28 10:19:12 -0400 | [diff] [blame] | 355 | // As with capitalized function parameters below, type parameters are |
| 356 | // local. |
| 357 | goto skipObjectPath |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 358 | } |
| 359 | case *types.Func: |
| 360 | obj = funcOrigin(obj.(*types.Func)) |
| 361 | case *types.Var: |
| 362 | // TODO(adonovan): do vars need the origin treatment too? (issue #58462) |
Alan Donovan | c6de5f5 | 2023-07-14 13:06:23 -0400 | [diff] [blame] | 363 | |
| 364 | // Function parameter and result vars that are (unusually) |
| 365 | // capitalized are technically exported, even though they |
| 366 | // cannot be referenced, because they may affect downstream |
| 367 | // error messages. But we can safely treat them as local. |
| 368 | // |
| 369 | // This is not merely an optimization: the renameExported |
| 370 | // operation gets confused by such vars. It finds them from |
| 371 | // objectpath, the classifies them as local vars, but as |
| 372 | // they came from export data they lack syntax and the |
| 373 | // correct scope tree (issue #61294). |
| 374 | if !obj.(*types.Var).IsField() && !isPackageLevel(obj) { |
| 375 | goto skipObjectPath |
| 376 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 377 | } |
| 378 | if path, err := objectpath.For(obj); err == nil { |
| 379 | declObjPath = path |
| 380 | } |
Alan Donovan | c6de5f5 | 2023-07-14 13:06:23 -0400 | [diff] [blame] | 381 | skipObjectPath: |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 382 | } |
| 383 | |
| 384 | // Nonexported? Search locally. |
| 385 | if declObjPath == "" { |
| 386 | var objects []types.Object |
| 387 | for obj := range targets { |
| 388 | objects = append(objects, obj) |
| 389 | } |
| 390 | editMap, _, err := renameObjects(ctx, snapshot, newName, pkg, objects...) |
| 391 | return editMap, err |
| 392 | } |
| 393 | |
| 394 | // Exported: search globally. |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 395 | // |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 396 | // For exported package-level var/const/func/type objects, the |
| 397 | // search scope is just the direct importers. |
| 398 | // |
| 399 | // For exported fields and methods, the scope is the |
| 400 | // transitive rdeps. (The exportedness of the field's struct |
| 401 | // or method's receiver is irrelevant.) |
| 402 | transitive := false |
| 403 | switch obj.(type) { |
| 404 | case *types.TypeName: |
| 405 | // Renaming an exported package-level type |
| 406 | // requires us to inspect all transitive rdeps |
| 407 | // in the event that the type is embedded. |
| 408 | // |
| 409 | // TODO(adonovan): opt: this is conservative |
| 410 | // but inefficient. Instead, expand the scope |
| 411 | // of the search only if we actually encounter |
| 412 | // an embedding of the type, and only then to |
| 413 | // the rdeps of the embedding package. |
| 414 | if obj.Parent() == obj.Pkg().Scope() { |
| 415 | transitive = true |
| 416 | } |
| 417 | |
| 418 | case *types.Var: |
| 419 | if obj.(*types.Var).IsField() { |
| 420 | transitive = true // field |
| 421 | } |
| 422 | |
| 423 | // TODO(adonovan): opt: process only packages that |
| 424 | // contain a reference (xrefs) to the target field. |
| 425 | |
| 426 | case *types.Func: |
| 427 | if obj.Type().(*types.Signature).Recv() != nil { |
| 428 | transitive = true // method |
| 429 | } |
| 430 | |
| 431 | // It's tempting to optimize by skipping |
| 432 | // packages that don't contain a reference to |
| 433 | // the method in the xrefs index, but we still |
| 434 | // need to apply the satisfy check to those |
| 435 | // packages to find assignment statements that |
| 436 | // might expands the scope of the renaming. |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 437 | } |
| 438 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 439 | // Type-check all the packages to inspect. |
| 440 | declURI := span.URIFromPath(pkg.FileSet().File(obj.Pos()).Name()) |
| 441 | pkgs, err := typeCheckReverseDependencies(ctx, snapshot, declURI, transitive) |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 442 | if err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 443 | return nil, err |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 444 | } |
| 445 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 446 | // Apply the renaming to the (initial) object. |
| 447 | declPkgPath := PackagePath(obj.Pkg().Path()) |
| 448 | return renameExported(ctx, snapshot, pkgs, declPkgPath, declObjPath, newName) |
| 449 | } |
| 450 | |
| 451 | // funcOrigin is a go1.18-portable implementation of (*types.Func).Origin. |
| 452 | func funcOrigin(fn *types.Func) *types.Func { |
| 453 | // Method? |
| 454 | if fn.Type().(*types.Signature).Recv() != nil { |
| 455 | return typeparams.OriginMethod(fn) |
| 456 | } |
| 457 | |
| 458 | // Package-level function? |
| 459 | // (Assume the origin has the same position.) |
| 460 | gen := fn.Pkg().Scope().Lookup(fn.Name()) |
| 461 | if gen != nil && gen.Pos() == fn.Pos() { |
| 462 | return gen.(*types.Func) |
| 463 | } |
| 464 | |
| 465 | return fn |
| 466 | } |
| 467 | |
| 468 | // typeCheckReverseDependencies returns the type-checked packages for |
| 469 | // the reverse dependencies of all packages variants containing |
| 470 | // file declURI. The packages are in some topological order. |
| 471 | // |
| 472 | // It includes all variants (even intermediate test variants) for the |
| 473 | // purposes of computing reverse dependencies, but discards ITVs for |
| 474 | // the actual renaming work. |
| 475 | // |
| 476 | // (This neglects obscure edge cases where a _test.go file changes the |
| 477 | // selectors used only in an ITV, but life is short. Also sin must be |
| 478 | // punished.) |
| 479 | func typeCheckReverseDependencies(ctx context.Context, snapshot Snapshot, declURI span.URI, transitive bool) ([]Package, error) { |
| 480 | variants, err := snapshot.MetadataForFile(ctx, declURI) |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 481 | if err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 482 | return nil, err |
| 483 | } |
Alan Donovan | b35949e | 2023-04-20 14:53:41 -0400 | [diff] [blame] | 484 | // variants must include ITVs for the reverse dependency |
| 485 | // computation, but they are filtered out before we typecheck. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 486 | allRdeps := make(map[PackageID]*Metadata) |
| 487 | for _, variant := range variants { |
| 488 | rdeps, err := snapshot.ReverseDependencies(ctx, variant.ID, transitive) |
| 489 | if err != nil { |
| 490 | return nil, err |
| 491 | } |
| 492 | allRdeps[variant.ID] = variant // include self |
| 493 | for id, meta := range rdeps { |
| 494 | allRdeps[id] = meta |
| 495 | } |
| 496 | } |
| 497 | var ids []PackageID |
| 498 | for id, meta := range allRdeps { |
| 499 | if meta.IsIntermediateTestVariant() { |
| 500 | continue |
| 501 | } |
| 502 | ids = append(ids, id) |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 503 | } |
| 504 | |
Robert Findley | 21d2256 | 2023-02-21 12:26:27 -0500 | [diff] [blame] | 505 | // Sort the packages into some topological order of the |
| 506 | // (unfiltered) metadata graph. |
| 507 | SortPostOrder(snapshot, ids) |
| 508 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 509 | // Dependencies must be visited first since they can expand |
| 510 | // the search set. Ideally we would process the (filtered) set |
| 511 | // of packages in the parallel postorder of the snapshot's |
| 512 | // (unfiltered) metadata graph, but this is quite tricky |
| 513 | // without a good graph abstraction. |
| 514 | // |
| 515 | // For now, we visit packages sequentially in order of |
| 516 | // ascending height, like an inverted breadth-first search. |
| 517 | // |
| 518 | // Type checking is by far the dominant cost, so |
| 519 | // overlapping it with renaming may not be worthwhile. |
Robert Findley | 21d2256 | 2023-02-21 12:26:27 -0500 | [diff] [blame] | 520 | return snapshot.TypeCheck(ctx, ids...) |
| 521 | } |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 522 | |
Robert Findley | 21d2256 | 2023-02-21 12:26:27 -0500 | [diff] [blame] | 523 | // SortPostOrder sorts the IDs so that if x depends on y, then y appears before x. |
| 524 | func SortPostOrder(meta MetadataSource, ids []PackageID) { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 525 | postorder := make(map[PackageID]int) |
Robert Findley | 21d2256 | 2023-02-21 12:26:27 -0500 | [diff] [blame] | 526 | order := 0 |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 527 | var visit func(PackageID) |
| 528 | visit = func(id PackageID) { |
| 529 | if _, ok := postorder[id]; !ok { |
| 530 | postorder[id] = -1 // break recursion |
Robert Findley | 21d2256 | 2023-02-21 12:26:27 -0500 | [diff] [blame] | 531 | if m := meta.Metadata(id); m != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 532 | for _, depID := range m.DepsByPkgPath { |
| 533 | visit(depID) |
| 534 | } |
| 535 | } |
Robert Findley | 21d2256 | 2023-02-21 12:26:27 -0500 | [diff] [blame] | 536 | order++ |
| 537 | postorder[id] = order |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 538 | } |
| 539 | } |
| 540 | for _, id := range ids { |
| 541 | visit(id) |
| 542 | } |
Robert Findley | 21d2256 | 2023-02-21 12:26:27 -0500 | [diff] [blame] | 543 | sort.Slice(ids, func(i, j int) bool { |
| 544 | return postorder[ids[i]] < postorder[ids[j]] |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 545 | }) |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 546 | } |
| 547 | |
| 548 | // renameExported renames the object denoted by (pkgPath, objPath) |
| 549 | // within the specified packages, along with any other objects that |
| 550 | // must be renamed as a consequence. The slice of packages must be |
| 551 | // topologically ordered. |
| 552 | func renameExported(ctx context.Context, snapshot Snapshot, pkgs []Package, declPkgPath PackagePath, declObjPath objectpath.Path, newName string) (map[span.URI][]diff.Edit, error) { |
| 553 | |
| 554 | // A target is a name for an object that is stable across types.Packages. |
| 555 | type target struct { |
| 556 | pkg PackagePath |
| 557 | obj objectpath.Path |
| 558 | } |
| 559 | |
| 560 | // Populate the initial set of target objects. |
| 561 | // This set may grow as we discover the consequences of each renaming. |
| 562 | // |
| 563 | // TODO(adonovan): strictly, each cone of reverse dependencies |
| 564 | // of a single variant should have its own target map that |
| 565 | // monotonically expands as we go up the import graph, because |
| 566 | // declarations in test files can alter the set of |
| 567 | // package-level names and change the meaning of field and |
| 568 | // method selectors. So if we parallelize the graph |
| 569 | // visitation (see above), we should also compute the targets |
| 570 | // as a union of dependencies. |
| 571 | // |
| 572 | // Or we could decide that the logic below is fast enough not |
| 573 | // to need parallelism. In small measurements so far the |
| 574 | // type-checking step is about 95% and the renaming only 5%. |
| 575 | targets := map[target]bool{{declPkgPath, declObjPath}: true} |
| 576 | |
| 577 | // Apply the renaming operation to each package. |
| 578 | allEdits := make(map[span.URI][]diff.Edit) |
| 579 | for _, pkg := range pkgs { |
| 580 | |
| 581 | // Resolved target objects within package pkg. |
| 582 | var objects []types.Object |
| 583 | for t := range targets { |
| 584 | p := pkg.DependencyTypes(t.pkg) |
| 585 | if p == nil { |
| 586 | continue // indirect dependency of no consequence |
| 587 | } |
| 588 | obj, err := objectpath.Object(p, t.obj) |
| 589 | if err != nil { |
Alan Donovan | a8cf665 | 2023-06-30 17:56:46 -0400 | [diff] [blame] | 590 | // Possibly a method or an unexported type |
| 591 | // that is not reachable through export data? |
| 592 | // See https://github.com/golang/go/issues/60789. |
| 593 | // |
| 594 | // TODO(adonovan): it seems unsatisfactory that Object |
| 595 | // should return an error for a "valid" path. Perhaps |
| 596 | // we should define such paths as invalid and make |
| 597 | // objectpath.For compute reachability? |
| 598 | // Would that be a compatible change? |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 599 | continue |
| 600 | } |
| 601 | objects = append(objects, obj) |
| 602 | } |
| 603 | if len(objects) == 0 { |
| 604 | continue // no targets of consequence to this package |
| 605 | } |
| 606 | |
| 607 | // Apply the renaming. |
| 608 | editMap, moreObjects, err := renameObjects(ctx, snapshot, newName, pkg, objects...) |
| 609 | if err != nil { |
| 610 | return nil, err |
| 611 | } |
| 612 | |
| 613 | // It is safe to concatenate the edits as they are non-overlapping |
| 614 | // (or identical, in which case they will be de-duped by Rename). |
| 615 | for uri, edits := range editMap { |
| 616 | allEdits[uri] = append(allEdits[uri], edits...) |
| 617 | } |
| 618 | |
| 619 | // Expand the search set? |
| 620 | for obj := range moreObjects { |
| 621 | objpath, err := objectpath.For(obj) |
| 622 | if err != nil { |
| 623 | continue // not exported |
| 624 | } |
| 625 | target := target{PackagePath(obj.Pkg().Path()), objpath} |
| 626 | targets[target] = true |
| 627 | |
| 628 | // TODO(adonovan): methods requires dynamic |
| 629 | // programming of the product targets x |
| 630 | // packages as any package might add a new |
| 631 | // target (from a foward dep) as a |
| 632 | // consequence, and any target might imply a |
| 633 | // new set of rdeps. See golang/go#58461. |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | return allEdits, nil |
| 638 | } |
| 639 | |
| 640 | // renamePackageName renames package declarations, imports, and go.mod files. |
| 641 | func renamePackageName(ctx context.Context, s Snapshot, f FileHandle, newName PackageName) (map[span.URI][]diff.Edit, error) { |
| 642 | // Rename the package decl and all imports. |
| 643 | renamingEdits, err := renamePackage(ctx, s, f, newName) |
| 644 | if err != nil { |
| 645 | return nil, err |
| 646 | } |
| 647 | |
| 648 | // Update the last component of the file's enclosing directory. |
| 649 | oldBase := filepath.Dir(f.URI().Filename()) |
| 650 | newPkgDir := filepath.Join(filepath.Dir(oldBase), string(newName)) |
| 651 | |
| 652 | // Update any affected replace directives in go.mod files. |
| 653 | // TODO(adonovan): extract into its own function. |
| 654 | // |
Alan Donovan | e8f417a | 2023-04-21 14:54:28 -0400 | [diff] [blame] | 655 | // Get all workspace modules. |
| 656 | // TODO(adonovan): should this operate on all go.mod files, |
| 657 | // irrespective of whether they are included in the workspace? |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 658 | modFiles := s.ModFiles() |
| 659 | for _, m := range modFiles { |
Alan Donovan | 36ed0b1 | 2023-03-13 14:20:23 -0400 | [diff] [blame] | 660 | fh, err := s.ReadFile(ctx, m) |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 661 | if err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 662 | return nil, err |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 663 | } |
| 664 | pm, err := s.ParseMod(ctx, fh) |
| 665 | if err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 666 | return nil, err |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 667 | } |
| 668 | |
| 669 | modFileDir := filepath.Dir(pm.URI.Filename()) |
| 670 | affectedReplaces := []*modfile.Replace{} |
| 671 | |
| 672 | // Check if any replace directives need to be fixed |
| 673 | for _, r := range pm.File.Replace { |
| 674 | if !strings.HasPrefix(r.New.Path, "/") && !strings.HasPrefix(r.New.Path, "./") && !strings.HasPrefix(r.New.Path, "../") { |
| 675 | continue |
| 676 | } |
| 677 | |
| 678 | replacedPath := r.New.Path |
| 679 | if strings.HasPrefix(r.New.Path, "./") || strings.HasPrefix(r.New.Path, "../") { |
| 680 | replacedPath = filepath.Join(modFileDir, r.New.Path) |
| 681 | } |
| 682 | |
| 683 | // TODO: Is there a risk of converting a '\' delimited replacement to a '/' delimited replacement? |
| 684 | if !strings.HasPrefix(filepath.ToSlash(replacedPath)+"/", filepath.ToSlash(oldBase)+"/") { |
| 685 | continue // not affected by the package renaming |
| 686 | } |
| 687 | |
| 688 | affectedReplaces = append(affectedReplaces, r) |
| 689 | } |
| 690 | |
| 691 | if len(affectedReplaces) == 0 { |
| 692 | continue |
| 693 | } |
| 694 | copied, err := modfile.Parse("", pm.Mapper.Content, nil) |
| 695 | if err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 696 | return nil, err |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 697 | } |
| 698 | |
| 699 | for _, r := range affectedReplaces { |
| 700 | replacedPath := r.New.Path |
| 701 | if strings.HasPrefix(r.New.Path, "./") || strings.HasPrefix(r.New.Path, "../") { |
| 702 | replacedPath = filepath.Join(modFileDir, r.New.Path) |
| 703 | } |
| 704 | |
| 705 | suffix := strings.TrimPrefix(replacedPath, string(oldBase)) |
| 706 | |
| 707 | newReplacedPath, err := filepath.Rel(modFileDir, newPkgDir+suffix) |
| 708 | if err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 709 | return nil, err |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 710 | } |
| 711 | |
| 712 | newReplacedPath = filepath.ToSlash(newReplacedPath) |
| 713 | |
| 714 | if !strings.HasPrefix(newReplacedPath, "/") && !strings.HasPrefix(newReplacedPath, "../") { |
| 715 | newReplacedPath = "./" + newReplacedPath |
| 716 | } |
| 717 | |
| 718 | if err := copied.AddReplace(r.Old.Path, "", newReplacedPath, ""); err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 719 | return nil, err |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 720 | } |
| 721 | } |
| 722 | |
| 723 | copied.Cleanup() |
| 724 | newContent, err := copied.Format() |
| 725 | if err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 726 | return nil, err |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 727 | } |
| 728 | |
| 729 | // Calculate the edits to be made due to the change. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 730 | edits := s.View().Options().ComputeEdits(string(pm.Mapper.Content), string(newContent)) |
| 731 | renamingEdits[pm.URI] = append(renamingEdits[pm.URI], edits...) |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 732 | } |
| 733 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 734 | return renamingEdits, nil |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 735 | } |
| 736 | |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 737 | // renamePackage computes all workspace edits required to rename the package |
| 738 | // described by the given metadata, to newName, by renaming its package |
| 739 | // directory. |
| 740 | // |
| 741 | // It updates package clauses and import paths for the renamed package as well |
Alan Donovan | 0809ec2 | 2023-05-08 17:47:09 -0400 | [diff] [blame] | 742 | // as any other packages affected by the directory renaming among all packages |
| 743 | // known to the snapshot. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 744 | func renamePackage(ctx context.Context, s Snapshot, f FileHandle, newName PackageName) (map[span.URI][]diff.Edit, error) { |
| 745 | if strings.HasSuffix(string(newName), "_test") { |
| 746 | return nil, fmt.Errorf("cannot rename to _test package") |
| 747 | } |
| 748 | |
| 749 | // We need metadata for the relevant package and module paths. |
| 750 | // These should be the same for all packages containing the file. |
Alan Donovan | b35949e | 2023-04-20 14:53:41 -0400 | [diff] [blame] | 751 | meta, err := NarrowestMetadataForFile(ctx, s, f.URI()) |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 752 | if err != nil { |
| 753 | return nil, err |
| 754 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 755 | |
| 756 | oldPkgPath := meta.PkgPath |
| 757 | if meta.Module == nil { |
| 758 | return nil, fmt.Errorf("cannot rename package: missing module information for package %q", meta.PkgPath) |
| 759 | } |
| 760 | modulePath := PackagePath(meta.Module.Path) |
| 761 | if modulePath == oldPkgPath { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 762 | return nil, 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) |
| 763 | } |
| 764 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 765 | newPathPrefix := path.Join(path.Dir(string(oldPkgPath)), string(newName)) |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 766 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 767 | // We must inspect all packages, not just direct importers, |
| 768 | // because we also rename subpackages, which may be unrelated. |
| 769 | // (If the renamed package imports a subpackage it may require |
| 770 | // edits to both its package and import decls.) |
| 771 | allMetadata, err := s.AllMetadata(ctx) |
| 772 | if err != nil { |
| 773 | return nil, err |
| 774 | } |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 775 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 776 | // Rename package and import declarations in all relevant packages. |
| 777 | edits := make(map[span.URI][]diff.Edit) |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 778 | for _, m := range allMetadata { |
| 779 | // Special case: x_test packages for the renamed package will not have the |
cui fliter | 9161e3a | 2023-07-14 14:55:17 +0800 | [diff] [blame] | 780 | // package path as a dir prefix, but still need their package clauses |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 781 | // renamed. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 782 | if m.PkgPath == oldPkgPath+"_test" { |
| 783 | if err := renamePackageClause(ctx, m, s, newName+"_test", edits); err != nil { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 784 | return nil, err |
| 785 | } |
| 786 | continue |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 787 | } |
| 788 | |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 789 | // Subtle: check this condition before checking for valid module info |
| 790 | // below, because we should not fail this operation if unrelated packages |
| 791 | // lack module info. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 792 | if !strings.HasPrefix(string(m.PkgPath)+"/", string(oldPkgPath)+"/") { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 793 | continue // not affected by the package renaming |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 794 | } |
| 795 | |
Alan Donovan | 85bf7a8 | 2022-11-18 12:03:11 -0500 | [diff] [blame] | 796 | if m.Module == nil { |
Alan Donovan | 44395ff | 2022-12-21 12:13:36 -0500 | [diff] [blame] | 797 | // This check will always fail under Bazel. |
Alan Donovan | 85bf7a8 | 2022-11-18 12:03:11 -0500 | [diff] [blame] | 798 | return nil, fmt.Errorf("cannot rename package: missing module information for package %q", m.PkgPath) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 799 | } |
| 800 | |
Alan Donovan | 85bf7a8 | 2022-11-18 12:03:11 -0500 | [diff] [blame] | 801 | if modulePath != PackagePath(m.Module.Path) { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 802 | continue // don't edit imports if nested package and renaming package have different module paths |
| 803 | } |
| 804 | |
| 805 | // Renaming a package consists of changing its import path and package name. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 806 | suffix := strings.TrimPrefix(string(m.PkgPath), string(oldPkgPath)) |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 807 | newPath := newPathPrefix + suffix |
| 808 | |
Alan Donovan | 85bf7a8 | 2022-11-18 12:03:11 -0500 | [diff] [blame] | 809 | pkgName := m.Name |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 810 | if m.PkgPath == oldPkgPath { |
| 811 | pkgName = PackageName(newName) |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 812 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 813 | if err := renamePackageClause(ctx, m, s, newName, edits); err != nil { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 814 | return nil, err |
| 815 | } |
| 816 | } |
| 817 | |
Alan Donovan | 3c3713e | 2022-11-10 13:02:38 -0500 | [diff] [blame] | 818 | imp := ImportPath(newPath) // TODO(adonovan): what if newPath has vendor/ prefix? |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 819 | if err := renameImports(ctx, s, m, imp, pkgName, edits); err != nil { |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 820 | return nil, err |
| 821 | } |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 822 | } |
| 823 | |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 824 | return edits, nil |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 825 | } |
| 826 | |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 827 | // renamePackageClause computes edits renaming the package clause of files in |
| 828 | // the package described by the given metadata, to newName. |
| 829 | // |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 830 | // Edits are written into the edits map. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 831 | func renamePackageClause(ctx context.Context, m *Metadata, snapshot Snapshot, newName PackageName, edits map[span.URI][]diff.Edit) error { |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 832 | // Rename internal references to the package in the renaming package. |
Alan Donovan | d7dfffd | 2022-12-08 00:37:50 -0500 | [diff] [blame] | 833 | for _, uri := range m.CompiledGoFiles { |
Alan Donovan | 36ed0b1 | 2023-03-13 14:20:23 -0400 | [diff] [blame] | 834 | fh, err := snapshot.ReadFile(ctx, uri) |
Alan Donovan | d7dfffd | 2022-12-08 00:37:50 -0500 | [diff] [blame] | 835 | if err != nil { |
| 836 | return err |
| 837 | } |
| 838 | f, err := snapshot.ParseGo(ctx, fh, ParseHeader) |
| 839 | if err != nil { |
| 840 | return err |
| 841 | } |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 842 | if f.File.Name == nil { |
Alan Donovan | d7dfffd | 2022-12-08 00:37:50 -0500 | [diff] [blame] | 843 | continue // no package declaration |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 844 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 845 | |
| 846 | edit, err := posEdit(f.Tok, f.File.Name.Pos(), f.File.Name.End(), string(newName)) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 847 | if err != nil { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 848 | return err |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 849 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 850 | edits[f.URI] = append(edits[f.URI], edit) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 851 | } |
| 852 | |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 853 | return nil |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 854 | } |
| 855 | |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 856 | // renameImports computes the set of edits to imports resulting from renaming |
| 857 | // the package described by the given metadata, to a package with import path |
| 858 | // newPath and name newName. |
| 859 | // |
| 860 | // Edits are written into the edits map. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 861 | func renameImports(ctx context.Context, snapshot Snapshot, m *Metadata, newPath ImportPath, newName PackageName, allEdits map[span.URI][]diff.Edit) error { |
Alan Donovan | 44395ff | 2022-12-21 12:13:36 -0500 | [diff] [blame] | 862 | rdeps, err := snapshot.ReverseDependencies(ctx, m.ID, false) // find direct importers |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 863 | if err != nil { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 864 | return err |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 865 | } |
| 866 | |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 867 | // Pass 1: rename import paths in import declarations. |
| 868 | needsTypeCheck := make(map[PackageID][]span.URI) |
| 869 | for _, rdep := range rdeps { |
| 870 | if rdep.IsIntermediateTestVariant() { |
| 871 | continue // for renaming, these variants are redundant |
| 872 | } |
| 873 | |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 874 | for _, uri := range rdep.CompiledGoFiles { |
Alan Donovan | 36ed0b1 | 2023-03-13 14:20:23 -0400 | [diff] [blame] | 875 | fh, err := snapshot.ReadFile(ctx, uri) |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 876 | if err != nil { |
| 877 | return err |
| 878 | } |
| 879 | f, err := snapshot.ParseGo(ctx, fh, ParseHeader) |
| 880 | if err != nil { |
| 881 | return err |
| 882 | } |
| 883 | if f.File.Name == nil { |
| 884 | continue // no package declaration |
| 885 | } |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 886 | for _, imp := range f.File.Imports { |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 887 | if rdep.DepsByImpPath[UnquoteImportPath(imp)] != m.ID { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 888 | continue // not the import we're looking for |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 889 | } |
| 890 | |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 891 | // If the import does not explicitly specify |
| 892 | // a local name, then we need to invoke the |
| 893 | // type checker to locate references to update. |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 894 | // |
| 895 | // TODO(adonovan): is this actually true? |
| 896 | // Renaming an import with a local name can still |
| 897 | // cause conflicts: shadowing of built-ins, or of |
| 898 | // package-level decls in the same or another file. |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 899 | if imp.Name == nil { |
| 900 | needsTypeCheck[rdep.ID] = append(needsTypeCheck[rdep.ID], uri) |
| 901 | } |
| 902 | |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 903 | // Create text edit for the import path (string literal). |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 904 | edit, err := posEdit(f.Tok, imp.Path.Pos(), imp.Path.End(), strconv.Quote(string(newPath))) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 905 | if err != nil { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 906 | return err |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 907 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 908 | allEdits[uri] = append(allEdits[uri], edit) |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 909 | } |
| 910 | } |
| 911 | } |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 912 | |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 913 | // If the imported package's name hasn't changed, |
| 914 | // we don't need to rename references within each file. |
| 915 | if newName == m.Name { |
| 916 | return nil |
| 917 | } |
| 918 | |
| 919 | // Pass 2: rename local name (types.PkgName) of imported |
| 920 | // package throughout one or more files of the package. |
| 921 | ids := make([]PackageID, 0, len(needsTypeCheck)) |
| 922 | for id := range needsTypeCheck { |
| 923 | ids = append(ids, id) |
| 924 | } |
Robert Findley | 21d2256 | 2023-02-21 12:26:27 -0500 | [diff] [blame] | 925 | pkgs, err := snapshot.TypeCheck(ctx, ids...) |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 926 | if err != nil { |
| 927 | return err |
| 928 | } |
| 929 | for i, id := range ids { |
| 930 | pkg := pkgs[i] |
| 931 | for _, uri := range needsTypeCheck[id] { |
| 932 | f, err := pkg.File(uri) |
| 933 | if err != nil { |
| 934 | return err |
| 935 | } |
| 936 | for _, imp := range f.File.Imports { |
| 937 | if imp.Name != nil { |
| 938 | continue // has explicit local name |
| 939 | } |
| 940 | if rdeps[id].DepsByImpPath[UnquoteImportPath(imp)] != m.ID { |
| 941 | continue // not the import we're looking for |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 942 | } |
| 943 | |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 944 | pkgname := pkg.GetTypesInfo().Implicits[imp].(*types.PkgName) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 945 | |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 946 | pkgScope := pkg.GetTypes().Scope() |
| 947 | fileScope := pkg.GetTypesInfo().Scopes[f.File] |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 948 | |
Alan Donovan | 3c3713e | 2022-11-10 13:02:38 -0500 | [diff] [blame] | 949 | localName := string(newName) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 950 | try := 0 |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 951 | |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 952 | // Keep trying with fresh names until one succeeds. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 953 | // |
| 954 | // TODO(adonovan): fix: this loop is not sufficient to choose a name |
| 955 | // that is guaranteed to be conflict-free; renameObj may still fail. |
| 956 | // So the retry loop should be around renameObj, and we shouldn't |
| 957 | // bother with scopes here. |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 958 | for fileScope.Lookup(localName) != nil || pkgScope.Lookup(localName) != nil { |
| 959 | try++ |
| 960 | localName = fmt.Sprintf("%s%d", newName, try) |
| 961 | } |
Alan Donovan | e0659d1 | 2023-01-26 17:55:24 -0500 | [diff] [blame] | 962 | |
| 963 | // renameObj detects various conflicts, including: |
| 964 | // - new name conflicts with a package-level decl in this file; |
| 965 | // - new name hides a package-level decl in another file that |
| 966 | // is actually referenced in this file; |
| 967 | // - new name hides a built-in that is actually referenced |
| 968 | // in this file; |
| 969 | // - a reference in this file to the old package name would |
| 970 | // become shadowed by an intervening declaration that |
| 971 | // uses the new name. |
| 972 | // It returns the edits if no conflict was detected. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 973 | editMap, _, err := renameObjects(ctx, snapshot, localName, pkg, pkgname) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 974 | if err != nil { |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 975 | return err |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 976 | } |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 977 | |
Alan Donovan | b2b9dc3 | 2022-12-12 11:31:59 -0500 | [diff] [blame] | 978 | // If the chosen local package name matches the package's |
| 979 | // new name, delete the change that would have inserted |
| 980 | // an explicit local name, which is always the lexically |
| 981 | // first change. |
Alan Donovan | 3c3713e | 2022-11-10 13:02:38 -0500 | [diff] [blame] | 982 | if localName == string(newName) { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 983 | edits, ok := editMap[uri] |
| 984 | if !ok { |
| 985 | return fmt.Errorf("internal error: no changes for %s", uri) |
| 986 | } |
| 987 | diff.SortEdits(edits) |
| 988 | editMap[uri] = edits[1:] |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 989 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 990 | for uri, edits := range editMap { |
| 991 | allEdits[uri] = append(allEdits[uri], edits...) |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 992 | } |
| 993 | } |
| 994 | } |
| 995 | } |
Robert Findley | 6128030 | 2022-10-17 16:35:50 -0400 | [diff] [blame] | 996 | return nil |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 997 | } |
| 998 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 999 | // renameObjects computes the edits to the type-checked syntax package pkg |
| 1000 | // required to rename a set of target objects to newName. |
| 1001 | // |
| 1002 | // It also returns the set of objects that were found (due to |
| 1003 | // corresponding methods and embedded fields) to require renaming as a |
| 1004 | // consequence of the requested renamings. |
| 1005 | // |
| 1006 | // It returns an error if the renaming would cause a conflict. |
| 1007 | func renameObjects(ctx context.Context, snapshot Snapshot, newName string, pkg Package, targets ...types.Object) (map[span.URI][]diff.Edit, map[types.Object]bool, error) { |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1008 | r := renamer{ |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1009 | pkg: pkg, |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1010 | objsToUpdate: make(map[types.Object]bool), |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1011 | from: targets[0].Name(), |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1012 | to: newName, |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1013 | } |
| 1014 | |
| 1015 | // A renaming initiated at an interface method indicates the |
| 1016 | // intention to rename abstract and concrete methods as needed |
| 1017 | // to preserve assignability. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1018 | // TODO(adonovan): pull this into the caller. |
| 1019 | for _, obj := range targets { |
| 1020 | if obj, ok := obj.(*types.Func); ok { |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1021 | recv := obj.Type().(*types.Signature).Recv() |
Alan Donovan | 9682b0d | 2023-01-18 10:02:11 -0500 | [diff] [blame] | 1022 | if recv != nil && types.IsInterface(recv.Type().Underlying()) { |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1023 | r.changeMethods = true |
| 1024 | break |
| 1025 | } |
| 1026 | } |
| 1027 | } |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1028 | |
| 1029 | // Check that the renaming of the identifier is ok. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1030 | for _, obj := range targets { |
| 1031 | r.check(obj) |
Alan Donovan | 80afb09 | 2023-02-07 15:42:30 -0500 | [diff] [blame] | 1032 | if len(r.conflicts) > 0 { |
| 1033 | // Stop at first error. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1034 | return nil, nil, fmt.Errorf("%s", strings.Join(r.conflicts, "\n")) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1035 | } |
| 1036 | } |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1037 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1038 | editMap, err := r.update() |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1039 | if err != nil { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1040 | return nil, nil, err |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1041 | } |
| 1042 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1043 | // Remove initial targets so that only 'consequences' remain. |
| 1044 | for _, obj := range targets { |
| 1045 | delete(r.objsToUpdate, obj) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1046 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1047 | return editMap, r.objsToUpdate, nil |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1048 | } |
| 1049 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1050 | // Rename all references to the target objects. |
Alan Donovan | d96b238 | 2022-09-30 21:58:21 -0400 | [diff] [blame] | 1051 | func (r *renamer) update() (map[span.URI][]diff.Edit, error) { |
| 1052 | result := make(map[span.URI][]diff.Edit) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1053 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1054 | // shouldUpdate reports whether obj is one of (or an |
| 1055 | // instantiation of one of) the target objects. |
| 1056 | shouldUpdate := func(obj types.Object) bool { |
Robert Findley | 1517d1a | 2023-08-11 19:35:44 -0400 | [diff] [blame] | 1057 | return containsOrigin(r.objsToUpdate, obj) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1058 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1059 | |
| 1060 | // Find all identifiers in the package that define or use a |
cui fliter | 2ffc4dc | 2023-07-25 17:11:18 +0800 | [diff] [blame] | 1061 | // renamed object. We iterate over info as it is more efficient |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1062 | // than calling ast.Inspect for each of r.pkg.CompiledGoFiles(). |
| 1063 | type item struct { |
| 1064 | node ast.Node // Ident, ImportSpec (obj=PkgName), or CaseClause (obj=Var) |
| 1065 | obj types.Object |
| 1066 | isDef bool |
| 1067 | } |
| 1068 | var items []item |
| 1069 | info := r.pkg.GetTypesInfo() |
| 1070 | for id, obj := range info.Uses { |
| 1071 | if shouldUpdate(obj) { |
| 1072 | items = append(items, item{id, obj, false}) |
| 1073 | } |
| 1074 | } |
| 1075 | for id, obj := range info.Defs { |
| 1076 | if shouldUpdate(obj) { |
| 1077 | items = append(items, item{id, obj, true}) |
| 1078 | } |
| 1079 | } |
| 1080 | for node, obj := range info.Implicits { |
| 1081 | if shouldUpdate(obj) { |
| 1082 | switch node.(type) { |
| 1083 | case *ast.ImportSpec, *ast.CaseClause: |
| 1084 | items = append(items, item{node, obj, true}) |
| 1085 | } |
| 1086 | } |
| 1087 | } |
| 1088 | sort.Slice(items, func(i, j int) bool { |
| 1089 | return items[i].node.Pos() < items[j].node.Pos() |
| 1090 | }) |
| 1091 | |
| 1092 | // Update each identifier. |
| 1093 | for _, item := range items { |
| 1094 | pgf, ok := enclosingFile(r.pkg, item.node.Pos()) |
| 1095 | if !ok { |
| 1096 | bug.Reportf("edit does not belong to syntax of package %q", r.pkg) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1097 | continue |
| 1098 | } |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1099 | |
| 1100 | // Renaming a types.PkgName may result in the addition or removal of an identifier, |
| 1101 | // so we deal with this separately. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1102 | if pkgName, ok := item.obj.(*types.PkgName); ok && item.isDef { |
| 1103 | edit, err := r.updatePkgName(pgf, pkgName) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1104 | if err != nil { |
| 1105 | return nil, err |
| 1106 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1107 | result[pgf.URI] = append(result[pgf.URI], edit) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1108 | continue |
| 1109 | } |
| 1110 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1111 | // Workaround the unfortunate lack of a Var object |
| 1112 | // for x in "switch x := expr.(type) {}" by adjusting |
| 1113 | // the case clause to the switch ident. |
| 1114 | // This may result in duplicate edits, but we de-dup later. |
| 1115 | if _, ok := item.node.(*ast.CaseClause); ok { |
| 1116 | path, _ := astutil.PathEnclosingInterval(pgf.File, item.obj.Pos(), item.obj.Pos()) |
| 1117 | item.node = path[0].(*ast.Ident) |
| 1118 | } |
| 1119 | |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1120 | // Replace the identifier with r.to. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1121 | edit, err := posEdit(pgf.Tok, item.node.Pos(), item.node.End(), r.to) |
| 1122 | if err != nil { |
| 1123 | return nil, err |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1124 | } |
| 1125 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1126 | result[pgf.URI] = append(result[pgf.URI], edit) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1127 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1128 | if !item.isDef { // uses do not have doc comments to update. |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1129 | continue |
| 1130 | } |
| 1131 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1132 | doc := docComment(pgf, item.node.(*ast.Ident)) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1133 | if doc == nil { |
| 1134 | continue |
| 1135 | } |
| 1136 | |
| 1137 | // Perform the rename in doc comments declared in the original package. |
| 1138 | // go/parser strips out \r\n returns from the comment text, so go |
| 1139 | // line-by-line through the comment text to get the correct positions. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1140 | docRegexp := regexp.MustCompile(`\b` + r.from + `\b`) // valid identifier => valid regexp |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1141 | for _, comment := range doc.List { |
| 1142 | if isDirective(comment.Text) { |
| 1143 | continue |
| 1144 | } |
Alan Donovan | d96b238 | 2022-09-30 21:58:21 -0400 | [diff] [blame] | 1145 | // TODO(adonovan): why are we looping over lines? |
| 1146 | // Just run the loop body once over the entire multiline comment. |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1147 | lines := strings.Split(comment.Text, "\n") |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1148 | tokFile := pgf.Tok |
Peter Weinberger | 0a3e5f0 | 2023-03-30 10:54:29 -0400 | [diff] [blame] | 1149 | commentLine := safetoken.Line(tokFile, comment.Pos()) |
Alan Donovan | d96b238 | 2022-09-30 21:58:21 -0400 | [diff] [blame] | 1150 | uri := span.URIFromPath(tokFile.Name()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1151 | for i, line := range lines { |
| 1152 | lineStart := comment.Pos() |
| 1153 | if i > 0 { |
| 1154 | lineStart = tokFile.LineStart(commentLine + i) |
| 1155 | } |
| 1156 | for _, locs := range docRegexp.FindAllIndex([]byte(line), -1) { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1157 | edit, err := posEdit(tokFile, lineStart+token.Pos(locs[0]), lineStart+token.Pos(locs[1]), r.to) |
| 1158 | if err != nil { |
| 1159 | return nil, err // can't happen |
| 1160 | } |
| 1161 | result[uri] = append(result[uri], edit) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1162 | } |
| 1163 | } |
| 1164 | } |
| 1165 | } |
| 1166 | |
| 1167 | return result, nil |
| 1168 | } |
| 1169 | |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1170 | // docComment returns the doc for an identifier within the specified file. |
| 1171 | func docComment(pgf *ParsedGoFile, id *ast.Ident) *ast.CommentGroup { |
| 1172 | nodes, _ := astutil.PathEnclosingInterval(pgf.File, id.Pos(), id.End()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1173 | for _, node := range nodes { |
| 1174 | switch decl := node.(type) { |
| 1175 | case *ast.FuncDecl: |
| 1176 | return decl.Doc |
| 1177 | case *ast.Field: |
| 1178 | return decl.Doc |
| 1179 | case *ast.GenDecl: |
| 1180 | return decl.Doc |
| 1181 | // For {Type,Value}Spec, if the doc on the spec is absent, |
| 1182 | // search for the enclosing GenDecl |
| 1183 | case *ast.TypeSpec: |
| 1184 | if decl.Doc != nil { |
| 1185 | return decl.Doc |
| 1186 | } |
| 1187 | case *ast.ValueSpec: |
| 1188 | if decl.Doc != nil { |
| 1189 | return decl.Doc |
| 1190 | } |
| 1191 | case *ast.Ident: |
| 1192 | case *ast.AssignStmt: |
| 1193 | // *ast.AssignStmt doesn't have an associated comment group. |
| 1194 | // So, we try to find a comment just before the identifier. |
| 1195 | |
| 1196 | // Try to find a comment group only for short variable declarations (:=). |
| 1197 | if decl.Tok != token.DEFINE { |
| 1198 | return nil |
| 1199 | } |
| 1200 | |
Peter Weinberger | 0a3e5f0 | 2023-03-30 10:54:29 -0400 | [diff] [blame] | 1201 | identLine := safetoken.Line(pgf.Tok, id.Pos()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1202 | for _, comment := range nodes[len(nodes)-1].(*ast.File).Comments { |
| 1203 | if comment.Pos() > id.Pos() { |
| 1204 | // Comment is after the identifier. |
| 1205 | continue |
| 1206 | } |
| 1207 | |
Peter Weinberger | 0a3e5f0 | 2023-03-30 10:54:29 -0400 | [diff] [blame] | 1208 | lastCommentLine := safetoken.Line(pgf.Tok, comment.End()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1209 | if lastCommentLine+1 == identLine { |
| 1210 | return comment |
| 1211 | } |
| 1212 | } |
| 1213 | default: |
| 1214 | return nil |
| 1215 | } |
| 1216 | } |
| 1217 | return nil |
| 1218 | } |
| 1219 | |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 1220 | // updatePkgName returns the updates to rename a pkgName in the import spec by |
| 1221 | // only modifying the package name portion of the import declaration. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1222 | func (r *renamer) updatePkgName(pgf *ParsedGoFile, pkgName *types.PkgName) (diff.Edit, error) { |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1223 | // Modify ImportSpec syntax to add or remove the Name as needed. |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1224 | path, _ := astutil.PathEnclosingInterval(pgf.File, pkgName.Pos(), pkgName.Pos()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1225 | if len(path) < 2 { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1226 | return diff.Edit{}, fmt.Errorf("no path enclosing interval for %s", pkgName.Name()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1227 | } |
| 1228 | spec, ok := path[1].(*ast.ImportSpec) |
| 1229 | if !ok { |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1230 | return diff.Edit{}, fmt.Errorf("failed to update PkgName for %s", pkgName.Name()) |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1231 | } |
| 1232 | |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 1233 | newText := "" |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1234 | if pkgName.Imported().Name() != r.to { |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 1235 | newText = r.to + " " |
Robert Findley | b15dac2 | 2022-08-30 14:40:12 -0400 | [diff] [blame] | 1236 | } |
| 1237 | |
Dylan Le | 40dabfa | 2022-08-03 14:45:51 -0400 | [diff] [blame] | 1238 | // Replace the portion (possibly empty) of the spec before the path: |
| 1239 | // local "path" or "path" |
| 1240 | // -> <- -><- |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1241 | return posEdit(pgf.Tok, spec.Pos(), spec.Path.Pos(), newText) |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 1242 | } |
| 1243 | |
| 1244 | // parsePackageNameDecl is a convenience function that parses and |
| 1245 | // returns the package name declaration of file fh, and reports |
| 1246 | // whether the position ppos lies within it. |
| 1247 | // |
Alan Donovan | 537c4aa | 2023-03-13 17:42:29 -0400 | [diff] [blame] | 1248 | // Note: also used by references. |
Alan Donovan | 5ed33df | 2023-01-26 22:08:04 -0500 | [diff] [blame] | 1249 | func parsePackageNameDecl(ctx context.Context, snapshot Snapshot, fh FileHandle, ppos protocol.Position) (*ParsedGoFile, bool, error) { |
| 1250 | pgf, err := snapshot.ParseGo(ctx, fh, ParseHeader) |
| 1251 | if err != nil { |
| 1252 | return nil, false, err |
| 1253 | } |
| 1254 | // Careful: because we used ParseHeader, |
| 1255 | // pgf.Pos(ppos) may be beyond EOF => (0, err). |
| 1256 | pos, _ := pgf.PositionPos(ppos) |
| 1257 | return pgf, pgf.File.Name.Pos() <= pos && pos <= pgf.File.Name.End(), nil |
| 1258 | } |
Alan Donovan | 64f9d62 | 2023-01-30 12:32:11 -0500 | [diff] [blame] | 1259 | |
| 1260 | // enclosingFile returns the CompiledGoFile of pkg that contains the specified position. |
| 1261 | func enclosingFile(pkg Package, pos token.Pos) (*ParsedGoFile, bool) { |
| 1262 | for _, pgf := range pkg.CompiledGoFiles() { |
| 1263 | if pgf.File.Pos() <= pos && pos <= pgf.File.End() { |
| 1264 | return pgf, true |
| 1265 | } |
| 1266 | } |
| 1267 | return nil, false |
| 1268 | } |
| 1269 | |
| 1270 | // posEdit returns an edit to replace the (start, end) range of tf with 'new'. |
| 1271 | func posEdit(tf *token.File, start, end token.Pos, new string) (diff.Edit, error) { |
| 1272 | startOffset, endOffset, err := safetoken.Offsets(tf, start, end) |
| 1273 | if err != nil { |
| 1274 | return diff.Edit{}, err |
| 1275 | } |
| 1276 | return diff.Edit{Start: startOffset, End: endOffset, New: new}, nil |
| 1277 | } |