| 1 |
// Copyright 2013 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 ir |
| 6 |
|
| 7 |
// This file defines a number of miscellaneous utility functions. |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"go/ast" |
| 12 |
"go/token" |
| 13 |
"go/types" |
| 14 |
"io" |
| 15 |
"os" |
| 16 |
"sync" |
| 17 |
_ "unsafe" // for go:linkname hack |
| 18 |
|
| 19 |
"honnef.co/go/tools/go/types/typeutil" |
| 20 |
|
| 21 |
"golang.org/x/exp/typeparams" |
| 22 |
) |
| 23 |
|
| 24 |
type unit struct{} |
| 25 |
|
| 26 |
//// AST utilities |
| 27 |
|
| 28 |
// isBlankIdent returns true iff e is an Ident with name "_". |
| 29 |
// They have no associated types.Object, and thus no type. |
| 30 |
func isBlankIdent(e ast.Expr) bool { |
| 31 |
id, ok := e.(*ast.Ident) |
| 32 |
return ok && id.Name == "_" |
| 33 |
} |
| 34 |
|
| 35 |
//// Type utilities. Some of these belong in go/types. |
| 36 |
|
| 37 |
// isString reports whether t is exactly a string type. |
| 38 |
// t is assumed to be an Underlying type (not Named or Alias). |
| 39 |
func isString(t types.Type) bool { |
| 40 |
basic, ok := t.(*types.Basic) |
| 41 |
return ok && basic.Info()&types.IsString != 0 |
| 42 |
} |
| 43 |
|
| 44 |
// isByteSlice reports whether t is of the form []~bytes. |
| 45 |
// t is assumed to be an Underlying type (not Named or Alias). |
| 46 |
func isByteSlice(t types.Type) bool { |
| 47 |
if b, ok := t.(*types.Slice); ok { |
| 48 |
e, _ := b.Elem().Underlying().(*types.Basic) |
| 49 |
return e != nil && e.Kind() == types.Byte |
| 50 |
} |
| 51 |
return false |
| 52 |
} |
| 53 |
|
| 54 |
// isRuneSlice reports whether t is of the form []~runes. |
| 55 |
// t is assumed to be an Underlying type (not Named or Alias). |
| 56 |
func isRuneSlice(t types.Type) bool { |
| 57 |
if b, ok := t.(*types.Slice); ok { |
| 58 |
e, _ := b.Elem().Underlying().(*types.Basic) |
| 59 |
return e != nil && e.Kind() == types.Rune |
| 60 |
} |
| 61 |
return false |
| 62 |
} |
| 63 |
|
| 64 |
// isBasicConvTypes returns true when the type set of a type |
| 65 |
// can be one side of a Convert operation. This is when: |
| 66 |
// - All are basic, []byte, or []rune. |
| 67 |
// - At least 1 is basic. |
| 68 |
// - At most 1 is []byte or []rune. |
| 69 |
func isBasicConvTypes(typ types.Type) bool { |
| 70 |
basics, cnt := 0, 0 |
| 71 |
ok := underIs(typ, func(t types.Type) bool { |
| 72 |
cnt++ |
| 73 |
if isBasic(t) { |
| 74 |
basics++ |
| 75 |
return true |
| 76 |
} |
| 77 |
return isByteSlice(t) || isRuneSlice(t) |
| 78 |
}) |
| 79 |
return ok && basics >= 1 && cnt-basics <= 1 |
| 80 |
} |
| 81 |
|
| 82 |
// isPointer reports whether t's underlying type is a pointer. |
| 83 |
func isPointer(t types.Type) bool { |
| 84 |
return is[*types.Pointer](t.Underlying()) |
| 85 |
} |
| 86 |
|
| 87 |
// isPointerCore reports whether t's core type is a pointer. |
| 88 |
// |
| 89 |
// (Most pointer manipulation is related to receivers, in which case |
| 90 |
// isPointer is appropriate. tecallers can use isPointer(t). |
| 91 |
func isPointerCore(t types.Type) bool { |
| 92 |
return is[*types.Pointer](typeutil.CoreType(t)) |
| 93 |
} |
| 94 |
|
| 95 |
func is[T any](x any) bool { |
| 96 |
_, ok := x.(T) |
| 97 |
return ok |
| 98 |
} |
| 99 |
|
| 100 |
// deref returns a pointer's element type; otherwise it returns typ. |
| 101 |
func deref(typ types.Type) types.Type { |
| 102 |
orig := typ |
| 103 |
typ = types.Unalias(typ) |
| 104 |
|
| 105 |
if t, ok := typ.(*types.TypeParam); ok { |
| 106 |
if ctyp := typeutil.CoreType(t); ctyp != nil { |
| 107 |
// This can happen, for example, with len(T) where T is a |
| 108 |
// type parameter whose core type is a pointer to array. |
| 109 |
typ = ctyp |
| 110 |
} |
| 111 |
} |
| 112 |
if p, ok := typ.Underlying().(*types.Pointer); ok { |
| 113 |
return p.Elem() |
| 114 |
} |
| 115 |
return orig |
| 116 |
} |
| 117 |
|
| 118 |
// recvType returns the receiver type of method obj. |
| 119 |
func recvType(obj *types.Func) types.Type { |
| 120 |
return obj.Type().(*types.Signature).Recv().Type() |
| 121 |
} |
| 122 |
|
| 123 |
// fieldOf returns the index'th field of the (core type of) a struct type; |
| 124 |
// otherwise returns nil. |
| 125 |
func fieldOf(typ types.Type, index int) *types.Var { |
| 126 |
if st, ok := typeutil.CoreType(typ).(*types.Struct); ok { |
| 127 |
if 0 <= index && index < st.NumFields() { |
| 128 |
return st.Field(index) |
| 129 |
} |
| 130 |
} |
| 131 |
return nil |
| 132 |
} |
| 133 |
|
| 134 |
// isUntyped reports whether typ is the type of an untyped constant. |
| 135 |
func isUntyped(typ types.Type) bool { |
| 136 |
// No Underlying/Unalias: untyped constant types cannot be Named or Alias. |
| 137 |
b, ok := typ.(*types.Basic) |
| 138 |
return ok && b.Info()&types.IsUntyped != 0 |
| 139 |
} |
| 140 |
|
| 141 |
// declaredWithin reports whether an object is declared within a function. |
| 142 |
// |
| 143 |
// obj must not be a method or a field. |
| 144 |
func declaredWithin(obj types.Object, fn *types.Func) bool { |
| 145 |
if obj.Pos() != token.NoPos { |
| 146 |
return fn.Scope().Contains(obj.Pos()) // trust the positions if they exist. |
| 147 |
} |
| 148 |
if fn.Pkg() != obj.Pkg() { |
| 149 |
return false // fast path for different packages |
| 150 |
} |
| 151 |
|
| 152 |
// Traverse Parent() scopes for fn.Scope(). |
| 153 |
for p := obj.Parent(); p != nil; p = p.Parent() { |
| 154 |
if p == fn.Scope() { |
| 155 |
return true |
| 156 |
} |
| 157 |
} |
| 158 |
return false |
| 159 |
} |
| 160 |
|
| 161 |
// logStack prints the formatted "start" message to stderr and |
| 162 |
// returns a closure that prints the corresponding "end" message. |
| 163 |
// Call using 'defer logStack(...)()' to show builder stack on panic. |
| 164 |
// Don't forget trailing parens! |
| 165 |
func logStack(format string, args ...any) func() { |
| 166 |
msg := fmt.Sprintf(format, args...) |
| 167 |
io.WriteString(os.Stderr, msg) |
| 168 |
io.WriteString(os.Stderr, "\n") |
| 169 |
return func() { |
| 170 |
io.WriteString(os.Stderr, msg) |
| 171 |
io.WriteString(os.Stderr, " end\n") |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
// newVar creates a 'var' for use in a types.Tuple. |
| 176 |
func newVar(name string, typ types.Type) *types.Var { |
| 177 |
return types.NewParam(token.NoPos, nil, name, typ) |
| 178 |
} |
| 179 |
|
| 180 |
// anonVar creates an anonymous 'var' for use in a types.Tuple. |
| 181 |
func anonVar(typ types.Type) *types.Var { |
| 182 |
return newVar("", typ) |
| 183 |
} |
| 184 |
|
| 185 |
var lenResults = types.NewTuple(anonVar(tInt)) |
| 186 |
|
| 187 |
// makeLen returns the len builtin specialized to type func(T)int. |
| 188 |
func makeLen(T types.Type) *Builtin { |
| 189 |
lenParams := types.NewTuple(anonVar(T)) |
| 190 |
return &Builtin{ |
| 191 |
name: "len", |
| 192 |
sig: types.NewSignatureType(nil, nil, nil, lenParams, lenResults, false), |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
func assert(x bool, msg string) { |
| 197 |
if !x { |
| 198 |
panic(msg) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
// BlockMap is a mapping from basic blocks (identified by their indices) to values. |
| 203 |
type BlockMap[T any] []T |
| 204 |
|
| 205 |
// isBasic reports whether t is a basic type. |
| 206 |
func isBasic(t types.Type) bool { |
| 207 |
_, ok := t.(*types.Basic) |
| 208 |
return ok |
| 209 |
} |
| 210 |
|
| 211 |
// receiverTypeArgs returns the type arguments to a method's receiver. |
| 212 |
// Returns an empty list if the receiver does not have type arguments. |
| 213 |
func receiverTypeArgs(method *types.Func) []types.Type { |
| 214 |
recv := method.Signature().Recv() |
| 215 |
named := func() (named *types.Named) { |
| 216 |
t := recv.Type() |
| 217 |
if ptr, ok := types.Unalias(t).(*types.Pointer); ok { |
| 218 |
t = ptr.Elem() |
| 219 |
} |
| 220 |
named, _ = types.Unalias(t).(*types.Named) |
| 221 |
return named |
| 222 |
}() |
| 223 |
if named == nil { |
| 224 |
return nil // recv is anonymous struct/interface |
| 225 |
} |
| 226 |
ts := named.TypeArgs() |
| 227 |
if ts.Len() == 0 { |
| 228 |
return nil |
| 229 |
} |
| 230 |
targs := make([]types.Type, ts.Len()) |
| 231 |
for i := 0; i < ts.Len(); i++ { |
| 232 |
targs[i] = ts.At(i) |
| 233 |
} |
| 234 |
return targs |
| 235 |
} |
| 236 |
|
| 237 |
// recvAsFirstArg takes a method signature and returns a function |
| 238 |
// signature with receiver as the first parameter. |
| 239 |
func recvAsFirstArg(sig *types.Signature) *types.Signature { |
| 240 |
params := make([]*types.Var, 0, 1+sig.Params().Len()) |
| 241 |
params = append(params, sig.Recv()) |
| 242 |
for v := range sig.Params().Variables() { |
| 243 |
params = append(params, v) |
| 244 |
} |
| 245 |
return types.NewSignatureType(nil, nil, nil, types.NewTuple(params...), sig.Results(), sig.Variadic()) |
| 246 |
} |
| 247 |
|
| 248 |
// instance returns whether an expression is a simple or qualified identifier |
| 249 |
// that is a generic instantiation. |
| 250 |
func instance(info *types.Info, expr ast.Expr) bool { |
| 251 |
// Compare the logic here against go/types.instantiatedIdent, |
| 252 |
// which also handles *IndexExpr and *IndexListExpr. |
| 253 |
var id *ast.Ident |
| 254 |
switch x := expr.(type) { |
| 255 |
case *ast.Ident: |
| 256 |
id = x |
| 257 |
case *ast.SelectorExpr: |
| 258 |
id = x.Sel |
| 259 |
default: |
| 260 |
return false |
| 261 |
} |
| 262 |
_, ok := info.Instances[id] |
| 263 |
return ok |
| 264 |
} |
| 265 |
|
| 266 |
// isNonTypeParamInterface reports whether t is an interface type but not a type parameter. |
| 267 |
func isNonTypeParamInterface(t types.Type) bool { |
| 268 |
return !typeparams.IsTypeParam(t) && types.IsInterface(t) |
| 269 |
} |
| 270 |
|
| 271 |
// instanceArgs returns the Instance[id].TypeArgs as a slice. |
| 272 |
func instanceArgs(info *types.Info, id *ast.Ident) []types.Type { |
| 273 |
targList := info.Instances[id].TypeArgs |
| 274 |
if targList == nil { |
| 275 |
return nil |
| 276 |
} |
| 277 |
|
| 278 |
targs := make([]types.Type, targList.Len()) |
| 279 |
for i, n := 0, targList.Len(); i < n; i++ { |
| 280 |
targs[i] = targList.At(i) |
| 281 |
} |
| 282 |
return targs |
| 283 |
} |
| 284 |
|
| 285 |
// Mapping of a type T to a canonical instance C s.t. types.Identical(T, C). |
| 286 |
// Thread-safe. |
| 287 |
type canonizer struct { |
| 288 |
mu sync.Mutex |
| 289 |
types typeutil.Map[types.Type] // map from type to a canonical instance |
| 290 |
lists typeListMap // map from a list of types to a canonical instance |
| 291 |
} |
| 292 |
|
| 293 |
func newCanonizer() *canonizer { |
| 294 |
c := &canonizer{} |
| 295 |
h := typeutil.MakeHasher() |
| 296 |
c.types.SetHasher(h) |
| 297 |
c.lists.hasher = h |
| 298 |
return c |
| 299 |
} |
| 300 |
|
| 301 |
// List returns a canonical representative of a list of types. |
| 302 |
// Representative of the empty list is nil. |
| 303 |
func (c *canonizer) List(ts []types.Type) *typeList { |
| 304 |
if len(ts) == 0 { |
| 305 |
return nil |
| 306 |
} |
| 307 |
|
| 308 |
unaliasAll := func(ts []types.Type) []types.Type { |
| 309 |
// Is there some top level alias? |
| 310 |
var found bool |
| 311 |
for _, t := range ts { |
| 312 |
if _, ok := t.(*types.Alias); ok { |
| 313 |
found = true |
| 314 |
break |
| 315 |
} |
| 316 |
} |
| 317 |
if !found { |
| 318 |
return ts // no top level alias |
| 319 |
} |
| 320 |
|
| 321 |
cp := make([]types.Type, len(ts)) // copy with top level aliases removed. |
| 322 |
for i, t := range ts { |
| 323 |
cp[i] = types.Unalias(t) |
| 324 |
} |
| 325 |
return cp |
| 326 |
} |
| 327 |
l := unaliasAll(ts) |
| 328 |
|
| 329 |
c.mu.Lock() |
| 330 |
defer c.mu.Unlock() |
| 331 |
return c.lists.rep(l) |
| 332 |
} |
| 333 |
|
| 334 |
// Type returns a canonical representative of type T. |
| 335 |
// Removes top-level aliases. |
| 336 |
// |
| 337 |
// For performance, reasons the canonical instance is order-dependent, |
| 338 |
// and may contain deeply nested aliases. |
| 339 |
func (c *canonizer) Type(T types.Type) types.Type { |
| 340 |
T = types.Unalias(T) // remove the top level alias. |
| 341 |
|
| 342 |
c.mu.Lock() |
| 343 |
defer c.mu.Unlock() |
| 344 |
|
| 345 |
if r, _ := c.types.At(T); r != nil { |
| 346 |
return r |
| 347 |
} |
| 348 |
c.types.Set(T, T) |
| 349 |
return T |
| 350 |
} |
| 351 |
|
| 352 |
// A type for representing a canonized list of types. |
| 353 |
type typeList []types.Type |
| 354 |
|
| 355 |
func (l *typeList) identical(ts []types.Type) bool { |
| 356 |
if l == nil { |
| 357 |
return len(ts) == 0 |
| 358 |
} |
| 359 |
n := len(*l) |
| 360 |
if len(ts) != n { |
| 361 |
return false |
| 362 |
} |
| 363 |
for i, left := range *l { |
| 364 |
right := ts[i] |
| 365 |
if !types.Identical(left, right) { |
| 366 |
return false |
| 367 |
} |
| 368 |
} |
| 369 |
return true |
| 370 |
} |
| 371 |
|
| 372 |
type typeListMap struct { |
| 373 |
hasher typeutil.Hasher |
| 374 |
buckets map[uint32][]*typeList |
| 375 |
} |
| 376 |
|
| 377 |
// rep returns a canonical representative of a slice of types. |
| 378 |
func (m *typeListMap) rep(ts []types.Type) *typeList { |
| 379 |
if m == nil || len(ts) == 0 { |
| 380 |
return nil |
| 381 |
} |
| 382 |
|
| 383 |
if m.buckets == nil { |
| 384 |
m.buckets = make(map[uint32][]*typeList) |
| 385 |
} |
| 386 |
|
| 387 |
h := m.hash(ts) |
| 388 |
bucket := m.buckets[h] |
| 389 |
for _, l := range bucket { |
| 390 |
if l.identical(ts) { |
| 391 |
return l |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
// not present. create a representative. |
| 396 |
cp := make(typeList, len(ts)) |
| 397 |
copy(cp, ts) |
| 398 |
rep := &cp |
| 399 |
|
| 400 |
m.buckets[h] = append(bucket, rep) |
| 401 |
return rep |
| 402 |
} |
| 403 |
|
| 404 |
func (m *typeListMap) hash(ts []types.Type) uint32 { |
| 405 |
if m == nil { |
| 406 |
return 0 |
| 407 |
} |
| 408 |
// Some smallish prime far away from typeutil.Hash. |
| 409 |
n := len(ts) |
| 410 |
h := uint32(13619) + 2*uint32(n) |
| 411 |
for i := range n { |
| 412 |
h += 3 * m.hasher.Hash(ts[i]) |
| 413 |
} |
| 414 |
return h |
| 415 |
} |
| 416 |
|
| 417 |
// instantiateMethod instantiates m with targs and returns a canonical representative for this method. |
| 418 |
func (canon *canonizer) instantiateMethod(m *types.Func, targs []types.Type, ctxt *types.Context) *types.Func { |
| 419 |
recv := recvType(m) |
| 420 |
if p, ok := types.Unalias(recv).(*types.Pointer); ok { |
| 421 |
recv = p.Elem() |
| 422 |
} |
| 423 |
named := types.Unalias(recv).(*types.Named) |
| 424 |
inst, err := types.Instantiate(ctxt, named.Origin(), targs, false) |
| 425 |
if err != nil { |
| 426 |
panic(err) |
| 427 |
} |
| 428 |
rep := canon.Type(inst) |
| 429 |
obj, _, _ := types.LookupFieldOrMethod(rep, true, m.Pkg(), m.Name()) |
| 430 |
return obj.(*types.Func) |
| 431 |
} |
| 432 |
|
| 433 |
// Exposed to irutil using the linkname hack. |
| 434 |
// |
| 435 |
//go:linkname isSyntactic honnef.co/go/tools/go/ir.isSyntactic |
| 436 |
func isSyntactic(pkg *Package) bool { return pkg.syntax } |