github.com/april1989/origin-go-tools@v0.0.32/internal/lsp/source/rename_check.go (about)

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