| 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 | import ( |
| 8 | "go/token" |
| 9 | "go/types" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "reflect" |
| 13 | "runtime" |
| 14 | "strings" |
| 15 | "unicode" |
| 16 | ) |
| 17 | |
| 18 | func objectKind(obj types.Object) string { |
| 19 | switch obj := obj.(type) { |
| 20 | case *types.PkgName: |
| 21 | return "imported package name" |
| 22 | case *types.TypeName: // defined type | alias | type parameter |
| 23 | return "type" |
| 24 | case *types.Var: |
| 25 | if obj.IsField() { |
| 26 | return "field" |
| 27 | } |
| 28 | case *types.Func: |
| 29 | if obj.Signature().Recv() != nil { |
| 30 | return "method" |
| 31 | } |
| 32 | } |
| 33 | // label, func, var, const |
| 34 | return strings.ToLower(strings.TrimPrefix(reflect.TypeOf(obj).String(), "*types.")) |
| 35 | } |
| 36 | |
| 37 | // NB: for renamings, blank is not considered valid. |
| 38 | func isValidIdentifier(id string) bool { |
| 39 | if id == "" || id == "_" { |
| 40 | return false |
| 41 | } |
| 42 | for i, r := range id { |
| 43 | if !isLetter(r) && (i == 0 || !isDigit(r)) { |
| 44 | return false |
| 45 | } |
| 46 | } |
| 47 | return token.Lookup(id) == token.IDENT |
| 48 | } |
| 49 | |
| 50 | // isLocal reports whether obj is local to some function. |
| 51 | // Precondition: not a struct field or interface method. |
| 52 | func isLocal(obj types.Object) bool { |
| 53 | // [... 5=stmt 4=func 3=file 2=pkg 1=universe] |
| 54 | var depth int |
| 55 | for scope := obj.Parent(); scope != nil; scope = scope.Parent() { |
| 56 | depth++ |
| 57 | } |
| 58 | return depth >= 4 |
| 59 | } |
| 60 | |
| 61 | // -- Plundered from go/scanner: --------------------------------------- |
| 62 | |
| 63 | func isLetter(ch rune) bool { |
| 64 | return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch) |
| 65 | } |
| 66 | |
| 67 | func isDigit(ch rune) bool { |
| 68 | return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) |
| 69 | } |
| 70 | |
| 71 | // -- Plundered from golang.org/x/tools/cmd/guru ----------------- |
| 72 | |
| 73 | // sameFile returns true if x and y have the same basename and denote |
| 74 | // the same file. |
| 75 | func sameFile(x, y string) bool { |
| 76 | if runtime.GOOS == "windows" { |
| 77 | x = filepath.ToSlash(x) |
| 78 | y = filepath.ToSlash(y) |
| 79 | } |
| 80 | if x == y { |
| 81 | return true |
| 82 | } |
| 83 | if filepath.Base(x) == filepath.Base(y) { // (optimisation) |
| 84 | if xi, err := os.Stat(x); err == nil { |
| 85 | if yi, err := os.Stat(y); err == nil { |
| 86 | return os.SameFile(xi, yi) |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | return false |
| 91 | } |
| 92 | |
| 93 | func is[T any](x any) bool { |
| 94 | _, ok := x.(T) |
| 95 | return ok |
| 96 | } |