golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/refactor/rename/check.go (about)

     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 ...interface{}) {
    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 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  	var stack []ast.Node
   317  
   318  	var visit func(n ast.Node) bool
   319  	visit = func(n ast.Node) bool {
   320  		if n == nil {
   321  			stack = stack[:len(stack)-1] // pop
   322  			return false
   323  		}
   324  		if !ok {
   325  			return false // bail out
   326  		}
   327  
   328  		stack = append(stack, n) // push
   329  		switch n := n.(type) {
   330  		case *ast.Ident:
   331  			if info.Uses[n] == obj {
   332  				block := enclosingBlock(&info.Info, stack)
   333  				if !fn(n, block) {
   334  					ok = false
   335  				}
   336  			}
   337  			return visit(nil) // pop stack
   338  
   339  		case *ast.SelectorExpr:
   340  			// don't visit n.Sel
   341  			ast.Inspect(n.X, visit)
   342  			return visit(nil) // pop stack, don't descend
   343  
   344  		case *ast.CompositeLit:
   345  			// Handle recursion ourselves for struct literals
   346  			// so we don't visit field identifiers.
   347  			tv := info.Types[n]
   348  			if is[*types.Struct](typeparams.CoreType(typeparams.Deref(tv.Type))) {
   349  				if n.Type != nil {
   350  					ast.Inspect(n.Type, visit)
   351  				}
   352  				for _, elt := range n.Elts {
   353  					if kv, ok := elt.(*ast.KeyValueExpr); ok {
   354  						ast.Inspect(kv.Value, visit)
   355  					} else {
   356  						ast.Inspect(elt, visit)
   357  					}
   358  				}
   359  				return visit(nil) // pop stack, don't descend
   360  			}
   361  		}
   362  		return true
   363  	}
   364  
   365  	for _, f := range info.Files {
   366  		ast.Inspect(f, visit)
   367  		if len(stack) != 0 {
   368  			panic(stack)
   369  		}
   370  		if !ok {
   371  			break
   372  		}
   373  	}
   374  	return ok
   375  }
   376  
   377  // enclosingBlock returns the innermost block enclosing the specified
   378  // AST node, specified in the form of a path from the root of the file,
   379  // [file...n].
   380  func enclosingBlock(info *types.Info, stack []ast.Node) *types.Scope {
   381  	for i := range stack {
   382  		n := stack[len(stack)-1-i]
   383  		// For some reason, go/types always associates a
   384  		// function's scope with its FuncType.
   385  		// TODO(adonovan): feature or a bug?
   386  		switch f := n.(type) {
   387  		case *ast.FuncDecl:
   388  			n = f.Type
   389  		case *ast.FuncLit:
   390  			n = f.Type
   391  		}
   392  		if b := info.Scopes[n]; b != nil {
   393  			return b
   394  		}
   395  	}
   396  	panic("no Scope for *ast.File")
   397  }
   398  
   399  func (r *renamer) checkLabel(label *types.Label) {
   400  	// Check there are no identical labels in the function's label block.
   401  	// (Label blocks don't nest, so this is easy.)
   402  	if prev := label.Parent().Lookup(r.to); prev != nil {
   403  		r.errorf(label.Pos(), "renaming this label %q to %q", label.Name(), prev.Name())
   404  		r.errorf(prev.Pos(), "\twould conflict with this one")
   405  	}
   406  }
   407  
   408  // checkStructField checks that the field renaming will not cause
   409  // conflicts at its declaration, or ambiguity or changes to any selection.
   410  func (r *renamer) checkStructField(from *types.Var) {
   411  	// Check that the struct declaration is free of field conflicts,
   412  	// and field/method conflicts.
   413  
   414  	// go/types offers no easy way to get from a field (or interface
   415  	// method) to its declaring struct (or interface), so we must
   416  	// ascend the AST.
   417  	info, path, _ := r.iprog.PathEnclosingInterval(from.Pos(), from.Pos())
   418  	// path matches this pattern:
   419  	// [Ident SelectorExpr? StarExpr? Field FieldList StructType ParenExpr* ... File]
   420  
   421  	// Ascend to FieldList.
   422  	var i int
   423  	for {
   424  		if _, ok := path[i].(*ast.FieldList); ok {
   425  			break
   426  		}
   427  		i++
   428  	}
   429  	i++
   430  	tStruct := path[i].(*ast.StructType)
   431  	i++
   432  	// Ascend past parens (unlikely).
   433  	for {
   434  		_, ok := path[i].(*ast.ParenExpr)
   435  		if !ok {
   436  			break
   437  		}
   438  		i++
   439  	}
   440  	if spec, ok := path[i].(*ast.TypeSpec); ok && !spec.Assign.IsValid() {
   441  		// This struct is also a defined type.
   442  		// We must check for direct (non-promoted) field/field
   443  		// and method/field conflicts.
   444  		named := info.Defs[spec.Name].Type()
   445  		prev, indices, _ := types.LookupFieldOrMethod(named, true, info.Pkg, r.to)
   446  		if len(indices) == 1 {
   447  			r.errorf(from.Pos(), "renaming this field %q to %q",
   448  				from.Name(), r.to)
   449  			r.errorf(prev.Pos(), "\twould conflict with this %s",
   450  				objectKind(prev))
   451  			return // skip checkSelections to avoid redundant errors
   452  		}
   453  	} else {
   454  		// This struct is not a defined type. (It may be an alias.)
   455  		// We need only check for direct (non-promoted) field/field conflicts.
   456  		T := info.Types[tStruct].Type.Underlying().(*types.Struct)
   457  		for i := 0; i < T.NumFields(); i++ {
   458  			if prev := T.Field(i); prev.Name() == r.to {
   459  				r.errorf(from.Pos(), "renaming this field %q to %q",
   460  					from.Name(), r.to)
   461  				r.errorf(prev.Pos(), "\twould conflict with this field")
   462  				return // skip checkSelections to avoid redundant errors
   463  			}
   464  		}
   465  	}
   466  
   467  	// Renaming an anonymous field requires renaming the TypeName too. e.g.
   468  	// 	print(s.T)       // if we rename T to U,
   469  	// 	type T int       // this and
   470  	// 	var s struct {T} // this must change too.
   471  	if from.Anonymous() {
   472  		// A TypeParam cannot appear as an anonymous field.
   473  		if t, ok := typesinternal.Unpointer(from.Type()).(hasTypeName); ok {
   474  			r.check(t.Obj())
   475  		}
   476  	}
   477  
   478  	// Check integrity of existing (field and method) selections.
   479  	r.checkSelections(from)
   480  }
   481  
   482  // hasTypeName abstracts the named types, *types.{Named,Alias,TypeParam}.
   483  type hasTypeName interface{ Obj() *types.TypeName }
   484  
   485  // checkSelections checks that all uses and selections that resolve to
   486  // the specified object would continue to do so after the renaming.
   487  func (r *renamer) checkSelections(from types.Object) {
   488  	for pkg, info := range r.packages {
   489  		if id := someUse(info, from); id != nil {
   490  			if !r.checkExport(id, pkg, from) {
   491  				return
   492  			}
   493  		}
   494  
   495  		for syntax, sel := range info.Selections {
   496  			// There may be extant selections of only the old
   497  			// name or only the new name, so we must check both.
   498  			// (If neither, the renaming is sound.)
   499  			//
   500  			// In both cases, we wish to compare the lengths
   501  			// of the implicit field path (Selection.Index)
   502  			// to see if the renaming would change it.
   503  			//
   504  			// If a selection that resolves to 'from', when renamed,
   505  			// would yield a path of the same or shorter length,
   506  			// this indicates ambiguity or a changed referent,
   507  			// analogous to same- or sub-block lexical conflict.
   508  			//
   509  			// If a selection using the name 'to' would
   510  			// yield a path of the same or shorter length,
   511  			// this indicates ambiguity or shadowing,
   512  			// analogous to same- or super-block lexical conflict.
   513  
   514  			// TODO(adonovan): fix: derive from Types[syntax.X].Mode
   515  			// TODO(adonovan): test with pointer, value, addressable value.
   516  			isAddressable := true
   517  
   518  			if sel.Obj() == from {
   519  				if obj, indices, _ := types.LookupFieldOrMethod(sel.Recv(), isAddressable, from.Pkg(), r.to); obj != nil {
   520  					// Renaming this existing selection of
   521  					// 'from' may block access to an existing
   522  					// type member named 'to'.
   523  					delta := len(indices) - len(sel.Index())
   524  					if delta > 0 {
   525  						continue // no ambiguity
   526  					}
   527  					r.selectionConflict(from, delta, syntax, obj)
   528  					return
   529  				}
   530  
   531  			} else if sel.Obj().Name() == r.to {
   532  				if obj, indices, _ := types.LookupFieldOrMethod(sel.Recv(), isAddressable, from.Pkg(), from.Name()); obj == from {
   533  					// Renaming 'from' may cause this existing
   534  					// selection of the name 'to' to change
   535  					// its meaning.
   536  					delta := len(indices) - len(sel.Index())
   537  					if delta > 0 {
   538  						continue //  no ambiguity
   539  					}
   540  					r.selectionConflict(from, -delta, syntax, sel.Obj())
   541  					return
   542  				}
   543  			}
   544  		}
   545  	}
   546  }
   547  
   548  func (r *renamer) selectionConflict(from types.Object, delta int, syntax *ast.SelectorExpr, obj types.Object) {
   549  	r.errorf(from.Pos(), "renaming this %s %q to %q",
   550  		objectKind(from), from.Name(), r.to)
   551  
   552  	switch {
   553  	case delta < 0:
   554  		// analogous to sub-block conflict
   555  		r.errorf(syntax.Sel.Pos(),
   556  			"\twould change the referent of this selection")
   557  		r.errorf(obj.Pos(), "\tof this %s", objectKind(obj))
   558  	case delta == 0:
   559  		// analogous to same-block conflict
   560  		r.errorf(syntax.Sel.Pos(),
   561  			"\twould make this reference ambiguous")
   562  		r.errorf(obj.Pos(), "\twith this %s", objectKind(obj))
   563  	case delta > 0:
   564  		// analogous to super-block conflict
   565  		r.errorf(syntax.Sel.Pos(),
   566  			"\twould shadow this selection")
   567  		r.errorf(obj.Pos(), "\tof the %s declared here",
   568  			objectKind(obj))
   569  	}
   570  }
   571  
   572  // checkMethod performs safety checks for renaming a method.
   573  // There are three hazards:
   574  //   - declaration conflicts
   575  //   - selection ambiguity/changes
   576  //   - entailed renamings of assignable concrete/interface types.
   577  //
   578  // We reject renamings initiated at concrete methods if it would
   579  // change the assignability relation.  For renamings of abstract
   580  // methods, we rename all methods transitively coupled to it via
   581  // assignability.
   582  func (r *renamer) checkMethod(from *types.Func) {
   583  	// e.g. error.Error
   584  	if from.Pkg() == nil {
   585  		r.errorf(from.Pos(), "you cannot rename built-in method %s", from)
   586  		return
   587  	}
   588  
   589  	// ASSIGNABILITY: We reject renamings of concrete methods that
   590  	// would break a 'satisfy' constraint; but renamings of abstract
   591  	// methods are allowed to proceed, and we rename affected
   592  	// concrete and abstract methods as necessary.  It is the
   593  	// initial method that determines the policy.
   594  
   595  	// Check for conflict at point of declaration.
   596  	// Check to ensure preservation of assignability requirements.
   597  	R := recv(from).Type()
   598  	if types.IsInterface(R) {
   599  		// Abstract method
   600  
   601  		// declaration
   602  		prev, _, _ := types.LookupFieldOrMethod(R, false, from.Pkg(), r.to)
   603  		if prev != nil {
   604  			r.errorf(from.Pos(), "renaming this interface method %q to %q",
   605  				from.Name(), r.to)
   606  			r.errorf(prev.Pos(), "\twould conflict with this method")
   607  			return
   608  		}
   609  
   610  		// Check all interfaces that embed this one for
   611  		// declaration conflicts too.
   612  		for _, info := range r.packages {
   613  			// Start with named interface types (better errors)
   614  			for _, obj := range info.Defs {
   615  				if obj, ok := obj.(*types.TypeName); ok && types.IsInterface(obj.Type()) {
   616  					f, _, _ := types.LookupFieldOrMethod(
   617  						obj.Type(), false, from.Pkg(), from.Name())
   618  					if f == nil {
   619  						continue
   620  					}
   621  					t, _, _ := types.LookupFieldOrMethod(
   622  						obj.Type(), false, from.Pkg(), r.to)
   623  					if t == nil {
   624  						continue
   625  					}
   626  					r.errorf(from.Pos(), "renaming this interface method %q to %q",
   627  						from.Name(), r.to)
   628  					r.errorf(t.Pos(), "\twould conflict with this method")
   629  					r.errorf(obj.Pos(), "\tin named interface type %q", obj.Name())
   630  				}
   631  			}
   632  
   633  			// Now look at all literal interface types (includes named ones again).
   634  			for e, tv := range info.Types {
   635  				if e, ok := e.(*ast.InterfaceType); ok {
   636  					_ = e
   637  					_ = tv.Type.(*types.Interface)
   638  					// TODO(adonovan): implement same check as above.
   639  				}
   640  			}
   641  		}
   642  
   643  		// assignability
   644  		//
   645  		// Find the set of concrete or abstract methods directly
   646  		// coupled to abstract method 'from' by some
   647  		// satisfy.Constraint, and rename them too.
   648  		for key := range r.satisfy() {
   649  			// key = (lhs, rhs) where lhs is always an interface.
   650  
   651  			lsel := r.msets.MethodSet(key.LHS).Lookup(from.Pkg(), from.Name())
   652  			if lsel == nil {
   653  				continue
   654  			}
   655  			rmethods := r.msets.MethodSet(key.RHS)
   656  			rsel := rmethods.Lookup(from.Pkg(), from.Name())
   657  			if rsel == nil {
   658  				continue
   659  			}
   660  
   661  			// If both sides have a method of this name,
   662  			// and one of them is m, the other must be coupled.
   663  			var coupled *types.Func
   664  			switch from {
   665  			case lsel.Obj():
   666  				coupled = rsel.Obj().(*types.Func)
   667  			case rsel.Obj():
   668  				coupled = lsel.Obj().(*types.Func)
   669  			default:
   670  				continue
   671  			}
   672  
   673  			// We must treat concrete-to-interface
   674  			// constraints like an implicit selection C.f of
   675  			// each interface method I.f, and check that the
   676  			// renaming leaves the selection unchanged and
   677  			// unambiguous.
   678  			//
   679  			// Fun fact: the implicit selection of C.f
   680  			// 	type I interface{f()}
   681  			// 	type C struct{I}
   682  			// 	func (C) g()
   683  			//      var _ I = C{} // here
   684  			// yields abstract method I.f.  This can make error
   685  			// messages less than obvious.
   686  			//
   687  			if !types.IsInterface(key.RHS) {
   688  				// The logic below was derived from checkSelections.
   689  
   690  				rtosel := rmethods.Lookup(from.Pkg(), r.to)
   691  				if rtosel != nil {
   692  					rto := rtosel.Obj().(*types.Func)
   693  					delta := len(rsel.Index()) - len(rtosel.Index())
   694  					if delta < 0 {
   695  						continue // no ambiguity
   696  					}
   697  
   698  					// TODO(adonovan): record the constraint's position.
   699  					keyPos := token.NoPos
   700  
   701  					r.errorf(from.Pos(), "renaming this method %q to %q",
   702  						from.Name(), r.to)
   703  					if delta == 0 {
   704  						// analogous to same-block conflict
   705  						r.errorf(keyPos, "\twould make the %s method of %s invoked via interface %s ambiguous",
   706  							r.to, key.RHS, key.LHS)
   707  						r.errorf(rto.Pos(), "\twith (%s).%s",
   708  							recv(rto).Type(), r.to)
   709  					} else {
   710  						// analogous to super-block conflict
   711  						r.errorf(keyPos, "\twould change the %s method of %s invoked via interface %s",
   712  							r.to, key.RHS, key.LHS)
   713  						r.errorf(coupled.Pos(), "\tfrom (%s).%s",
   714  							recv(coupled).Type(), r.to)
   715  						r.errorf(rto.Pos(), "\tto (%s).%s",
   716  							recv(rto).Type(), r.to)
   717  					}
   718  					return // one error is enough
   719  				}
   720  			}
   721  
   722  			if !r.changeMethods {
   723  				// This should be unreachable.
   724  				r.errorf(from.Pos(), "internal error: during renaming of abstract method %s", from)
   725  				r.errorf(coupled.Pos(), "\tchangedMethods=false, coupled method=%s", coupled)
   726  				r.errorf(from.Pos(), "\tPlease file a bug report")
   727  				return
   728  			}
   729  
   730  			// Rename the coupled method to preserve assignability.
   731  			r.check(coupled)
   732  		}
   733  	} else {
   734  		// Concrete method
   735  
   736  		// declaration
   737  		prev, indices, _ := types.LookupFieldOrMethod(R, true, from.Pkg(), r.to)
   738  		if prev != nil && len(indices) == 1 {
   739  			r.errorf(from.Pos(), "renaming this method %q to %q",
   740  				from.Name(), r.to)
   741  			r.errorf(prev.Pos(), "\twould conflict with this %s",
   742  				objectKind(prev))
   743  			return
   744  		}
   745  
   746  		// assignability
   747  		//
   748  		// Find the set of abstract methods coupled to concrete
   749  		// method 'from' by some satisfy.Constraint, and rename
   750  		// them too.
   751  		//
   752  		// Coupling may be indirect, e.g. I.f <-> C.f via type D.
   753  		//
   754  		// 	type I interface {f()}
   755  		//	type C int
   756  		//	type (C) f()
   757  		//	type D struct{C}
   758  		//	var _ I = D{}
   759  		//
   760  		for key := range r.satisfy() {
   761  			// key = (lhs, rhs) where lhs is always an interface.
   762  			if types.IsInterface(key.RHS) {
   763  				continue
   764  			}
   765  			rsel := r.msets.MethodSet(key.RHS).Lookup(from.Pkg(), from.Name())
   766  			if rsel == nil || rsel.Obj() != from {
   767  				continue // rhs does not have the method
   768  			}
   769  			lsel := r.msets.MethodSet(key.LHS).Lookup(from.Pkg(), from.Name())
   770  			if lsel == nil {
   771  				continue
   772  			}
   773  			imeth := lsel.Obj().(*types.Func)
   774  
   775  			// imeth is the abstract method (e.g. I.f)
   776  			// and key.RHS is the concrete coupling type (e.g. D).
   777  			if !r.changeMethods {
   778  				r.errorf(from.Pos(), "renaming this method %q to %q",
   779  					from.Name(), r.to)
   780  				var pos token.Pos
   781  				var iface string
   782  
   783  				I := recv(imeth).Type()
   784  				if named, ok := I.(hasTypeName); ok {
   785  					pos = named.Obj().Pos()
   786  					iface = "interface " + named.Obj().Name()
   787  				} else {
   788  					pos = from.Pos()
   789  					iface = I.String()
   790  				}
   791  				r.errorf(pos, "\twould make %s no longer assignable to %s",
   792  					key.RHS, iface)
   793  				r.errorf(imeth.Pos(), "\t(rename %s.%s if you intend to change both types)",
   794  					I, from.Name())
   795  				return // one error is enough
   796  			}
   797  
   798  			// Rename the coupled interface method to preserve assignability.
   799  			r.check(imeth)
   800  		}
   801  	}
   802  
   803  	// Check integrity of existing (field and method) selections.
   804  	// We skip this if there were errors above, to avoid redundant errors.
   805  	r.checkSelections(from)
   806  }
   807  
   808  func (r *renamer) checkExport(id *ast.Ident, pkg *types.Package, from types.Object) bool {
   809  	// Reject cross-package references if r.to is unexported.
   810  	// (Such references may be qualified identifiers or field/method
   811  	// selections.)
   812  	if !ast.IsExported(r.to) && pkg != from.Pkg() {
   813  		r.errorf(from.Pos(),
   814  			"renaming this %s %q to %q would make it unexported",
   815  			objectKind(from), from.Name(), r.to)
   816  		r.errorf(id.Pos(), "\tbreaking references from packages such as %q",
   817  			pkg.Path())
   818  		return false
   819  	}
   820  	return true
   821  }
   822  
   823  // satisfy returns the set of interface satisfaction constraints.
   824  func (r *renamer) satisfy() map[satisfy.Constraint]bool {
   825  	if r.satisfyConstraints == nil {
   826  		// Compute on demand: it's expensive.
   827  		var f satisfy.Finder
   828  		for _, info := range r.packages {
   829  			f.Find(&info.Info, info.Files)
   830  		}
   831  		r.satisfyConstraints = f.Result
   832  	}
   833  	return r.satisfyConstraints
   834  }
   835  
   836  // -- helpers ----------------------------------------------------------
   837  
   838  // recv returns the method's receiver.
   839  func recv(meth *types.Func) *types.Var {
   840  	return meth.Type().(*types.Signature).Recv()
   841  }
   842  
   843  // someUse returns an arbitrary use of obj within info.
   844  func someUse(info *loader.PackageInfo, obj types.Object) *ast.Ident {
   845  	for id, o := range info.Uses {
   846  		if o == obj {
   847  			return id
   848  		}
   849  	}
   850  	return nil
   851  }