| 1 |
// Copyright 2024 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 |
) |
| 10 |
|
| 11 |
// ReceiverNamed returns the named type (if any) associated with the |
| 12 |
// type of recv, which may be of the form N or *N, or aliases thereof. |
| 13 |
// It also reports whether a Pointer was present. |
| 14 |
// |
| 15 |
// The named result may be nil if recv is from a method on an |
| 16 |
// anonymous interface or struct types or in ill-typed code. |
| 17 |
func ReceiverNamed(recv *types.Var) (isPtr bool, named *types.Named) { |
| 18 |
t := recv.Type() |
| 19 |
if ptr, ok := types.Unalias(t).(*types.Pointer); ok { |
| 20 |
isPtr = true |
| 21 |
t = ptr.Elem() |
| 22 |
} |
| 23 |
named, _ = types.Unalias(t).(*types.Named) |
| 24 |
return |
| 25 |
} |
| 26 |
|
| 27 |
// Unpointer returns T given *T or an alias thereof. |
| 28 |
// For all other types it is the identity function. |
| 29 |
// It does not look at underlying types. |
| 30 |
// The result may be an alias. |
| 31 |
// |
| 32 |
// Use this function to strip off the optional pointer on a receiver |
| 33 |
// in a field or method selection, without losing the named type |
| 34 |
// (which is needed to compute the method set). |
| 35 |
// |
| 36 |
// See also [typeparams.MustDeref], which removes one level of |
| 37 |
// indirection from the type, regardless of named types (analogous to |
| 38 |
// a LOAD instruction). |
| 39 |
func Unpointer(t types.Type) types.Type { |
| 40 |
if ptr, ok := types.Unalias(t).(*types.Pointer); ok { |
| 41 |
return ptr.Elem() |
| 42 |
} |
| 43 |
return t |
| 44 |
} |