Debian Codegraph @

refactor/rename/rename.go

raw symbols SCIP
1 // Copyright 2014 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 rename contains the obsolete implementation of the deleted
6 // golang.org/x/tools/cmd/gorename. This logic has not worked properly
7 // since the advent of Go modules, and should be deleted too.
8 //
9 // Use gopls instead, either via the Rename LSP method or the "gopls
10 // rename" subcommand.
11 package rename
12
13 import (
14 "bytes"
15 "errors"
16 "fmt"
17 "go/ast"
18 "go/build"
19 "go/format"
20 "go/parser"
21 "go/token"
22 "go/types"
23 "io"
24 "log"
25 "os"
26 "os/exec"
27 "path"
28 "regexp"
29 "sort"
30 "strconv"
31 "strings"
32
33 "golang.org/x/tools/go/loader"
34 "golang.org/x/tools/go/types/typeutil"
35 "golang.org/x/tools/refactor/importgraph"
36 "golang.org/x/tools/refactor/satisfy"
37 )
38
39 const Usage = `gorename: precise type-safe renaming of identifiers in Go source code.
40
41 Usage:
42
43 gorename (-from <spec> | -offset <file>:#<byte-offset>) -to <name> [-force]
44
45 You must specify the object (named entity) to rename using the -offset
46 or -from flag. Exactly one must be specified.
47
48 Flags:
49
50 -offset specifies the filename and byte offset of an identifier to rename.
51 This form is intended for use by text editors.
52
53 -from specifies the object to rename using a query notation;
54 This form is intended for interactive use at the command line.
55 A legal -from query has one of the following forms:
56
57 "encoding/json".Decoder.Decode method of package-level named type
58 (*"encoding/json".Decoder).Decode ditto, alternative syntax
59 "encoding/json".Decoder.buf field of package-level named struct type
60 "encoding/json".HTMLEscape package member (const, func, var, type)
61 "encoding/json".Decoder.Decode::x local object x within a method
62 "encoding/json".HTMLEscape::x local object x within a function
63 "encoding/json"::x object x anywhere within a package
64 json.go::x object x within file json.go
65
66 Double-quotes must be escaped when writing a shell command.
67 Quotes may be omitted for single-segment import paths such as "fmt".
68
69 For methods, the parens and '*' on the receiver type are both
70 optional.
71
72 It is an error if one of the ::x queries matches multiple
73 objects.
74
75 -to the new name.
76
77 -force causes the renaming to proceed even if conflicts were reported.
78 The resulting program may be ill-formed, or experience a change
79 in behaviour.
80
81 WARNING: this flag may even cause the renaming tool to crash.
82 (In due course this bug will be fixed by moving certain
83 analyses into the type-checker.)
84
85 -d display diffs instead of rewriting files
86
87 -v enables verbose logging.
88
89 gorename automatically computes the set of packages that might be
90 affected. For a local renaming, this is just the package specified by
91 -from or -offset, but for a potentially exported name, gorename scans
92 the workspace ($GOROOT and $GOPATH).
93
94 gorename rejects renamings of concrete methods that would change the
95 assignability relation between types and interfaces. If the interface
96 change was intentional, initiate the renaming at the interface method.
97
98 gorename rejects any renaming that would create a conflict at the point
99 of declaration, or a reference conflict (ambiguity or shadowing), or
100 anything else that could cause the resulting program not to compile.
101
102
103 Examples:
104
105 $ gorename -offset file.go:#123 -to foo
106
107 Rename the object whose identifier is at byte offset 123 within file file.go.
108
109 $ gorename -from '"bytes".Buffer.Len' -to Size
110
111 Rename the "Len" method of the *bytes.Buffer type to "Size".
112 `
113
114 // ---- TODO ----
115
116 // Correctness:
117 // - handle dot imports correctly
118 // - document limitations (reflection, 'implements' algorithm).
119 // - sketch a proof of exhaustiveness.
120
121 // Features:
122 // - support running on packages specified as *.go files on the command line
123 // - support running on programs containing errors (loader.Config.AllowErrors)
124 // - allow users to specify a scope other than "global" (to avoid being
125 // stuck by neglected packages in $GOPATH that don't build).
126 // - support renaming the package clause (no object)
127 // - support renaming an import path (no ident or object)
128 // (requires filesystem + SCM updates).
129 // - detect and reject edits to autogenerated files (cgo, protobufs)
130 // and optionally $GOROOT packages.
131 // - report all conflicts, or at least all qualitatively distinct ones.
132 // Sometimes we stop to avoid redundancy, but
133 // it may give a disproportionate sense of safety in -force mode.
134 // - support renaming all instances of a pattern, e.g.
135 // all receiver vars of a given type,
136 // all local variables of a given type,
137 // all PkgNames for a given package.
138 // - emit JSON output for other editors and tools.
139
140 var (
141 // Force enables patching of the source files even if conflicts were reported.
142 // The resulting program may be ill-formed.
143 // It may even cause gorename to crash. TODO(adonovan): fix that.
144 Force bool
145
146 // Diff causes the tool to display diffs instead of rewriting files.
147 Diff bool
148
149 // DiffCmd specifies the diff command used by the -d feature.
150 // (The command must accept a -u flag and two filename arguments.)
151 DiffCmd = "diff"
152
153 // ConflictError is returned by Main when it aborts the renaming due to conflicts.
154 // (It is distinguished because the interesting errors are the conflicts themselves.)
155 ConflictError = errors.New("renaming aborted due to conflicts")
156
157 // Verbose enables extra logging.
158 Verbose bool
159 )
160
161 var stdout io.Writer = os.Stdout
162
163 type renamer struct {
164 iprog *loader.Program
165 objsToUpdate map[types.Object]bool
166 hadConflicts bool
167 from, to string
168 satisfyConstraints map[satisfy.Constraint]bool
169 packages map[*types.Package]*loader.PackageInfo // subset of iprog.AllPackages to inspect
170 msets typeutil.MethodSetCache
171 changeMethods bool
172 }
173
174 var reportError = func(posn token.Position, message string) {
175 fmt.Fprintf(os.Stderr, "%s: %s\n", posn, message)
176 }
177
178 // importName renames imports of fromPath within the package specified by info.
179 // If fromName is not empty, importName renames only imports as fromName.
180 // If the renaming would lead to a conflict, the file is left unchanged.
181 func importName(iprog *loader.Program, info *loader.PackageInfo, fromPath, fromName, to string) error {
182 if fromName == to {
183 return nil // no-op (e.g. rename x/foo to y/foo)
184 }
185 for _, f := range info.Files {
186 var from types.Object
187 for _, imp := range f.Imports {
188 importPath, _ := strconv.Unquote(imp.Path.Value)
189 importName := path.Base(importPath)
190 if imp.Name != nil {
191 importName = imp.Name.Name
192 }
193 if importPath == fromPath && (fromName == "" || importName == fromName) {
194 from = info.Implicits[imp]
195 break
196 }
197 }
198 if from == nil {
199 continue
200 }
201 r := renamer{
202 iprog: iprog,
203 objsToUpdate: make(map[types.Object]bool),
204 to: to,
205 packages: map[*types.Package]*loader.PackageInfo{info.Pkg: info},
206 }
207 r.check(from)
208 if r.hadConflicts {
209 reportError(iprog.Fset.Position(f.Imports[0].Pos()),
210 "skipping update of this file")
211 continue // ignore errors; leave the existing name
212 }
213 if err := r.update(); err != nil {
214 return err
215 }
216 }
217 return nil
218 }
219
220 func Main(ctxt *build.Context, offsetFlag, fromFlag, to string) error {
221 // -- Parse the -from or -offset specifier ----------------------------
222
223 if (offsetFlag == "") == (fromFlag == "") {
224 return fmt.Errorf("exactly one of the -from and -offset flags must be specified")
225 }
226
227 if !isValidIdentifier(to) {
228 return fmt.Errorf("-to %q: not a valid identifier", to)
229 }
230
231 if Diff {
232 defer func(saved func(string, []byte) error) { writeFile = saved }(writeFile)
233 writeFile = diff
234 }
235
236 var spec *spec
237 var err error
238 if fromFlag != "" {
239 spec, err = parseFromFlag(ctxt, fromFlag)
240 } else {
241 spec, err = parseOffsetFlag(ctxt, offsetFlag)
242 }
243 if err != nil {
244 return err
245 }
246
247 if spec.fromName == to {
248 return fmt.Errorf("the old and new names are the same: %s", to)
249 }
250
251 // -- Load the program consisting of the initial package -------------
252
253 iprog, err := loadProgram(ctxt, map[string]bool{spec.pkg: true})
254 if err != nil {
255 return err
256 }
257
258 fromObjects, err := findFromObjects(iprog, spec)
259 if err != nil {
260 return err
261 }
262
263 // -- Load a larger program, for global renamings ---------------------
264
265 if requiresGlobalRename(fromObjects, to) {
266 // For a local refactoring, we needn't load more
267 // packages, but if the renaming affects the package's
268 // API, we must load all packages that depend on the
269 // package defining the object, plus their tests.
270
271 if Verbose {
272 log.Print("Potentially global renaming; scanning workspace...")
273 }
274
275 // Scan the workspace and build the import graph.
276 _, rev, errors := importgraph.Build(ctxt)
277 if len(errors) > 0 {
278 // With a large GOPATH tree, errors are inevitable.
279 // Report them but proceed.
280 fmt.Fprintf(os.Stderr, "While scanning Go workspace:\n")
281 for path, err := range errors {
282 fmt.Fprintf(os.Stderr, "Package %q: %s.\n", path, err)
283 }
284 }
285
286 // Enumerate the set of potentially affected packages.
287 affectedPackages := make(map[string]bool)
288 for _, obj := range fromObjects {
289 // External test packages are never imported,
290 // so they will never appear in the graph.
291 for path := range rev.Search(obj.Pkg().Path()) {
292 affectedPackages[path] = true
293 }
294 }
295
296 // TODO(adonovan): allow the user to specify the scope,
297 // or -ignore patterns? Computing the scope when we
298 // don't (yet) support inputs containing errors can make
299 // the tool rather brittle.
300
301 // Re-load the larger program.
302 iprog, err = loadProgram(ctxt, affectedPackages)
303 if err != nil {
304 return err
305 }
306
307 fromObjects, err = findFromObjects(iprog, spec)
308 if err != nil {
309 return err
310 }
311 }
312
313 // -- Do the renaming -------------------------------------------------
314
315 r := renamer{
316 iprog: iprog,
317 objsToUpdate: make(map[types.Object]bool),
318 from: spec.fromName,
319 to: to,
320 packages: make(map[*types.Package]*loader.PackageInfo),
321 }
322
323 // A renaming initiated at an interface method indicates the
324 // intention to rename abstract and concrete methods as needed
325 // to preserve assignability.
326 for _, obj := range fromObjects {
327 if obj, ok := obj.(*types.Func); ok {
328 recv := obj.Signature().Recv()
329 if recv != nil && types.IsInterface(recv.Type()) {
330 r.changeMethods = true
331 break
332 }
333 }
334 }
335
336 // Only the initially imported packages (iprog.Imported) and
337 // their external tests (iprog.Created) should be inspected or
338 // modified, as only they have type-checked function bodies.
339 // The rest are just dependencies, needed only for package-level
340 // type information.
341 for _, info := range iprog.Imported {
342 r.packages[info.Pkg] = info
343 }
344 for _, info := range iprog.Created { // (tests)
345 r.packages[info.Pkg] = info
346 }
347
348 for _, from := range fromObjects {
349 r.check(from)
350 }
351 if r.hadConflicts && !Force {
352 return ConflictError
353 }
354 return r.update()
355 }
356
357 // loadProgram loads the specified set of packages (plus their tests)
358 // and all their dependencies, from source, through the specified build
359 // context. Only packages in pkgs will have their functions bodies typechecked.
360 func loadProgram(ctxt *build.Context, pkgs map[string]bool) (*loader.Program, error) {
361 conf := loader.Config{
362 Build: ctxt,
363 ParserMode: parser.ParseComments,
364
365 // TODO(adonovan): enable this. Requires making a lot of code more robust!
366 AllowErrors: false,
367 }
368 // Optimization: don't type-check the bodies of functions in our
369 // dependencies, since we only need exported package members.
370 conf.TypeCheckFuncBodies = func(p string) bool {
371 return pkgs[p] || pkgs[strings.TrimSuffix(p, "_test")]
372 }
373
374 if Verbose {
375 var list []string
376 for pkg := range pkgs {
377 list = append(list, pkg)
378 }
379 sort.Strings(list)
380 for _, pkg := range list {
381 log.Printf("Loading package: %s", pkg)
382 }
383 }
384
385 for pkg := range pkgs {
386 conf.ImportWithTests(pkg)
387 }
388
389 // Ideally we would just return conf.Load() here, but go/types
390 // reports certain "soft" errors that gc does not (Go issue 14596).
391 // As a workaround, we set AllowErrors=true and then duplicate
392 // the loader's error checking but allow soft errors.
393 // It would be nice if the loader API permitted "AllowErrors: soft".
394 conf.AllowErrors = true
395 prog, err := conf.Load()
396 if err != nil {
397 return nil, err
398 }
399
400 var errpkgs []string
401 // Report hard errors in indirectly imported packages.
402 for _, info := range prog.AllPackages {
403 if containsHardErrors(info.Errors) {
404 errpkgs = append(errpkgs, info.Pkg.Path())
405 }
406 }
407 if errpkgs != nil {
408 var more string
409 if len(errpkgs) > 3 {
410 more = fmt.Sprintf(" and %d more", len(errpkgs)-3)
411 errpkgs = errpkgs[:3]
412 }
413 return nil, fmt.Errorf("couldn't load packages due to errors: %s%s",
414 strings.Join(errpkgs, ", "), more)
415 }
416 return prog, nil
417 }
418
419 func containsHardErrors(errors []error) bool {
420 for _, err := range errors {
421 if err, ok := err.(types.Error); ok && err.Soft {
422 continue
423 }
424 return true
425 }
426 return false
427 }
428
429 // requiresGlobalRename reports whether this renaming could potentially
430 // affect other packages in the Go workspace.
431 func requiresGlobalRename(fromObjects []types.Object, to string) bool {
432 var tfm bool
433 for _, from := range fromObjects {
434 if from.Exported() {
435 return true
436 }
437 switch objectKind(from) {
438 case "type", "field", "method":
439 tfm = true
440 }
441 }
442 if ast.IsExported(to) && tfm {
443 // A global renaming may be necessary even if we're
444 // exporting a previous unexported name, since if it's
445 // the name of a type, field or method, this could
446 // change selections in other packages.
447 // (We include "type" in this list because a type
448 // used as an embedded struct field entails a field
449 // renaming.)
450 return true
451 }
452 return false
453 }
454
455 // update updates the input files.
456 func (r *renamer) update() error {
457 // We use token.File, not filename, since a file may appear to
458 // belong to multiple packages and be parsed more than once.
459 // token.File captures this distinction; filename does not.
460
461 var nidents int
462 var filesToUpdate = make(map[*token.File]bool)
463 docRegexp := regexp.MustCompile(`\b` + r.from + `\b`)
464 for _, info := range r.packages {
465 // Mutate the ASTs and note the filenames.
466 for id, obj := range info.Defs {
467 if r.objsToUpdate[obj] {
468 nidents++
469 id.Name = r.to
470 filesToUpdate[r.iprog.Fset.File(id.Pos())] = true
471 // Perform the rename in doc comments too.
472 if doc := r.docComment(id); doc != nil {
473 for _, comment := range doc.List {
474 comment.Text = docRegexp.ReplaceAllString(comment.Text, r.to)
475 }
476 }
477 }
478 }
479
480 for id, obj := range info.Uses {
481 if r.objsToUpdate[obj] {
482 nidents++
483 id.Name = r.to
484 filesToUpdate[r.iprog.Fset.File(id.Pos())] = true
485 }
486 }
487 }
488
489 // Renaming not supported if cgo files are affected.
490 var generatedFileNames []string
491 for _, info := range r.packages {
492 for _, f := range info.Files {
493 tokenFile := r.iprog.Fset.File(f.FileStart)
494 if filesToUpdate[tokenFile] && ast.IsGenerated(f) {
495 generatedFileNames = append(generatedFileNames, tokenFile.Name())
496 }
497 }
498 }
499 if !Force && len(generatedFileNames) > 0 {
500 return fmt.Errorf("refusing to modify generated file%s containing DO NOT EDIT marker: %v", plural(len(generatedFileNames)), generatedFileNames)
501 }
502
503 // Write affected files.
504 var nerrs, npkgs int
505 for _, info := range r.packages {
506 first := true
507 for _, f := range info.Files {
508 tokenFile := r.iprog.Fset.File(f.FileStart)
509 if filesToUpdate[tokenFile] {
510 if first {
511 npkgs++
512 first = false
513 if Verbose {
514 log.Printf("Updating package %s", info.Pkg.Path())
515 }
516 }
517
518 filename := tokenFile.Name()
519 var buf bytes.Buffer
520 if err := format.Node(&buf, r.iprog.Fset, f); err != nil {
521 log.Printf("failed to pretty-print syntax tree: %v", err)
522 nerrs++
523 continue
524 }
525 if err := writeFile(filename, buf.Bytes()); err != nil {
526 log.Print(err)
527 nerrs++
528 }
529 }
530 }
531 }
532 if !Diff {
533 fmt.Printf("Renamed %d occurrence%s in %d file%s in %d package%s.\n",
534 nidents, plural(nidents),
535 len(filesToUpdate), plural(len(filesToUpdate)),
536 npkgs, plural(npkgs))
537 }
538 if nerrs > 0 {
539 return fmt.Errorf("failed to rewrite %d file%s", nerrs, plural(nerrs))
540 }
541 return nil
542 }
543
544 // docComment returns the doc for an identifier.
545 func (r *renamer) docComment(id *ast.Ident) *ast.CommentGroup {
546 _, nodes, _ := r.iprog.PathEnclosingInterval(id.Pos(), id.End())
547 for _, node := range nodes {
548 switch decl := node.(type) {
549 case *ast.FuncDecl:
550 return decl.Doc
551 case *ast.Field:
552 return decl.Doc
553 case *ast.GenDecl:
554 return decl.Doc
555 // For {Type,Value}Spec, if the doc on the spec is absent,
556 // search for the enclosing GenDecl
557 case *ast.TypeSpec:
558 if decl.Doc != nil {
559 return decl.Doc
560 }
561 case *ast.ValueSpec:
562 if decl.Doc != nil {
563 return decl.Doc
564 }
565 case *ast.Ident:
566 default:
567 return nil
568 }
569 }
570 return nil
571 }
572
573 func plural(n int) string {
574 if n != 1 {
575 return "s"
576 }
577 return ""
578 }
579
580 // writeFile is a seam for testing and for the -d flag.
581 var writeFile = reallyWriteFile
582
583 func reallyWriteFile(filename string, content []byte) error {
584 return os.WriteFile(filename, content, 0644)
585 }
586
587 func diff(filename string, content []byte) error {
588 renamed := fmt.Sprintf("%s.%d.renamed", filename, os.Getpid())
589 if err := os.WriteFile(renamed, content, 0644); err != nil {
590 return err
591 }
592 defer os.Remove(renamed)
593
594 diff, err := exec.Command(DiffCmd, "-u", filename, renamed).Output()
595 if len(diff) > 0 {
596 // diff exits with a non-zero status when the files don't match.
597 // Ignore that failure as long as we get output.
598 stdout.Write(diff)
599 return nil
600 }
601 if err != nil {
602 if exit, ok := err.(*exec.ExitError); ok && len(exit.Stderr) > 0 {
603 err = fmt.Errorf("%w\nstderr:\n%s", err, exit.Stderr)
604 }
605 return fmt.Errorf("computing diff: %v", err)
606 }
607 return nil
608 }