| 1 | // Copyright 2020 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 typesinternal provides helpful operators for dealing with |
| 6 | // go/types: |
| 7 | // |
| 8 | // - operators for querying typed syntax trees (e.g. [Imports], [IsFunctionNamed]); |
| 9 | // - functions for converting types to strings or syntax (e.g. [TypeExpr], FileQualifier]); |
| 10 | // - helpers for working with the [go/types] API (e.g. [NewTypesInfo]); |
| 11 | // - access to internal go/types APIs that are not yet |
| 12 | // exported (e.g. [SetUsesCgo], [ErrorCodeStartEnd], [VarKind]); and |
| 13 | // - common algorithms related to types (e.g. [TooNewStdSymbols]). |
| 14 | // |
| 15 | // See also: |
| 16 | // - [golang.org/x/tools/internal/astutil], for operations on untyped syntax; |
| 17 | // - [golang.org/x/tools/internal/analysisinernal], for helpers for analyzers; |
| 18 | // - [golang.org/x/tools/internal/refactor], for operators to compute text edits. |
| 19 | package typesinternal |
| 20 | |
| 21 | import ( |
| 22 | "go/ast" |
| 23 | "go/token" |
| 24 | "go/types" |
| 25 | "reflect" |
| 26 | |
| 27 | "golang.org/x/tools/go/ast/inspector" |
| 28 | ) |
| 29 | |
| 30 | func SetUsesCgo(conf *types.Config) bool { |
| 31 | v := reflect.ValueOf(conf).Elem() |
| 32 | |
| 33 | f := v.FieldByName("go115UsesCgo") |
| 34 | if !f.IsValid() { |
| 35 | f = v.FieldByName("UsesCgo") |
| 36 | if !f.IsValid() { |
| 37 | return false |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | *(*bool)(f.Addr().UnsafePointer()) = true |
| 42 | |
| 43 | return true |
| 44 | } |
| 45 | |
| 46 | // ErrorCodeStartEnd extracts additional information from types.Error values |
| 47 | // generated by Go version 1.16 and later: the error code, start position, and |
| 48 | // end position. If all positions are valid, start <= err.Pos <= end. |
| 49 | // |
| 50 | // If the data could not be read, the final result parameter will be false. |
| 51 | // |
| 52 | // TODO(adonovan): eliminate start/end when proposal #71803 is accepted. |
| 53 | func ErrorCodeStartEnd(err types.Error) (code ErrorCode, start, end token.Pos, ok bool) { |
| 54 | var data [3]int |
| 55 | // By coincidence all of these fields are ints, which simplifies things. |
| 56 | v := reflect.ValueOf(err) |
| 57 | for i, name := range []string{"go116code", "go116start", "go116end"} { |
| 58 | f := v.FieldByName(name) |
| 59 | if !f.IsValid() { |
| 60 | return 0, 0, 0, false |
| 61 | } |
| 62 | data[i] = int(f.Int()) |
| 63 | } |
| 64 | return ErrorCode(data[0]), token.Pos(data[1]), token.Pos(data[2]), true |
| 65 | } |
| 66 | |
| 67 | // NameRelativeTo returns a types.Qualifier that qualifies members of |
| 68 | // all packages other than pkg, using only the package name. |
| 69 | // (By contrast, [types.RelativeTo] uses the complete package path, |
| 70 | // which is often excessive.) |
| 71 | // |
| 72 | // If pkg is nil, it is equivalent to [*types.Package.Name]. |
| 73 | // |
| 74 | // TODO(adonovan): all uses of this with TypeString should be |
| 75 | // eliminated when https://go.dev/issues/75604 is resolved. |
| 76 | func NameRelativeTo(pkg *types.Package) types.Qualifier { |
| 77 | return func(other *types.Package) string { |
| 78 | if pkg != nil && pkg == other { |
| 79 | return "" // same package; unqualified |
| 80 | } |
| 81 | return other.Name() |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | // TypeNameFor returns the type name symbol for the specified type, if |
| 86 | // it is a [*types.Alias], [*types.Named], [*types.TypeParam], or a |
| 87 | // [*types.Basic] representing a type. |
| 88 | // |
| 89 | // For all other types, and for Basic types representing a builtin, |
| 90 | // constant, or nil, it returns nil. Be careful not to convert the |
| 91 | // resulting nil pointer to a [types.Object]! |
| 92 | // |
| 93 | // If t is the type of a constant, it may be an "untyped" type, which |
| 94 | // has no TypeName. To access the name of such types (e.g. "untyped |
| 95 | // int"), use [types.Basic.Name]. |
| 96 | func TypeNameFor(t types.Type) *types.TypeName { |
| 97 | switch t := t.(type) { |
| 98 | case *types.Alias: |
| 99 | return t.Obj() |
| 100 | case *types.Named: |
| 101 | return t.Obj() |
| 102 | case *types.TypeParam: |
| 103 | return t.Obj() |
| 104 | case *types.Basic: |
| 105 | // See issues #71886 and #66890 for some history. |
| 106 | if tname, ok := types.Universe.Lookup(t.Name()).(*types.TypeName); ok { |
| 107 | return tname |
| 108 | } |
| 109 | } |
| 110 | return nil |
| 111 | } |
| 112 | |
| 113 | // A NamedOrAlias is a [types.Type] that is named (as |
| 114 | // defined by the spec) and capable of bearing type parameters: it |
| 115 | // abstracts aliases ([types.Alias]) and defined types |
| 116 | // ([types.Named]). |
| 117 | // |
| 118 | // Every type declared by an explicit "type" declaration is a |
| 119 | // NamedOrAlias. (Built-in type symbols may additionally |
| 120 | // have type [types.Basic], which is not a NamedOrAlias, |
| 121 | // though the spec regards them as "named"; see [TypeNameFor].) |
| 122 | // |
| 123 | // NamedOrAlias cannot expose the Origin method, because |
| 124 | // [types.Alias.Origin] and [types.Named.Origin] have different |
| 125 | // (covariant) result types; use [Origin] instead. |
| 126 | type NamedOrAlias interface { |
| 127 | types.Type |
| 128 | Obj() *types.TypeName |
| 129 | TypeArgs() *types.TypeList |
| 130 | TypeParams() *types.TypeParamList |
| 131 | SetTypeParams(tparams []*types.TypeParam) |
| 132 | } |
| 133 | |
| 134 | var ( |
| 135 | _ NamedOrAlias = (*types.Alias)(nil) |
| 136 | _ NamedOrAlias = (*types.Named)(nil) |
| 137 | ) |
| 138 | |
| 139 | // Origin returns the generic type of the Named or Alias type t if it |
| 140 | // is instantiated, otherwise it returns t. |
| 141 | func Origin(t NamedOrAlias) NamedOrAlias { |
| 142 | switch t := t.(type) { |
| 143 | case *types.Alias: |
| 144 | return t.Origin() |
| 145 | case *types.Named: |
| 146 | return t.Origin() |
| 147 | } |
| 148 | return t |
| 149 | } |
| 150 | |
| 151 | // IsPackageLevel reports whether obj is a package-level symbol. |
| 152 | func IsPackageLevel(obj types.Object) bool { |
| 153 | return obj.Pkg() != nil && obj.Parent() == obj.Pkg().Scope() |
| 154 | } |
| 155 | |
| 156 | // NewTypesInfo returns a *types.Info with all maps populated. |
| 157 | func NewTypesInfo() *types.Info { |
| 158 | return &types.Info{ |
| 159 | Types: map[ast.Expr]types.TypeAndValue{}, |
| 160 | Instances: map[*ast.Ident]types.Instance{}, |
| 161 | Defs: map[*ast.Ident]types.Object{}, |
| 162 | Uses: map[*ast.Ident]types.Object{}, |
| 163 | Implicits: map[ast.Node]types.Object{}, |
| 164 | Selections: map[*ast.SelectorExpr]*types.Selection{}, |
| 165 | Scopes: map[ast.Node]*types.Scope{}, |
| 166 | FileVersions: map[*ast.File]string{}, |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // EnclosingScope returns the innermost block logically enclosing the cursor. |
| 171 | func EnclosingScope(info *types.Info, cur inspector.Cursor) *types.Scope { |
| 172 | for cur := range cur.Enclosing() { |
| 173 | n := cur.Node() |
| 174 | // A function's Scope is associated with its FuncType. |
| 175 | switch f := n.(type) { |
| 176 | case *ast.FuncDecl: |
| 177 | n = f.Type |
| 178 | case *ast.FuncLit: |
| 179 | n = f.Type |
| 180 | } |
| 181 | if b := info.Scopes[n]; b != nil { |
| 182 | return b |
| 183 | } |
| 184 | } |
| 185 | panic("no Scope for *ast.File") |
| 186 | } |
| 187 | |
| 188 | // Imports reports whether path is imported by pkg. |
| 189 | func Imports(pkg *types.Package, path string) bool { |
| 190 | for _, imp := range pkg.Imports() { |
| 191 | if imp.Path() == path { |
| 192 | return true |
| 193 | } |
| 194 | } |
| 195 | return false |
| 196 | } |
| 197 | |
| 198 | // ObjectKind returns a description of the object's kind. |
| 199 | // |
| 200 | // from objectKind in go/types |
| 201 | func ObjectKind(obj types.Object) string { |
| 202 | switch obj := obj.(type) { |
| 203 | case *types.PkgName: |
| 204 | return "package name" |
| 205 | case *types.Const: |
| 206 | return "constant" |
| 207 | case *types.TypeName: |
| 208 | if obj.IsAlias() { |
| 209 | return "type alias" |
| 210 | } else if _, ok := obj.Type().(*types.TypeParam); ok { |
| 211 | return "type parameter" |
| 212 | } else { |
| 213 | return "defined type" |
| 214 | } |
| 215 | case *types.Var: |
| 216 | switch obj.Kind() { |
| 217 | case PackageVar: |
| 218 | return "package-level variable" |
| 219 | case LocalVar: |
| 220 | return "local variable" |
| 221 | case RecvVar: |
| 222 | return "receiver" |
| 223 | case ParamVar: |
| 224 | return "parameter" |
| 225 | case ResultVar: |
| 226 | return "result variable" |
| 227 | case FieldVar: |
| 228 | return "struct field" |
| 229 | } |
| 230 | case *types.Func: |
| 231 | if obj.Signature().Recv() != nil { |
| 232 | return "method" |
| 233 | } else { |
| 234 | return "function" |
| 235 | } |
| 236 | case *types.Label: |
| 237 | return "label" |
| 238 | case *types.Builtin: |
| 239 | return "built-in function" |
| 240 | case *types.Nil: |
| 241 | return "untyped nil" |
| 242 | } |
| 243 | return "unknown symbol" |
| 244 | } |