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