Debian Codegraph @

refactor/rename/check.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
6
7 // This file defines the safety checks for each kind of renaming.
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/token"
13 "go/types"
14
15 "golang.org/x/tools/go/loader"
16 "golang.org/x/tools/internal/typeparams"
17 "golang.org/x/tools/internal/typesinternal"
18 "golang.org/x/tools/refactor/satisfy"
19 )
20
21 // errorf reports an error (e.g. conflict) and prevents file modification.
22 func (r *renamer) errorf(pos token.Pos, format string, args ...any) {
23 r.hadConflicts = true
24 reportError(r.iprog.Fset.Position(pos), fmt.Sprintf(format, args...))
25 }
26
27 // check performs safety checks of the renaming of the 'from' object to r.to.
28 func (r *renamer) check(from types.Object) {
29 if r.objsToUpdate[from] {
30 return
31 }
32 r.objsToUpdate[from] = true
33
34 // NB: order of conditions is important.
35 if from_, ok := from.(*types.PkgName); ok {
36 r.checkInFileBlock(from_)
37 } else if from_, ok := from.(*types.Label); ok {
38 r.checkLabel(from_)
39 } else if typesinternal.IsPackageLevel(from) {
40 r.checkInPackageBlock(from)
41 } else if v, ok := from.(*types.Var); ok && v.IsField() {
42 r.checkStructField(v)
43 } else if f, ok := from.(*types.Func); ok && recv(f) != nil {
44 r.checkMethod(f)
45 } else if isLocal(from) {
46 r.checkInLocalScope(from)
47 } else {
48 r.errorf(from.Pos(), "unexpected %s object %q (please report a bug)\n",
49 objectKind(from), from)
50 }
51 }
52
53 // checkInFileBlock performs safety checks for renames of objects in the file block,
54 // i.e. imported package names.
55 func (r *renamer) checkInFileBlock(from *types.PkgName) {
56 // Check import name is not "init".
57 if r.to == "init" {
58 r.errorf(from.Pos(), "%q is not a valid imported package name", r.to)
59 }
60
61 // Check for conflicts between file and package block.
62 if prev := from.Pkg().Scope().Lookup(r.to); prev != nil {
63 r.errorf(from.Pos(), "renaming this %s %q to %q would conflict",
64 objectKind(from), from.Name(), r.to)
65 r.errorf(prev.Pos(), "\twith this package member %s",
66 objectKind(prev))
67 return // since checkInPackageBlock would report redundant errors
68 }
69
70 // Check for conflicts in lexical scope.
71 r.checkInLexicalScope(from, r.packages[from.Pkg()])
72
73 // Finally, modify ImportSpec syntax to add or remove the Name as needed.
74 info, path, _ := r.iprog.PathEnclosingInterval(from.Pos(), from.Pos())
75 if from.Imported().Name() == r.to {
76 // ImportSpec.Name not needed
77 path[1].(*ast.ImportSpec).Name = nil
78 } else {
79 // ImportSpec.Name needed
80 if spec := path[1].(*ast.ImportSpec); spec.Name == nil {
81 spec.Name = &ast.Ident{NamePos: spec.Path.Pos(), Name: r.to}
82 info.Defs[spec.Name] = from
83 }
84 }
85 }
86
87 // checkInPackageBlock performs safety checks for renames of
88 // func/var/const/type objects in the package block.
89 func (r *renamer) checkInPackageBlock(from types.Object) {
90 // Check that there are no references to the name from another
91 // package if the renaming would make it unexported.
92 if ast.IsExported(from.Name()) && !ast.IsExported(r.to) {
93 for pkg, info := range r.packages {
94 if pkg == from.Pkg() {
95 continue
96 }
97 if id := someUse(info, from); id != nil &&
98 !r.checkExport(id, pkg, from) {
99 break
100 }
101 }
102 }
103
104 info := r.packages[from.Pkg()]
105
106 // Check that in the package block, "init" is a function, and never referenced.
107 if r.to == "init" {
108 kind := objectKind(from)
109 if kind == "func" {
110 // Reject if intra-package references to it exist.
111 for id, obj := range info.Uses {
112 if obj == from {
113 r.errorf(from.Pos(),
114 "renaming this func %q to %q would make it a package initializer",
115 from.Name(), r.to)
116 r.errorf(id.Pos(), "\tbut references to it exist")
117 break
118 }
119 }
120 } else {
121 r.errorf(from.Pos(), "you cannot have a %s at package level named %q",
122 kind, r.to)
123 }
124 }
125
126 // Check for conflicts between package block and all file blocks.
127 for _, f := range info.Files {
128 fileScope := info.Info.Scopes[f]
129 b, prev := fileScope.LookupParent(r.to, token.NoPos)
130 if b == fileScope {
131 r.errorf(from.Pos(), "renaming this %s %q to %q would conflict",
132 objectKind(from), from.Name(), r.to)
133 r.errorf(prev.Pos(), "\twith this %s",
134 objectKind(prev))
135 return // since checkInPackageBlock would report redundant errors
136 }
137 }
138
139 // Check for conflicts in lexical scope.
140 if from.Exported() {
141 for _, info := range r.packages {
142 r.checkInLexicalScope(from, info)
143 }
144 } else {
145 r.checkInLexicalScope(from, info)
146 }
147 }
148
149 func (r *renamer) checkInLocalScope(from types.Object) {
150 info := r.packages[from.Pkg()]
151
152 // Is this object an implicit local var for a type switch?
153 // Each case has its own var, whose position is the decl of y,
154 // but Ident in that decl does not appear in the Uses map.
155 //
156 // switch y := x.(type) { // Defs[Ident(y)] is undefined
157 // case int: print(y) // Implicits[CaseClause(int)] = Var(y_int)
158 // case string: print(y) // Implicits[CaseClause(string)] = Var(y_string)
159 // }
160 //
161 var isCaseVar bool
162 for syntax, obj := range info.Implicits {
163 if _, ok := syntax.(*ast.CaseClause); ok && obj.Pos() == from.Pos() {
164 isCaseVar = true
165 r.check(obj)
166 }
167 }
168
169 r.checkInLexicalScope(from, info)
170
171 // Finally, if this was a type switch, change the variable y.
172 if isCaseVar {
173 _, path, _ := r.iprog.PathEnclosingInterval(from.Pos(), from.Pos())
174 path[0].(*ast.Ident).Name = r.to // path is [Ident AssignStmt TypeSwitchStmt...]
175 }
176 }
177
178 // checkInLexicalScope performs safety checks that a renaming does not
179 // change the lexical reference structure of the specified package.
180 //
181 // For objects in lexical scope, there are three kinds of conflicts:
182 // same-, sub-, and super-block conflicts. We will illustrate all three
183 // using this example:
184 //
185 // var x int
186 // var z int
187 //
188 // func f(y int) {
189 // print(x)
190 // print(y)
191 // }
192 //
193 // Renaming x to z encounters a SAME-BLOCK CONFLICT, because an object
194 // with the new name already exists, defined in the same lexical block
195 // as the old object.
196 //
197 // Renaming x to y encounters a SUB-BLOCK CONFLICT, because there exists
198 // a reference to x from within (what would become) a hole in its scope.
199 // The definition of y in an (inner) sub-block would cast a shadow in
200 // the scope of the renamed variable.
201 //
202 // Renaming y to x encounters a SUPER-BLOCK CONFLICT. This is the
203 // converse situation: there is an existing definition of the new name
204 // (x) in an (enclosing) super-block, and the renaming would create a
205 // hole in its scope, within which there exist references to it. The
206 // new name casts a shadow in scope of the existing definition of x in
207 // the super-block.
208 //
209 // Removing the old name (and all references to it) is always safe, and
210 // requires no checks.
211 func (r *renamer) checkInLexicalScope(from types.Object, info *loader.PackageInfo) {
212 b := from.Parent() // the block defining the 'from' object
213 if b != nil {
214 toBlock, to := b.LookupParent(r.to, from.Parent().End())
215 if toBlock == b {
216 // same-block conflict
217 r.errorf(from.Pos(), "renaming this %s %q to %q",
218 objectKind(from), from.Name(), r.to)
219 r.errorf(to.Pos(), "\tconflicts with %s in same block",
220 objectKind(to))
221 return
222 } else if toBlock != nil {
223 // Check for super-block conflict.
224 // The name r.to is defined in a superblock.
225 // Is that name referenced from within this block?
226 forEachLexicalRef(info, to, func(id *ast.Ident, block *types.Scope) bool {
227 _, obj := lexicalLookup(block, from.Name(), id.Pos())
228 if obj == from {
229 // super-block conflict
230 r.errorf(from.Pos(), "renaming this %s %q to %q",
231 objectKind(from), from.Name(), r.to)
232 r.errorf(id.Pos(), "\twould shadow this reference")
233 r.errorf(to.Pos(), "\tto the %s declared here",
234 objectKind(to))
235 return false // stop
236 }
237 return true
238 })
239 }
240 }
241
242 // Check for sub-block conflict.
243 // Is there an intervening definition of r.to between
244 // the block defining 'from' and some reference to it?
245 forEachLexicalRef(info, from, func(id *ast.Ident, block *types.Scope) bool {
246 // Find the block that defines the found reference.
247 // It may be an ancestor.
248 fromBlock, _ := lexicalLookup(block, from.Name(), id.Pos())
249
250 // See what r.to would resolve to in the same scope.
251 toBlock, to := lexicalLookup(block, r.to, id.Pos())
252 if to != nil {
253 // sub-block conflict
254 if deeper(toBlock, fromBlock) {
255 r.errorf(from.Pos(), "renaming this %s %q to %q",
256 objectKind(from), from.Name(), r.to)
257 r.errorf(id.Pos(), "\twould cause this reference to become shadowed")
258 r.errorf(to.Pos(), "\tby this intervening %s definition",
259 objectKind(to))
260 return false // stop
261 }
262 }
263 return true
264 })
265
266 // Renaming a type that is used as an embedded field
267 // requires renaming the field too. e.g.
268 // type T int // if we rename this to U..
269 // var s struct {T}
270 // print(s.T) // ...this must change too
271 if _, ok := from.(*types.TypeName); ok {
272 for id, obj := range info.Uses {
273 if obj == from {
274 if field := info.Defs[id]; field != nil {
275 r.check(field)
276 }
277 }
278 }
279 }
280 }
281
282 // lexicalLookup is like (*types.Scope).LookupParent but respects the
283 // environment visible at pos. It assumes the relative position
284 // information is correct with each file.
285 func lexicalLookup(block *types.Scope, name string, pos token.Pos) (*types.Scope, types.Object) {
286 for b := block; b != nil; b = b.Parent() {
287 obj := b.Lookup(name)
288 // The scope of a package-level object is the entire package,
289 // so ignore pos in that case.
290 // No analogous clause is needed for file-level objects
291 // since no reference can appear before an import decl.
292 if obj != nil && (b == obj.Pkg().Scope() || obj.Pos() < pos) {
293 return b, obj
294 }
295 }
296 return nil, nil
297 }
298
299 // deeper reports whether block x is lexically deeper than y.
300 func deeper(x, y *types.Scope) bool {
301 if x == y || x == nil {
302 return false
303 } else if y == nil {
304 return true
305 } else {
306 return deeper(x.Parent(), y.Parent())
307 }
308 }
309
310 // forEachLexicalRef calls fn(id, block) for each identifier id in package
311 // info that is a reference to obj in lexical scope. block is the
312 // lexical block enclosing the reference. If fn returns false the
313 // iteration is terminated and findLexicalRefs returns false.
314 func forEachLexicalRef(info *loader.PackageInfo, obj types.Object, fn func(id *ast.Ident, block *types.Scope) bool) bool {
315 ok := true
316
317 var visit func(n ast.Node, stack []ast.Node) bool
318 visit = func(n ast.Node, stack []ast.Node) bool {
319 if !ok {
320 return false // bail out
321 }
322 switch n := n.(type) {
323 case *ast.Ident:
324 if info.Uses[n] == obj {
325 block := enclosingBlock(&info.Info, stack)
326 if !fn(n, block) {
327 ok = false
328 }
329 }
330 return false
331
332 case *ast.SelectorExpr:
333 // don't visit n.Sel
334 ast.PreorderStack(n.X, stack, visit)
335 return false // don't descend
336
337 case *ast.CompositeLit:
338 // Handle recursion ourselves for struct literals
339 // so we don't visit field identifiers.
340 tv := info.Types[n]
341 if is[*types.Struct](typeparams.CoreType(typeparams.Deref(tv.Type))) {
342 if n.Type != nil {
343 ast.PreorderStack(n.Type, stack, visit)
344 }
345 for _, elt := range n.Elts {
346 if kv, ok := elt.(*ast.KeyValueExpr); ok {
347 ast.PreorderStack(kv.Value, stack, visit)
348 } else {
349 ast.PreorderStack(elt, stack, visit)
350 }
351 }
352 return false // don't descend
353 }
354 }
355 return true
356 }
357
358 for _, f := range info.Files {
359 ast.PreorderStack(f, nil, visit)
360 if !ok {
361 break
362 }
363 }
364 return ok
365 }
366
367 // enclosingBlock returns the innermost block enclosing the specified
368 // AST node, specified in the form of a path from the root of the file,
369 // [file...n].
370 func enclosingBlock(info *types.Info, stack []ast.Node) *types.Scope {
371 for i := range stack {
372 n := stack[len(stack)-1-i]
373 // For some reason, go/types always associates a
374 // function's scope with its FuncType.
375 // TODO(adonovan): feature or a bug?
376 switch f := n.(type) {
377 case *ast.FuncDecl:
378 n = f.Type
379 case *ast.FuncLit:
380 n = f.Type
381 }
382 if b := info.Scopes[n]; b != nil {
383 return b
384 }
385 }
386 panic("no Scope for *ast.File")
387 }
388
389 func (r *renamer) checkLabel(label *types.Label) {
390 // Check there are no identical labels in the function's label block.
391 // (Label blocks don't nest, so this is easy.)
392 if prev := label.Parent().Lookup(r.to); prev != nil {
393 r.errorf(label.Pos(), "renaming this label %q to %q", label.Name(), prev.Name())
394 r.errorf(prev.Pos(), "\twould conflict with this one")
395 }
396 }
397
398 // checkStructField checks that the field renaming will not cause
399 // conflicts at its declaration, or ambiguity or changes to any selection.
400 func (r *renamer) checkStructField(from *types.Var) {
401 // Check that the struct declaration is free of field conflicts,
402 // and field/method conflicts.
403
404 // go/types offers no easy way to get from a field (or interface
405 // method) to its declaring struct (or interface), so we must
406 // ascend the AST.
407 info, path, _ := r.iprog.PathEnclosingInterval(from.Pos(), from.Pos())
408 // path matches this pattern:
409 // [Ident SelectorExpr? StarExpr? Field FieldList StructType ParenExpr* ... File]
410
411 // Ascend to FieldList.
412 var i int
413 for {
414 if _, ok := path[i].(*ast.FieldList); ok {
415 break
416 }
417 i++
418 }
419 i++
420 tStruct := path[i].(*ast.StructType)
421 i++
422 // Ascend past parens (unlikely).
423 for {
424 _, ok := path[i].(*ast.ParenExpr)
425 if !ok {
426 break
427 }
428 i++
429 }
430 if spec, ok := path[i].(*ast.TypeSpec); ok && !spec.Assign.IsValid() {
431 // This struct is also a defined type.
432 // We must check for direct (non-promoted) field/field
433 // and method/field conflicts.
434 named := info.Defs[spec.Name].Type()
435 prev, indices, _ := types.LookupFieldOrMethod(named, true, info.Pkg, r.to)
436 if len(indices) == 1 {
437 r.errorf(from.Pos(), "renaming this field %q to %q",
438 from.Name(), r.to)
439 r.errorf(prev.Pos(), "\twould conflict with this %s",
440 objectKind(prev))
441 return // skip checkSelections to avoid redundant errors
442 }
443 } else {
444 // This struct is not a defined type. (It may be an alias.)
445 // We need only check for direct (non-promoted) field/field conflicts.
446 T := info.Types[tStruct].Type.Underlying().(*types.Struct)
447 for field := range T.Fields() {
448 if prev := field; prev.Name() == r.to {
449 r.errorf(from.Pos(), "renaming this field %q to %q",
450 from.Name(), r.to)
451 r.errorf(prev.Pos(), "\twould conflict with this field")
452 return // skip checkSelections to avoid redundant errors
453 }
454 }
455 }
456
457 // Renaming an anonymous field requires renaming the TypeName too. e.g.
458 // print(s.T) // if we rename T to U,
459 // type T int // this and
460 // var s struct {T} // this must change too.
461 if from.Anonymous() {
462 // A TypeParam cannot appear as an anonymous field.
463 if t, ok := typesinternal.Unpointer(from.Type()).(hasTypeName); ok {
464 r.check(t.Obj())
465 }
466 }
467
468 // Check integrity of existing (field and method) selections.
469 r.checkSelections(from)
470 }
471
472 // hasTypeName abstracts the named types, *types.{Named,Alias,TypeParam}.
473 type hasTypeName interface{ Obj() *types.TypeName }
474
475 // checkSelections checks that all uses and selections that resolve to
476 // the specified object would continue to do so after the renaming.
477 func (r *renamer) checkSelections(from types.Object) {
478 for pkg, info := range r.packages {
479 if id := someUse(info, from); id != nil {
480 if !r.checkExport(id, pkg, from) {
481 return
482 }
483 }
484
485 for syntax, sel := range info.Selections {
486 // There may be extant selections of only the old
487 // name or only the new name, so we must check both.
488 // (If neither, the renaming is sound.)
489 //
490 // In both cases, we wish to compare the lengths
491 // of the implicit field path (Selection.Index)
492 // to see if the renaming would change it.
493 //
494 // If a selection that resolves to 'from', when renamed,
495 // would yield a path of the same or shorter length,
496 // this indicates ambiguity or a changed referent,
497 // analogous to same- or sub-block lexical conflict.
498 //
499 // If a selection using the name 'to' would
500 // yield a path of the same or shorter length,
501 // this indicates ambiguity or shadowing,
502 // analogous to same- or super-block lexical conflict.
503
504 // TODO(adonovan): fix: derive from Types[syntax.X].Mode
505 // TODO(adonovan): test with pointer, value, addressable value.
506 isAddressable := true
507
508 if sel.Obj() == from {
509 if obj, indices, _ := types.LookupFieldOrMethod(sel.Recv(), isAddressable, from.Pkg(), r.to); obj != nil {
510 // Renaming this existing selection of
511 // 'from' may block access to an existing
512 // type member named 'to'.
513 delta := len(indices) - len(sel.Index())
514 if delta > 0 {
515 continue // no ambiguity
516 }
517 r.selectionConflict(from, delta, syntax, obj)
518 return
519 }
520
521 } else if sel.Obj().Name() == r.to {
522 if obj, indices, _ := types.LookupFieldOrMethod(sel.Recv(), isAddressable, from.Pkg(), from.Name()); obj == from {
523 // Renaming 'from' may cause this existing
524 // selection of the name 'to' to change
525 // its meaning.
526 delta := len(indices) - len(sel.Index())
527 if delta > 0 {
528 continue // no ambiguity
529 }
530 r.selectionConflict(from, -delta, syntax, sel.Obj())
531 return
532 }
533 }
534 }
535 }
536 }
537
538 func (r *renamer) selectionConflict(from types.Object, delta int, syntax *ast.SelectorExpr, obj types.Object) {
539 r.errorf(from.Pos(), "renaming this %s %q to %q",
540 objectKind(from), from.Name(), r.to)
541
542 switch {
543 case delta < 0:
544 // analogous to sub-block conflict
545 r.errorf(syntax.Sel.Pos(),
546 "\twould change the referent of this selection")
547 r.errorf(obj.Pos(), "\tof this %s", objectKind(obj))
548 case delta == 0:
549 // analogous to same-block conflict
550 r.errorf(syntax.Sel.Pos(),
551 "\twould make this reference ambiguous")
552 r.errorf(obj.Pos(), "\twith this %s", objectKind(obj))
553 case delta > 0:
554 // analogous to super-block conflict
555 r.errorf(syntax.Sel.Pos(),
556 "\twould shadow this selection")
557 r.errorf(obj.Pos(), "\tof the %s declared here",
558 objectKind(obj))
559 }
560 }
561
562 // checkMethod performs safety checks for renaming a method.
563 // There are three hazards:
564 // - declaration conflicts
565 // - selection ambiguity/changes
566 // - entailed renamings of assignable concrete/interface types.
567 //
568 // We reject renamings initiated at concrete methods if it would
569 // change the assignability relation. For renamings of abstract
570 // methods, we rename all methods transitively coupled to it via
571 // assignability.
572 func (r *renamer) checkMethod(from *types.Func) {
573 // e.g. error.Error
574 if from.Pkg() == nil {
575 r.errorf(from.Pos(), "you cannot rename built-in method %s", from)
576 return
577 }
578
579 // ASSIGNABILITY: We reject renamings of concrete methods that
580 // would break a 'satisfy' constraint; but renamings of abstract
581 // methods are allowed to proceed, and we rename affected
582 // concrete and abstract methods as necessary. It is the
583 // initial method that determines the policy.
584
585 // Check for conflict at point of declaration.
586 // Check to ensure preservation of assignability requirements.
587 R := recv(from).Type()
588 if types.IsInterface(R) {
589 // Abstract method
590
591 // declaration
592 prev, _, _ := types.LookupFieldOrMethod(R, false, from.Pkg(), r.to)
593 if prev != nil {
594 r.errorf(from.Pos(), "renaming this interface method %q to %q",
595 from.Name(), r.to)
596 r.errorf(prev.Pos(), "\twould conflict with this method")
597 return
598 }
599
600 // Check all interfaces that embed this one for
601 // declaration conflicts too.
602 for _, info := range r.packages {
603 // Start with named interface types (better errors)
604 for _, obj := range info.Defs {
605 if obj, ok := obj.(*types.TypeName); ok && types.IsInterface(obj.Type()) {
606 f, _, _ := types.LookupFieldOrMethod(
607 obj.Type(), false, from.Pkg(), from.Name())
608 if f == nil {
609 continue
610 }
611 t, _, _ := types.LookupFieldOrMethod(
612 obj.Type(), false, from.Pkg(), r.to)
613 if t == nil {
614 continue
615 }
616 r.errorf(from.Pos(), "renaming this interface method %q to %q",
617 from.Name(), r.to)
618 r.errorf(t.Pos(), "\twould conflict with this method")
619 r.errorf(obj.Pos(), "\tin named interface type %q", obj.Name())
620 }
621 }
622
623 // Now look at all literal interface types (includes named ones again).
624 for e, tv := range info.Types {
625 if e, ok := e.(*ast.InterfaceType); ok {
626 _ = e
627 _ = tv.Type.(*types.Interface)
628 // TODO(adonovan): implement same check as above.
629 }
630 }
631 }
632
633 // assignability
634 //
635 // Find the set of concrete or abstract methods directly
636 // coupled to abstract method 'from' by some
637 // satisfy.Constraint, and rename them too.
638 for key := range r.satisfy() {
639 // key = (lhs, rhs) where lhs is always an interface.
640
641 lsel := r.msets.MethodSet(key.LHS).Lookup(from.Pkg(), from.Name())
642 if lsel == nil {
643 continue
644 }
645 rmethods := r.msets.MethodSet(key.RHS)
646 rsel := rmethods.Lookup(from.Pkg(), from.Name())
647 if rsel == nil {
648 continue
649 }
650
651 // If both sides have a method of this name,
652 // and one of them is m, the other must be coupled.
653 var coupled *types.Func
654 switch from {
655 case lsel.Obj():
656 coupled = rsel.Obj().(*types.Func)
657 case rsel.Obj():
658 coupled = lsel.Obj().(*types.Func)
659 default:
660 continue
661 }
662
663 // We must treat concrete-to-interface
664 // constraints like an implicit selection C.f of
665 // each interface method I.f, and check that the
666 // renaming leaves the selection unchanged and
667 // unambiguous.
668 //
669 // Fun fact: the implicit selection of C.f
670 // type I interface{f()}
671 // type C struct{I}
672 // func (C) g()
673 // var _ I = C{} // here
674 // yields abstract method I.f. This can make error
675 // messages less than obvious.
676 //
677 if !types.IsInterface(key.RHS) {
678 // The logic below was derived from checkSelections.
679
680 rtosel := rmethods.Lookup(from.Pkg(), r.to)
681 if rtosel != nil {
682 rto := rtosel.Obj().(*types.Func)
683 delta := len(rsel.Index()) - len(rtosel.Index())
684 if delta < 0 {
685 continue // no ambiguity
686 }
687
688 // TODO(adonovan): record the constraint's position.
689 keyPos := token.NoPos
690
691 r.errorf(from.Pos(), "renaming this method %q to %q",
692 from.Name(), r.to)
693 if delta == 0 {
694 // analogous to same-block conflict
695 r.errorf(keyPos, "\twould make the %s method of %s invoked via interface %s ambiguous",
696 r.to, key.RHS, key.LHS)
697 r.errorf(rto.Pos(), "\twith (%s).%s",
698 recv(rto).Type(), r.to)
699 } else {
700 // analogous to super-block conflict
701 r.errorf(keyPos, "\twould change the %s method of %s invoked via interface %s",
702 r.to, key.RHS, key.LHS)
703 r.errorf(coupled.Pos(), "\tfrom (%s).%s",
704 recv(coupled).Type(), r.to)
705 r.errorf(rto.Pos(), "\tto (%s).%s",
706 recv(rto).Type(), r.to)
707 }
708 return // one error is enough
709 }
710 }
711
712 if !r.changeMethods {
713 // This should be unreachable.
714 r.errorf(from.Pos(), "internal error: during renaming of abstract method %s", from)
715 r.errorf(coupled.Pos(), "\tchangedMethods=false, coupled method=%s", coupled)
716 r.errorf(from.Pos(), "\tPlease file a bug report")
717 return
718 }
719
720 // Rename the coupled method to preserve assignability.
721 r.check(coupled)
722 }
723 } else {
724 // Concrete method
725
726 // declaration
727 prev, indices, _ := types.LookupFieldOrMethod(R, true, from.Pkg(), r.to)
728 if prev != nil && len(indices) == 1 {
729 r.errorf(from.Pos(), "renaming this method %q to %q",
730 from.Name(), r.to)
731 r.errorf(prev.Pos(), "\twould conflict with this %s",
732 objectKind(prev))
733 return
734 }
735
736 // assignability
737 //
738 // Find the set of abstract methods coupled to concrete
739 // method 'from' by some satisfy.Constraint, and rename
740 // them too.
741 //
742 // Coupling may be indirect, e.g. I.f <-> C.f via type D.
743 //
744 // type I interface {f()}
745 // type C int
746 // type (C) f()
747 // type D struct{C}
748 // var _ I = D{}
749 //
750 for key := range r.satisfy() {
751 // key = (lhs, rhs) where lhs is always an interface.
752 if types.IsInterface(key.RHS) {
753 continue
754 }
755 rsel := r.msets.MethodSet(key.RHS).Lookup(from.Pkg(), from.Name())
756 if rsel == nil || rsel.Obj() != from {
757 continue // rhs does not have the method
758 }
759 lsel := r.msets.MethodSet(key.LHS).Lookup(from.Pkg(), from.Name())
760 if lsel == nil {
761 continue
762 }
763 imeth := lsel.Obj().(*types.Func)
764
765 // imeth is the abstract method (e.g. I.f)
766 // and key.RHS is the concrete coupling type (e.g. D).
767 if !r.changeMethods {
768 r.errorf(from.Pos(), "renaming this method %q to %q",
769 from.Name(), r.to)
770 var pos token.Pos
771 var iface string
772
773 I := recv(imeth).Type()
774 if named, ok := I.(hasTypeName); ok { // *Named or *Alias
775 pos = named.Obj().Pos()
776 iface = "interface " + named.Obj().Name()
777 } else {
778 pos = from.Pos()
779 iface = I.String()
780 }
781 r.errorf(pos, "\twould make %s no longer assignable to %s",
782 key.RHS, iface)
783 r.errorf(imeth.Pos(), "\t(rename %s.%s if you intend to change both types)",
784 I, from.Name())
785 return // one error is enough
786 }
787
788 // Rename the coupled interface method to preserve assignability.
789 r.check(imeth)
790 }
791 }
792
793 // Check integrity of existing (field and method) selections.
794 // We skip this if there were errors above, to avoid redundant errors.
795 r.checkSelections(from)
796 }
797
798 func (r *renamer) checkExport(id *ast.Ident, pkg *types.Package, from types.Object) bool {
799 // Reject cross-package references if r.to is unexported.
800 // (Such references may be qualified identifiers or field/method
801 // selections.)
802 if !ast.IsExported(r.to) && pkg != from.Pkg() {
803 r.errorf(from.Pos(),
804 "renaming this %s %q to %q would make it unexported",
805 objectKind(from), from.Name(), r.to)
806 r.errorf(id.Pos(), "\tbreaking references from packages such as %q",
807 pkg.Path())
808 return false
809 }
810 return true
811 }
812
813 // satisfy returns the set of interface satisfaction constraints.
814 func (r *renamer) satisfy() map[satisfy.Constraint]bool {
815 if r.satisfyConstraints == nil {
816 // Compute on demand: it's expensive.
817 var f satisfy.Finder
818 for _, info := range r.packages {
819 f.Find(&info.Info, info.Files)
820 }
821 r.satisfyConstraints = f.Result
822 }
823 return r.satisfyConstraints
824 }
825
826 // -- helpers ----------------------------------------------------------
827
828 // recv returns the method's receiver.
829 func recv(meth *types.Func) *types.Var {
830 return meth.Signature().Recv()
831 }
832
833 // someUse returns an arbitrary use of obj within info.
834 func someUse(info *loader.PackageInfo, obj types.Object) *ast.Ident {
835 for id, o := range info.Uses {
836 if o == obj {
837 return id
838 }
839 }
840 return nil
841 }