Debian Codegraph @

gopls/internal/golang/rename_check.go

raw symbols SCIP
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4 //
5 // Taken from golang.org/x/tools/refactor/rename.
6
7 package golang
8
9 // This file defines the conflict-checking portion of the rename operation.
10 //
11 // The renamer works on a single package of type-checked syntax, and
12 // is called in parallel for all necessary packages in the workspace,
13 // possibly up to the transitive reverse dependencies of the
14 // declaration. Finally the union of all edits and errors is computed.
15 //
16 // Renaming one object may entail renaming of others. For example:
17 //
18 // - An embedded field couples a Var (field) and a TypeName.
19 // So, renaming either one requires renaming the other.
20 // If the initial object is an embedded field, we must add its
21 // TypeName (and its enclosing package) to the renaming set;
22 // this is easily discovered at the outset.
23 //
24 // Conversely, if the initial object is a TypeName, we must observe
25 // whether any of its references (from directly importing packages)
26 // is coincident with an embedded field Var and, if so, initiate a
27 // renaming of it.
28 //
29 // - A method of an interface type is coupled to all corresponding
30 // methods of types that are assigned to the interface (as
31 // discovered by the 'satisfy' pass). As a matter of usability, we
32 // require that such renamings be initiated from the interface
33 // method, not the concrete method.
34
35 import (
36 "errors"
37 "fmt"
38 "go/ast"
39 "go/build"
40 "go/token"
41 "go/types"
42 "io/fs"
43 "os"
44 "path/filepath"
45 "reflect"
46 "strings"
47 "unicode"
48
49 "golang.org/x/tools/go/ast/astutil"
50 "golang.org/x/tools/go/ast/edge"
51 "golang.org/x/tools/go/ast/inspector"
52 "golang.org/x/tools/gopls/internal/cache"
53 "golang.org/x/tools/gopls/internal/file"
54 "golang.org/x/tools/gopls/internal/util/safetoken"
55 "golang.org/x/tools/internal/typeparams"
56 "golang.org/x/tools/internal/typesinternal"
57 "golang.org/x/tools/refactor/satisfy"
58 )
59
60 // errorf reports an error (e.g. conflict) and prevents file modification.
61 func (r *renamer) errorf(pos token.Pos, format string, args ...any) {
62 // Conflict error messages in the old gorename tool (whence this
63 // logic originated) contain rich information associated with
64 // multiple source lines, such as:
65 //
66 // p/a.go:1:2: renaming "x" to "y" here
67 // p/b.go:3:4: \t would cause this reference to "y"
68 // p/c.go:5:5: \t to become shadowed by this intervening declaration.
69 //
70 // Unfortunately LSP provides no means to transmit the
71 // structure of this error, so we format the positions briefly
72 // using dir/file.go where dir is the base name of the parent
73 // directory.
74
75 var conflict strings.Builder
76
77 // Add prefix of (truncated) position.
78 if pos != token.NoPos {
79 // TODO(adonovan): skip position of first error if it is
80 // on the same line as the renaming itself.
81 posn := safetoken.StartPosition(r.pkg.FileSet(), pos).String()
82 segments := strings.Split(filepath.ToSlash(posn), "/")
83 if n := len(segments); n > 2 {
84 segments = segments[n-2:]
85 }
86 posn = strings.Join(segments, "/")
87 fmt.Fprintf(&conflict, "%s:", posn)
88
89 if !strings.HasPrefix(format, "\t") {
90 conflict.WriteByte(' ')
91 }
92 }
93
94 fmt.Fprintf(&conflict, format, args...)
95 r.conflicts = append(r.conflicts, conflict.String())
96 }
97
98 // check performs safety checks of the renaming of the 'from' object to r.to.
99 func (r *renamer) check(from types.Object) {
100 if r.objsToUpdate[from] {
101 return
102 }
103 r.objsToUpdate[from] = true
104
105 // NB: order of conditions is important.
106 if from_, ok := from.(*types.PkgName); ok {
107 r.checkInFileBlock(from_)
108 } else if from_, ok := from.(*types.Label); ok {
109 r.checkLabel(from_)
110 } else if typesinternal.IsPackageLevel(from) {
111 r.checkInPackageBlock(from)
112 } else if v, ok := from.(*types.Var); ok && v.IsField() {
113 r.checkStructField(v)
114 } else if f, ok := from.(*types.Func); ok && recv(f) != nil {
115 r.checkMethod(f)
116 } else if isLocal(from) {
117 r.checkInLexicalScope(from)
118 } else {
119 r.errorf(from.Pos(), "unexpected %s object %q (please report a bug)\n",
120 objectKind(from), from)
121 }
122 }
123
124 // checkInFileBlock performs safety checks for renames of objects in the file block,
125 // i.e. imported package names.
126 func (r *renamer) checkInFileBlock(from *types.PkgName) {
127 // Check import name is not "init".
128 if r.to == "init" {
129 r.errorf(from.Pos(), "%q is not a valid imported package name", r.to)
130 }
131
132 // Check for conflicts between file and package block.
133 if prev := from.Pkg().Scope().Lookup(r.to); prev != nil {
134 r.errorf(from.Pos(), "renaming this %s %q to %q would conflict",
135 objectKind(from), from.Name(), r.to)
136 r.errorf(prev.Pos(), "\twith this package member %s",
137 objectKind(prev))
138 return // since checkInPackageBlock would report redundant errors
139 }
140
141 // Check for conflicts in lexical scope.
142 r.checkInLexicalScope(from)
143 }
144
145 // checkInPackageBlock performs safety checks for renames of
146 // func/var/const/type objects in the package block.
147 func (r *renamer) checkInPackageBlock(from types.Object) {
148 // Check that there are no references to the name from another
149 // package if the renaming would make it unexported.
150 if typ := r.pkg.Types(); typ != from.Pkg() && ast.IsExported(r.from) && !ast.IsExported(r.to) {
151 if id := someUse(r.pkg.TypesInfo(), from); id != nil {
152 r.checkExport(id, typ, from)
153 }
154 }
155
156 // Check that in the package block, "init" is a function, and never referenced.
157 if r.to == "init" {
158 kind := objectKind(from)
159 if kind == "func" {
160 // Reject if intra-package references to it exist.
161 for id, obj := range r.pkg.TypesInfo().Uses {
162 if obj == from {
163 r.errorf(from.Pos(),
164 "renaming this func %q to %q would make it a package initializer",
165 from.Name(), r.to)
166 r.errorf(id.Pos(), "\tbut references to it exist")
167 break
168 }
169 }
170 } else {
171 r.errorf(from.Pos(), "you cannot have a %s at package level named %q",
172 kind, r.to)
173 }
174 }
175
176 // In the declaring package, check for conflicts between the
177 // package block and all file blocks.
178 if from.Pkg() == r.pkg.Types() {
179 for _, f := range r.pkg.Syntax() {
180 fileScope := r.pkg.TypesInfo().Scopes[f]
181 if fileScope == nil {
182 continue // type error? (golang/go#40835)
183 }
184 b, prev := fileScope.LookupParent(r.to, token.NoPos)
185 if b == fileScope {
186 r.errorf(from.Pos(), "renaming this %s %q to %q would conflict", objectKind(from), from.Name(), r.to)
187 r.errorf(prev.Pos(), "\twith this %s", objectKind(prev))
188 return // since checkInPackageBlock would report redundant errors
189 }
190 }
191 }
192
193 // Check for conflicts in lexical scope.
194 r.checkInLexicalScope(from)
195 }
196
197 // checkInLexicalScope performs safety checks that a renaming does not
198 // change the lexical reference structure of the specified package.
199 //
200 // For objects in lexical scope, there are three kinds of conflicts:
201 // same-, sub-, and super-block conflicts. We will illustrate all three
202 // using this example:
203 //
204 // var x int
205 // var z int
206 //
207 // func f(y int) {
208 // print(x)
209 // print(y)
210 // }
211 //
212 // Renaming x to z encounters a "same-block conflict", because an object
213 // with the new name already exists, defined in the same lexical block
214 // as the old object.
215 //
216 // Renaming x to y encounters a "sub-block conflict", because there exists
217 // a reference to x from within (what would become) a hole in its scope.
218 // The definition of y in an (inner) sub-block would cast a shadow in
219 // the scope of the renamed variable.
220 //
221 // Renaming y to x encounters a "super-block conflict". This is the
222 // converse situation: there is an existing definition of the new name
223 // (x) in an (enclosing) super-block, and the renaming would create a
224 // hole in its scope, within which there exist references to it. The
225 // new name shadows the existing definition of x in the super-block.
226 //
227 // Removing the old name (and all references to it) is always safe, and
228 // requires no checks.
229 func (r *renamer) checkInLexicalScope(from types.Object) {
230 b := from.Parent() // the block defining the 'from' object
231 if b != nil {
232 toBlock, to := b.LookupParent(r.to, from.Parent().End())
233 if toBlock == b {
234 // same-block conflict
235 r.errorf(from.Pos(), "renaming this %s %q to %q",
236 objectKind(from), from.Name(), r.to)
237 r.errorf(to.Pos(), "\tconflicts with %s in same block",
238 objectKind(to))
239 return
240 } else if toBlock != nil {
241 // Check for super-block conflict.
242 // The name r.to is defined in a superblock.
243 // Is that name referenced from within this block?
244 forEachLexicalRef(r.pkg, to, func(id *ast.Ident, block *types.Scope) bool {
245 _, obj := block.LookupParent(from.Name(), id.Pos())
246 if obj == from {
247 // super-block conflict
248 r.errorf(from.Pos(), "renaming this %s %q to %q",
249 objectKind(from), from.Name(), r.to)
250 r.errorf(id.Pos(), "\twould shadow this reference")
251 r.errorf(to.Pos(), "\tto the %s declared here",
252 objectKind(to))
253 return false // stop
254 }
255 return true
256 })
257 }
258 }
259 // Check for sub-block conflict.
260 // Is there an intervening definition of r.to between
261 // the block defining 'from' and some reference to it?
262 forEachLexicalRef(r.pkg, from, func(id *ast.Ident, block *types.Scope) bool {
263 // Find the block that defines the found reference.
264 // It may be an ancestor.
265 fromBlock, _ := block.LookupParent(from.Name(), id.Pos())
266 // See what r.to would resolve to in the same scope.
267 toBlock, to := block.LookupParent(r.to, id.Pos())
268 if to != nil {
269 // sub-block conflict
270 if deeper(toBlock, fromBlock) {
271 r.errorf(from.Pos(), "renaming this %s %q to %q",
272 objectKind(from), from.Name(), r.to)
273 r.errorf(id.Pos(), "\twould cause this reference to become shadowed")
274 r.errorf(to.Pos(), "\tby this intervening %s definition",
275 objectKind(to))
276 return false // stop
277 }
278 }
279 return true
280 })
281
282 // Renaming a type that is used as an embedded field
283 // requires renaming the field too. e.g.
284 // type T int // if we rename this to U..
285 // var s struct {T}
286 // print(s.T) // ...this must change too
287 if _, ok := from.(*types.TypeName); ok {
288 for id, obj := range r.pkg.TypesInfo().Uses {
289 if obj == from {
290 if field := r.pkg.TypesInfo().Defs[id]; field != nil {
291 r.check(field)
292 }
293 }
294 }
295 }
296 }
297
298 // deeper reports whether block x is lexically deeper than y.
299 func deeper(x, y *types.Scope) bool {
300 if x == y || x == nil {
301 return false
302 } else if y == nil {
303 return true
304 } else {
305 return deeper(x.Parent(), y.Parent())
306 }
307 }
308
309 // Scope and Position
310 //
311 // Consider a function f declared as:
312 //
313 // func f[T *U, U *T](p, q T) (r, s U) { var ( v T; w = v ); type (t *t; u t) }
314 // ^ ^ ^ ^ ^ ^
315 /// {T,U} {p,q,r,s} v w t u
316 //
317 // All objects {T, U, p, q, r, s, local} belong to the same lexical
318 // block, the function scope, which is found in types.Info.Scopes
319 // for f's FuncType. (A function body's BlockStmt does not have
320 // an associated scope; only nested BlockStmts do.)
321 //
322 // The effective scope of each object is different:
323 //
324 // - The type parameters T and U, whose constraints may refer to each
325 // other, all have a scope that starts at the beginning of the
326 // FuncDecl.Type.Func token.
327 //
328 // - The parameter and result variables {p,q,r,s} can reference the
329 // type parameters but not each other, so their scopes all start at
330 // the end of the FuncType.
331 // (Prior to go1.22 it was--incorrectly--unset; see #64295).
332 // Beware also that Scope.Innermost does not currently work correctly for
333 // type parameters: it returns the scope of the package, not the function.
334 //
335 // - Each const or var {v,w} declared within the function body has a
336 // scope that begins at the end of its ValueSpec, or after the
337 // AssignStmt for a var declared by ":=".
338 //
339 // - Each type {t,u} in the body has a scope that begins at
340 // the start of the TypeSpec, so they can be self-recursive
341 // but--unlike package-level types--not mutually recursive.
342
343 // forEachLexicalRef calls fn(id, block) for each identifier id in package
344 // pkg that is a reference to obj in lexical scope. block is the
345 // lexical block enclosing the reference. If fn returns false the
346 // iteration is terminated and findLexicalRefs returns false.
347 func forEachLexicalRef(pkg *cache.Package, obj types.Object, fn func(id *ast.Ident, block *types.Scope) bool) bool {
348 filter := []ast.Node{
349 (*ast.Ident)(nil),
350 (*ast.SelectorExpr)(nil),
351 (*ast.CompositeLit)(nil),
352 }
353 ok := true
354 var visit func(cur inspector.Cursor) (descend bool)
355 visit = func(cur inspector.Cursor) (descend bool) {
356 if !ok {
357 return false // bail out
358 }
359 switch n := cur.Node().(type) {
360 case *ast.Ident:
361 if pkg.TypesInfo().Uses[n] == obj {
362 block := typesinternal.EnclosingScope(pkg.TypesInfo(), cur)
363 if !fn(n, block) {
364 ok = false
365 }
366 }
367
368 case *ast.SelectorExpr:
369 // don't visit n.Sel
370 cur.ChildAt(edge.SelectorExpr_X, -1).Inspect(filter, visit)
371 return false // don't descend
372
373 case *ast.CompositeLit:
374 // Handle recursion ourselves for struct literals
375 // so we don't visit field identifiers.
376 tv, ok := pkg.TypesInfo().Types[n]
377 if !ok {
378 return false // don't descend
379 }
380 if is[*types.Struct](typeparams.CoreType(typeparams.Deref(tv.Type))) {
381 if n.Type != nil {
382 cur.ChildAt(edge.CompositeLit_Type, -1).Inspect(filter, visit)
383 }
384 for i, elt := range n.Elts {
385 curElt := cur.ChildAt(edge.CompositeLit_Elts, i)
386 if _, ok := elt.(*ast.KeyValueExpr); ok {
387 // skip kv.Key
388 curElt = curElt.ChildAt(edge.KeyValueExpr_Value, -1)
389 }
390 curElt.Inspect(filter, visit)
391 }
392 return false // don't descend
393 }
394 }
395 return true
396 }
397
398 for _, pgf := range pkg.CompiledGoFiles() {
399 pgf.Cursor().Inspect(filter, visit)
400 if !ok {
401 break
402 }
403 }
404 return ok
405 }
406
407 func (r *renamer) checkLabel(label *types.Label) {
408 // Check there are no identical labels in the function's label block.
409 // (Label blocks don't nest, so this is easy.)
410 if prev := label.Parent().Lookup(r.to); prev != nil {
411 r.errorf(label.Pos(), "renaming this label %q to %q", label.Name(), prev.Name())
412 r.errorf(prev.Pos(), "\twould conflict with this one")
413 }
414 }
415
416 // checkStructField checks that the field renaming will not cause
417 // conflicts at its declaration, or ambiguity or changes to any selection.
418 func (r *renamer) checkStructField(from *types.Var) {
419 // If this is the declaring package, check that the struct
420 // declaration is free of field conflicts, and field/method
421 // conflicts.
422 //
423 // go/types offers no easy way to get from a field (or interface
424 // method) to its declaring struct (or interface), so we must
425 // ascend the AST.
426 if pgf, err := r.pkg.FileEnclosing(from.Pos()); err == nil {
427 path, _ := astutil.PathEnclosingInterval(pgf.File, from.Pos(), from.Pos())
428 // path matches this pattern:
429 // [Ident SelectorExpr? StarExpr? Field FieldList StructType ParenExpr* ... File]
430
431 // Ascend to FieldList.
432 var i int
433 for {
434 if _, ok := path[i].(*ast.FieldList); ok {
435 break
436 }
437 i++
438 }
439 i++
440 tStruct := path[i].(*ast.StructType)
441 i++
442 // Ascend past parens (unlikely).
443 for {
444 _, ok := path[i].(*ast.ParenExpr)
445 if !ok {
446 break
447 }
448 i++
449 }
450 if spec, ok := path[i].(*ast.TypeSpec); ok {
451 // This struct is also a named type.
452 // We must check for direct (non-promoted) field/field
453 // and method/field conflicts.
454 if tname := r.pkg.TypesInfo().Defs[spec.Name]; tname != nil {
455 prev, indices, _ := types.LookupFieldOrMethod(tname.Type(), true, r.pkg.Types(), r.to)
456 if len(indices) == 1 {
457 r.errorf(from.Pos(), "renaming this field %q to %q",
458 from.Name(), r.to)
459 r.errorf(prev.Pos(), "\twould conflict with this %s",
460 objectKind(prev))
461 return // skip checkSelections to avoid redundant errors
462 }
463 }
464 } else {
465 // This struct is not a named type.
466 // We need only check for direct (non-promoted) field/field conflicts.
467 T := r.pkg.TypesInfo().Types[tStruct].Type.Underlying().(*types.Struct)
468 for prev := range T.Fields() {
469 if prev.Name() == r.to {
470 r.errorf(from.Pos(), "renaming this field %q to %q",
471 from.Name(), r.to)
472 r.errorf(prev.Pos(), "\twould conflict with this field")
473 return // skip checkSelections to avoid redundant errors
474 }
475 }
476 }
477 }
478
479 // Renaming an anonymous field requires renaming the type too. e.g.
480 // print(s.T) // if we rename T to U,
481 // type T int // this and
482 // var s struct {T} // this must change too.
483 if from.Anonymous() {
484 if named, ok := from.Type().(*types.Named); ok {
485 r.check(named.Obj())
486 } else if named, ok := types.Unalias(typesinternal.Unpointer(from.Type())).(*types.Named); ok {
487 r.check(named.Obj())
488 }
489 }
490
491 // Check integrity of existing (field and method) selections.
492 r.checkSelections(from)
493 }
494
495 // checkSelections checks that all uses and selections that resolve to
496 // the specified object would continue to do so after the renaming.
497 func (r *renamer) checkSelections(from types.Object) {
498 pkg := r.pkg
499 typ := pkg.Types()
500 {
501 if id := someUse(pkg.TypesInfo(), from); id != nil {
502 if !r.checkExport(id, typ, from) {
503 return
504 }
505 }
506
507 for syntax, sel := range pkg.TypesInfo().Selections {
508 // There may be extant selections of only the old
509 // name or only the new name, so we must check both.
510 // (If neither, the renaming is sound.)
511 //
512 // In both cases, we wish to compare the lengths
513 // of the implicit field path (Selection.Index)
514 // to see if the renaming would change it.
515 //
516 // If a selection that resolves to 'from', when renamed,
517 // would yield a path of the same or shorter length,
518 // this indicates ambiguity or a changed referent,
519 // analogous to same- or sub-block lexical conflict.
520 //
521 // If a selection using the name 'to' would
522 // yield a path of the same or shorter length,
523 // this indicates ambiguity or shadowing,
524 // analogous to same- or super-block lexical conflict.
525
526 // TODO(adonovan): fix: derive from Types[syntax.X].Mode
527 // TODO(adonovan): test with pointer, value, addressable value.
528 isAddressable := true
529
530 if sel.Obj() == from {
531 if obj, indices, _ := types.LookupFieldOrMethod(sel.Recv(), isAddressable, from.Pkg(), r.to); obj != nil {
532 // Renaming this existing selection of
533 // 'from' may block access to an existing
534 // type member named 'to'.
535 delta := len(indices) - len(sel.Index())
536 if delta > 0 {
537 continue // no ambiguity
538 }
539 r.selectionConflict(from, delta, syntax, obj)
540 return
541 }
542 } else if sel.Obj().Name() == r.to {
543 if obj, indices, _ := types.LookupFieldOrMethod(sel.Recv(), isAddressable, from.Pkg(), from.Name()); obj == from {
544 // Renaming 'from' may cause this existing
545 // selection of the name 'to' to change
546 // its meaning.
547 delta := len(indices) - len(sel.Index())
548 if delta > 0 {
549 continue // no ambiguity
550 }
551 r.selectionConflict(from, -delta, syntax, sel.Obj())
552 return
553 }
554 }
555 }
556 }
557 }
558
559 func (r *renamer) selectionConflict(from types.Object, delta int, syntax *ast.SelectorExpr, obj types.Object) {
560 r.errorf(from.Pos(), "renaming this %s %q to %q",
561 objectKind(from), from.Name(), r.to)
562
563 switch {
564 case delta < 0:
565 // analogous to sub-block conflict
566 r.errorf(syntax.Sel.Pos(),
567 "\twould change the referent of this selection")
568 r.errorf(obj.Pos(), "\tof this %s", objectKind(obj))
569 case delta == 0:
570 // analogous to same-block conflict
571 r.errorf(syntax.Sel.Pos(),
572 "\twould make this reference ambiguous")
573 r.errorf(obj.Pos(), "\twith this %s", objectKind(obj))
574 case delta > 0:
575 // analogous to super-block conflict
576 r.errorf(syntax.Sel.Pos(),
577 "\twould shadow this selection")
578 r.errorf(obj.Pos(), "\tof the %s declared here",
579 objectKind(obj))
580 }
581 }
582
583 // checkMethod performs safety checks for renaming a method.
584 // There are three hazards:
585 // - declaration conflicts
586 // - selection ambiguity/changes
587 // - entailed renamings of assignable concrete/interface types.
588 //
589 // We reject renamings initiated at concrete methods if it would
590 // change the assignability relation. For renamings of abstract
591 // methods, we rename all methods transitively coupled to it via
592 // assignability.
593 func (r *renamer) checkMethod(from *types.Func) {
594 // e.g. error.Error
595 if from.Pkg() == nil {
596 r.errorf(from.Pos(), "you cannot rename built-in method %s", from)
597 return
598 }
599
600 // ASSIGNABILITY: We reject renamings of concrete methods that
601 // would break a 'satisfy' constraint; but renamings of abstract
602 // methods are allowed to proceed, and we rename affected
603 // concrete and abstract methods as necessary. It is the
604 // initial method that determines the policy.
605
606 // Check for conflict at point of declaration.
607 // Check to ensure preservation of assignability requirements.
608 R := recv(from).Type()
609 if types.IsInterface(R) {
610 // Abstract method
611
612 // declaration
613 prev, _, _ := types.LookupFieldOrMethod(R, false, from.Pkg(), r.to)
614 if prev != nil {
615 r.errorf(from.Pos(), "renaming this interface method %q to %q",
616 from.Name(), r.to)
617 r.errorf(prev.Pos(), "\twould conflict with this method")
618 return
619 }
620
621 // Check all interfaces that embed this one for
622 // declaration conflicts too.
623 {
624 // Start with named interface types (better errors)
625 for _, obj := range r.pkg.TypesInfo().Defs {
626 if obj, ok := obj.(*types.TypeName); ok && types.IsInterface(obj.Type()) {
627 f, _, _ := types.LookupFieldOrMethod(
628 obj.Type(), false, from.Pkg(), from.Name())
629 if f == nil {
630 continue
631 }
632 t, _, _ := types.LookupFieldOrMethod(
633 obj.Type(), false, from.Pkg(), r.to)
634 if t == nil {
635 continue
636 }
637 r.errorf(from.Pos(), "renaming this interface method %q to %q",
638 from.Name(), r.to)
639 r.errorf(t.Pos(), "\twould conflict with this method")
640 r.errorf(obj.Pos(), "\tin named interface type %q", obj.Name())
641 }
642 }
643
644 // Now look at all literal interface types (includes named ones again).
645 for e, tv := range r.pkg.TypesInfo().Types {
646 if e, ok := e.(*ast.InterfaceType); ok {
647 _ = e
648 _ = tv.Type.(*types.Interface)
649 // TODO(adonovan): implement same check as above.
650 }
651 }
652 }
653
654 // assignability
655 //
656 // Find the set of concrete or abstract methods directly
657 // coupled to abstract method 'from' by some
658 // satisfy.Constraint, and rename them too.
659 for key := range r.satisfy() {
660 // key = (lhs, rhs) where lhs is always an interface.
661
662 lsel := r.msets.MethodSet(key.LHS).Lookup(from.Pkg(), from.Name())
663 if lsel == nil {
664 continue
665 }
666 rmethods := r.msets.MethodSet(key.RHS)
667 rsel := rmethods.Lookup(from.Pkg(), from.Name())
668 if rsel == nil {
669 continue
670 }
671
672 // If both sides have a method of this name,
673 // and one of them is m, the other must be coupled.
674 var coupled *types.Func
675 switch from {
676 case lsel.Obj():
677 coupled = rsel.Obj().(*types.Func)
678 case rsel.Obj():
679 coupled = lsel.Obj().(*types.Func)
680 default:
681 continue
682 }
683
684 // We must treat concrete-to-interface
685 // constraints like an implicit selection C.f of
686 // each interface method I.f, and check that the
687 // renaming leaves the selection unchanged and
688 // unambiguous.
689 //
690 // Fun fact: the implicit selection of C.f
691 // type I interface{f()}
692 // type C struct{I}
693 // func (C) g()
694 // var _ I = C{} // here
695 // yields abstract method I.f. This can make error
696 // messages less than obvious.
697 //
698 if !types.IsInterface(key.RHS) {
699 // The logic below was derived from checkSelections.
700
701 rtosel := rmethods.Lookup(from.Pkg(), r.to)
702 if rtosel != nil {
703 rto := rtosel.Obj().(*types.Func)
704 delta := len(rsel.Index()) - len(rtosel.Index())
705 if delta < 0 {
706 continue // no ambiguity
707 }
708
709 // TODO(adonovan): record the constraint's position.
710 keyPos := token.NoPos
711
712 r.errorf(from.Pos(), "renaming this method %q to %q",
713 from.Name(), r.to)
714 if delta == 0 {
715 // analogous to same-block conflict
716 r.errorf(keyPos, "\twould make the %s method of %s invoked via interface %s ambiguous",
717 r.to, key.RHS, key.LHS)
718 r.errorf(rto.Pos(), "\twith (%s).%s",
719 recv(rto).Type(), r.to)
720 } else {
721 // analogous to super-block conflict
722 r.errorf(keyPos, "\twould change the %s method of %s invoked via interface %s",
723 r.to, key.RHS, key.LHS)
724 r.errorf(coupled.Pos(), "\tfrom (%s).%s",
725 recv(coupled).Type(), r.to)
726 r.errorf(rto.Pos(), "\tto (%s).%s",
727 recv(rto).Type(), r.to)
728 }
729 return // one error is enough
730 }
731 }
732
733 if !r.changeMethods {
734 // This should be unreachable.
735 r.errorf(from.Pos(), "internal error: during renaming of abstract method %s", from)
736 r.errorf(coupled.Pos(), "\tchangedMethods=false, coupled method=%s", coupled)
737 r.errorf(from.Pos(), "\tPlease file a bug report")
738 return
739 }
740
741 // Rename the coupled method to preserve assignability.
742 r.check(coupled)
743 }
744 } else {
745 // Concrete method
746
747 // declaration
748 prev, indices, _ := types.LookupFieldOrMethod(R, true, from.Pkg(), r.to)
749 if prev != nil && len(indices) == 1 {
750 r.errorf(from.Pos(), "renaming this method %q to %q",
751 from.Name(), r.to)
752 r.errorf(prev.Pos(), "\twould conflict with this %s",
753 objectKind(prev))
754 return
755 }
756
757 // assignability
758 //
759 // Find the set of abstract methods coupled to concrete
760 // method 'from' by some satisfy.Constraint, and rename
761 // them too.
762 //
763 // Coupling may be indirect, e.g. I.f <-> C.f via type D.
764 //
765 // type I interface {f()}
766 // type C int
767 // type (C) f()
768 // type D struct{C}
769 // var _ I = D{}
770 //
771 for key := range r.satisfy() {
772 // key = (lhs, rhs) where lhs is always an interface.
773 if types.IsInterface(key.RHS) {
774 continue
775 }
776 rsel := r.msets.MethodSet(key.RHS).Lookup(from.Pkg(), from.Name())
777 if rsel == nil || rsel.Obj() != from {
778 continue // rhs does not have the method
779 }
780 lsel := r.msets.MethodSet(key.LHS).Lookup(from.Pkg(), from.Name())
781 if lsel == nil {
782 continue
783 }
784 imeth := lsel.Obj().(*types.Func)
785
786 // imeth is the abstract method (e.g. I.f)
787 // and key.RHS is the concrete coupling type (e.g. D).
788 if !r.changeMethods {
789 r.errorf(from.Pos(), "renaming this method %q to %q",
790 from.Name(), r.to)
791 var pos token.Pos
792 var iface string
793
794 I := recv(imeth).Type()
795 if named, ok := types.Unalias(I).(*types.Named); ok {
796 pos = named.Obj().Pos()
797 iface = "interface " + named.Obj().Name()
798 } else {
799 pos = from.Pos()
800 iface = I.String()
801 }
802 r.errorf(pos, "\twould make %s no longer assignable to %s",
803 key.RHS, iface)
804 r.errorf(imeth.Pos(), "\t(rename %s.%s if you intend to change both types)",
805 I, from.Name())
806 return // one error is enough
807 }
808
809 // Rename the coupled interface method to preserve assignability.
810 r.check(imeth)
811 }
812 }
813
814 // Check integrity of existing (field and method) selections.
815 // We skip this if there were errors above, to avoid redundant errors.
816 r.checkSelections(from)
817 }
818
819 func (r *renamer) checkExport(id *ast.Ident, pkg *types.Package, from types.Object) bool {
820 // Reject cross-package references if r.to is unexported.
821 // (Such references may be qualified identifiers or field/method
822 // selections.)
823 if !ast.IsExported(r.to) && pkg != from.Pkg() {
824 r.errorf(from.Pos(),
825 "renaming %q to %q would make it unexported",
826 from.Name(), r.to)
827 r.errorf(id.Pos(), "\tbreaking references from packages such as %q",
828 pkg.Path())
829 return false
830 }
831 return true
832 }
833
834 // satisfy returns the set of interface satisfaction constraints.
835 func (r *renamer) satisfy() map[satisfy.Constraint]bool {
836 if r.satisfyConstraints == nil {
837 // Compute on demand: it's expensive.
838 var f satisfy.Finder
839 pkg := r.pkg
840 {
841 // From satisfy.Finder documentation:
842 //
843 // The package must be free of type errors, and
844 // info.{Defs,Uses,Selections,Types} must have been populated by the
845 // type-checker.
846 //
847 // Only proceed if all packages have no errors.
848 if len(pkg.ParseErrors()) > 0 || len(pkg.TypeErrors()) > 0 {
849 var filename string
850 if len(pkg.ParseErrors()) > 0 {
851 err := pkg.ParseErrors()[0][0]
852 filename = filepath.Base(err.Pos.Filename)
853 } else if len(pkg.TypeErrors()) > 0 {
854 err := pkg.TypeErrors()[0]
855 filename = filepath.Base(err.Fset.File(err.Pos).Name())
856 }
857 r.errorf(token.NoPos, // we don't have a position for this error.
858 "renaming %q to %q not possible because %q in %q has errors",
859 r.from, r.to, filename, pkg.Metadata().PkgPath)
860 return nil
861 }
862 f.Find(pkg.TypesInfo(), pkg.Syntax())
863 }
864 r.satisfyConstraints = f.Result
865 }
866 return r.satisfyConstraints
867 }
868
869 // -- helpers ----------------------------------------------------------
870
871 // recv returns the method's receiver.
872 func recv(meth *types.Func) *types.Var {
873 return meth.Signature().Recv()
874 }
875
876 // someUse returns an arbitrary use of obj within info.
877 func someUse(info *types.Info, obj types.Object) *ast.Ident {
878 for id, o := range info.Uses {
879 if o == obj {
880 return id
881 }
882 }
883 return nil
884 }
885
886 func objectKind(obj types.Object) string {
887 if obj == nil {
888 return "nil object"
889 }
890 switch obj := obj.(type) {
891 case *types.PkgName:
892 return "imported package name"
893 case *types.TypeName:
894 return "type"
895 case *types.Var:
896 if obj.IsField() {
897 return "field"
898 }
899 case *types.Func:
900 if recv(obj) != nil {
901 return "method"
902 }
903 }
904 // label, func, var, const
905 return strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types."))
906 }
907
908 // NB: for renamings, blank is not considered valid.
909 func isValidIdentifier(id string) bool {
910 if id == "" || id == "_" {
911 return false
912 }
913 for i, r := range id {
914 if !isLetter(r) && (i == 0 || !isDigit(r)) {
915 return false
916 }
917 }
918 return token.Lookup(id) == token.IDENT
919 }
920
921 // checkPackageRename returns the effective new package directory, path and name
922 // resulting from renaming the current package to newName, which may be an
923 // identifier or a package path. An error is returned if the renaming is
924 // invalid.
925 func checkPackageRename(curPkg *cache.Package, f file.Handle, newName string, moveSubpackages bool) (newPkgDir string, newPkgName PackageName, newPkgPath PackagePath, err error) {
926 // Path unchanged
927 if newName == curPkg.String() || newName == string(curPkg.Metadata().Name) {
928 return f.URI().DirPath(), curPkg.Metadata().Name, curPkg.Metadata().PkgPath, nil
929 }
930
931 // If there are any Go files in the package that are not in the compiled package
932 // with the current build config, we should not allow a package move.
933 ignored := hasIgnoredGoFiles(curPkg)
934 if ignored {
935 return "", "", "", fmt.Errorf("moving a package with ignored files is not supported")
936 }
937
938 // TODO(mkalil): support relative paths
939 if build.IsLocalImport(newName) {
940 return "", "", "", fmt.Errorf("specifying relative paths in package rename not yet supported")
941 }
942 // When package move is enabled, we prompt with the full package path. Users
943 // can either submit a full package path or just provide the package
944 // identifier.
945 validIdent := isValidIdentifier(newName)
946 if validIdent {
947 // Not an attempted move. Check if a directory already exists at that
948 // path, in which case we should not allow renaming.
949 root := filepath.Dir(f.URI().DirPath())
950 newPkgDir = filepath.Join(root, newName)
951 exists, empty, err := dirIsEmpty(newPkgDir)
952 if err != nil {
953 return "", "", "", err
954 }
955 // When rename moves subpackages, we merely change the directory name, which cannot
956 // happen if the target directory already exists.
957 if moveSubpackages && exists || !empty {
958 return "", "", "", fmt.Errorf("invalid package identifier: %q is not empty", newPkgDir)
959 }
960 parentPkgPath := strings.TrimSuffix(string(curPkg.Metadata().PkgPath), string(curPkg.Metadata().Name)) // leaves a trailing slash
961 newPkgPath = PackagePath(parentPkgPath + newName)
962 newPkgName = PackageName(newName)
963 return newPkgDir, newPkgName, newPkgPath, nil
964 }
965 // Don't allow moving packages across module boundaries.
966 curModPath := curPkg.Metadata().Module.Path
967 if !strings.HasPrefix(newName+"/", curModPath+"/") {
968 return "", "", "", fmt.Errorf("invalid package path %q; cannot move package across module boundary", newName)
969 }
970 // Don't support package merging. If a directory already exists
971 // at that path, we should not allow renaming.
972 newPathAfterMod := strings.TrimPrefix(newName, curModPath) //newName is a package path here.
973 modDir := curPkg.Metadata().Module.Dir
974 newPkgDir = filepath.Join(modDir, filepath.FromSlash(newPathAfterMod))
975 // Trim the starting slash, which is not considered valid in fs.ValidPath.
976 isValidDir := fs.ValidPath(strings.TrimPrefix(newPkgDir, string(filepath.Separator)))
977 if !isValidDir {
978 return "", "", "", fmt.Errorf("invalid package path %q", newName)
979 }
980 newPkgName = PackageName(filepath.Base(newPkgDir))
981 exists, empty, err := dirIsEmpty(newPkgDir)
982 if err != nil {
983 return "", "", "", err
984 }
985 // When rename moves subpackages, we merely change the directory name, which cannot
986 // happen if the target directory already exists.
987 if moveSubpackages && exists || !empty {
988 return "", "", "", fmt.Errorf("invalid package path: %q is not empty", newPkgDir)
989 }
990 // Verify that the new package name is a valid identifier.
991 if !isValidIdentifier(string(newPkgName)) {
992 return "", "", "", fmt.Errorf("invalid package name %q", newPkgName)
993 }
994 if f.URI().Dir().Base() != string(curPkg.Metadata().Name) {
995 return "", "", "", fmt.Errorf("can't move package: package name %q does not match directory base name %q", string(curPkg.Metadata().Name), f.URI().Dir().Base())
996 }
997 return newPkgDir, newPkgName, PackagePath(newName), nil
998 }
999
1000 // hasIgnoredGoFiles returns true if the input pkg contains any Go files that
1001 // are not part of package pkg with the current build configuration.
1002 func hasIgnoredGoFiles(pkg *cache.Package) bool {
1003 // If any ignored files are Go files, don't allow a package move.
1004 for _, f := range pkg.Metadata().IgnoredFiles {
1005 if strings.HasSuffix(f.Path(), ".go") {
1006 return true
1007 }
1008 }
1009 return false
1010 }
1011
1012 // dirIsEmpty returns two values: whether the directory exists and whether it is
1013 // empty (contains only directory entries). If it does not exist, empty is
1014 // always true.
1015 func dirIsEmpty(dir string) (exists bool, empty bool, err error) {
1016 files, err := os.ReadDir(dir)
1017 if err != nil {
1018 if errors.Is(err, fs.ErrNotExist) {
1019 return false, true, nil
1020 } else {
1021 return false, false, err
1022 }
1023 }
1024 for _, f := range files {
1025 if !f.IsDir() {
1026 return true, false, nil
1027 }
1028 }
1029 return true, true, nil
1030 }
1031
1032 // isLocal reports whether obj is local to some function.
1033 // Precondition: not a struct field or interface method.
1034 func isLocal(obj types.Object) bool {
1035 // [... 5=stmt 4=func 3=file 2=pkg 1=universe]
1036 var depth int
1037 for scope := obj.Parent(); scope != nil; scope = scope.Parent() {
1038 depth++
1039 }
1040 return depth >= 4
1041 }
1042
1043 // -- Plundered from go/scanner: ---------------------------------------
1044
1045 func isLetter(ch rune) bool {
1046 return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
1047 }
1048
1049 func isDigit(ch rune) bool {
1050 return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch)
1051 }