| 1 | // Copyright 2025 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 |
| 6 | |
| 7 | import ( |
| 8 | "go/types" |
| 9 | "slices" |
| 10 | ) |
| 11 | |
| 12 | // IsTypeNamed reports whether t is (or is an alias for) a |
| 13 | // package-level defined type with the given package path and one of |
| 14 | // the given names. It returns false if t is nil. |
| 15 | // |
| 16 | // This function avoids allocating the concatenation of "pkg.Name", |
| 17 | // which is important for the performance of syntax matching. |
| 18 | func IsTypeNamed(t types.Type, pkgPath string, names ...string) bool { |
| 19 | if named, ok := types.Unalias(t).(*types.Named); ok { |
| 20 | tname := named.Obj() |
| 21 | return tname != nil && |
| 22 | IsPackageLevel(tname) && |
| 23 | tname.Pkg().Path() == pkgPath && |
| 24 | slices.Contains(names, tname.Name()) |
| 25 | } |
| 26 | return false |
| 27 | } |
| 28 | |
| 29 | // IsPointerToNamed reports whether t is (or is an alias for) a pointer to a |
| 30 | // package-level defined type with the given package path and one of the given |
| 31 | // names. It returns false if t is not a pointer type. |
| 32 | func IsPointerToNamed(t types.Type, pkgPath string, names ...string) bool { |
| 33 | r := Unpointer(t) |
| 34 | if r == t { |
| 35 | return false |
| 36 | } |
| 37 | return IsTypeNamed(r, pkgPath, names...) |
| 38 | } |
| 39 | |
| 40 | // IsFunctionNamed reports whether obj is a package-level function |
| 41 | // defined in the given package and has one of the given names. |
| 42 | // It returns false if obj is nil. |
| 43 | // |
| 44 | // This function avoids allocating the concatenation of "pkg.Name", |
| 45 | // which is important for the performance of syntax matching. |
| 46 | func IsFunctionNamed(obj types.Object, pkgPath string, names ...string) bool { |
| 47 | f, ok := obj.(*types.Func) |
| 48 | return ok && |
| 49 | IsPackageLevel(obj) && |
| 50 | f.Pkg().Path() == pkgPath && |
| 51 | f.Signature().Recv() == nil && |
| 52 | slices.Contains(names, f.Name()) |
| 53 | } |
| 54 | |
| 55 | // IsMethodNamed reports whether obj is a method defined on a |
| 56 | // package-level type with the given package and type name, and has |
| 57 | // one of the given names. It returns false if obj is nil. |
| 58 | // |
| 59 | // This function avoids allocating the concatenation of "pkg.TypeName.Name", |
| 60 | // which is important for the performance of syntax matching. |
| 61 | func IsMethodNamed(obj types.Object, pkgPath string, typeName string, names ...string) bool { |
| 62 | if fn, ok := obj.(*types.Func); ok { |
| 63 | if recv := fn.Signature().Recv(); recv != nil { |
| 64 | _, T := ReceiverNamed(recv) |
| 65 | return T != nil && |
| 66 | IsTypeNamed(T, pkgPath, typeName) && |
| 67 | slices.Contains(names, fn.Name()) |
| 68 | } |
| 69 | } |
| 70 | return false |
| 71 | } |