Source file src/cmd/compile/internal/types2/lookup.go

     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  // This file implements various field and method lookup functions.
     6  
     7  package types2
     8  
     9  import (
    10  	"bytes"
    11  	"cmd/compile/internal/syntax"
    12  	"strings"
    13  )
    14  
    15  // Internal use of LookupFieldOrMethod: If the obj result is a method
    16  // associated with a concrete (non-interface) type, the method's signature
    17  // may not be fully set up. Call Checker.objDecl(obj, nil) before accessing
    18  // the method's type.
    19  
    20  // LookupFieldOrMethod looks up a field or method with given package and name
    21  // in T and returns the corresponding *Var or *Func, an index sequence, and a
    22  // bool indicating if there were any pointer indirections on the path to the
    23  // field or method. If addressable is set, T is the type of an addressable
    24  // variable (only matters for method lookups). T must not be nil.
    25  //
    26  // The last index entry is the field or method index in the (possibly embedded)
    27  // type where the entry was found, either:
    28  //
    29  //  1. the list of declared methods of a named type; or
    30  //  2. the list of all methods (method set) of an interface type; or
    31  //  3. the list of fields of a struct type.
    32  //
    33  // The earlier index entries are the indices of the embedded struct fields
    34  // traversed to get to the found entry, starting at depth 0.
    35  //
    36  // If no entry is found, a nil object is returned. In this case, the returned
    37  // index and indirect values have the following meaning:
    38  //
    39  //   - If index != nil, the index sequence points to an ambiguous entry
    40  //     (the same name appeared more than once at the same embedding level).
    41  //
    42  //   - If indirect is set, a method with a pointer receiver type was found
    43  //     but there was no pointer on the path from the actual receiver type to
    44  //     the method's formal receiver base type, nor was the receiver addressable.
    45  func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
    46  	if T == nil {
    47  		panic("LookupFieldOrMethod on nil type")
    48  	}
    49  
    50  	// Methods cannot be associated to a named pointer type.
    51  	// (spec: "The type denoted by T is called the receiver base type;
    52  	// it must not be a pointer or interface type and it must be declared
    53  	// in the same package as the method.").
    54  	// Thus, if we have a named pointer type, proceed with the underlying
    55  	// pointer type but discard the result if it is a method since we would
    56  	// not have found it for T (see also go.dev/issue/8590).
    57  	if t := asNamed(T); t != nil {
    58  		if p, _ := t.Underlying().(*Pointer); p != nil {
    59  			obj, index, indirect = lookupFieldOrMethodImpl(p, false, pkg, name, false)
    60  			if _, ok := obj.(*Func); ok {
    61  				return nil, nil, false
    62  			}
    63  			return
    64  		}
    65  	}
    66  
    67  	obj, index, indirect = lookupFieldOrMethodImpl(T, addressable, pkg, name, false)
    68  
    69  	// If we didn't find anything and if we have a type parameter with a core type,
    70  	// see if there is a matching field (but not a method, those need to be declared
    71  	// explicitly in the constraint). If the constraint is a named pointer type (see
    72  	// above), we are ok here because only fields are accepted as results.
    73  	const enableTParamFieldLookup = false // see go.dev/issue/51576
    74  	if enableTParamFieldLookup && obj == nil && isTypeParam(T) {
    75  		if t := coreType(T); t != nil {
    76  			obj, index, indirect = lookupFieldOrMethodImpl(t, addressable, pkg, name, false)
    77  			if _, ok := obj.(*Var); !ok {
    78  				obj, index, indirect = nil, nil, false // accept fields (variables) only
    79  			}
    80  		}
    81  	}
    82  	return
    83  }
    84  
    85  // lookupFieldOrMethodImpl is the implementation of LookupFieldOrMethod.
    86  // Notably, in contrast to LookupFieldOrMethod, it won't find struct fields
    87  // in base types of defined (*Named) pointer types T. For instance, given
    88  // the declaration:
    89  //
    90  //	type T *struct{f int}
    91  //
    92  // lookupFieldOrMethodImpl won't find the field f in the defined (*Named) type T
    93  // (methods on T are not permitted in the first place).
    94  //
    95  // Thus, lookupFieldOrMethodImpl should only be called by LookupFieldOrMethod
    96  // and missingMethod (the latter doesn't care about struct fields).
    97  //
    98  // If foldCase is true, method names are considered equal if they are equal
    99  // with case folding, irrespective of which package they are in.
   100  //
   101  // The resulting object may not be fully type-checked.
   102  func lookupFieldOrMethodImpl(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool) {
   103  	// WARNING: The code in this function is extremely subtle - do not modify casually!
   104  
   105  	if name == "_" {
   106  		return // blank fields/methods are never found
   107  	}
   108  
   109  	// Importantly, we must not call under before the call to deref below (nor
   110  	// does deref call under), as doing so could incorrectly result in finding
   111  	// methods of the pointer base type when T is a (*Named) pointer type.
   112  	typ, isPtr := deref(T)
   113  
   114  	// *typ where typ is an interface (incl. a type parameter) has no methods.
   115  	if isPtr {
   116  		if _, ok := under(typ).(*Interface); ok {
   117  			return
   118  		}
   119  	}
   120  
   121  	// Start with typ as single entry at shallowest depth.
   122  	current := []embeddedType{{typ, nil, isPtr, false}}
   123  
   124  	// seen tracks named types that we have seen already, allocated lazily.
   125  	// Used to avoid endless searches in case of recursive types.
   126  	//
   127  	// We must use a lookup on identity rather than a simple map[*Named]bool as
   128  	// instantiated types may be identical but not equal.
   129  	var seen instanceLookup
   130  
   131  	// search current depth
   132  	for len(current) > 0 {
   133  		var next []embeddedType // embedded types found at current depth
   134  
   135  		// look for (pkg, name) in all types at current depth
   136  		for _, e := range current {
   137  			typ := e.typ
   138  
   139  			// If we have a named type, we may have associated methods.
   140  			// Look for those first.
   141  			if named := asNamed(typ); named != nil {
   142  				if alt := seen.lookup(named); alt != nil {
   143  					// We have seen this type before, at a more shallow depth
   144  					// (note that multiples of this type at the current depth
   145  					// were consolidated before). The type at that depth shadows
   146  					// this same type at the current depth, so we can ignore
   147  					// this one.
   148  					continue
   149  				}
   150  				seen.add(named)
   151  
   152  				// look for a matching attached method
   153  				if i, m := named.lookupMethod(pkg, name, foldCase); m != nil {
   154  					// potential match
   155  					// caution: method may not have a proper signature yet
   156  					index = concat(e.index, i)
   157  					if obj != nil || e.multiples {
   158  						return nil, index, false // collision
   159  					}
   160  					obj = m
   161  					indirect = e.indirect
   162  					continue // we can't have a matching field or interface method
   163  				}
   164  			}
   165  
   166  			switch t := under(typ).(type) {
   167  			case *Struct:
   168  				// look for a matching field and collect embedded types
   169  				for i, f := range t.fields {
   170  					if f.sameId(pkg, name) {
   171  						assert(f.typ != nil)
   172  						index = concat(e.index, i)
   173  						if obj != nil || e.multiples {
   174  							return nil, index, false // collision
   175  						}
   176  						obj = f
   177  						indirect = e.indirect
   178  						continue // we can't have a matching interface method
   179  					}
   180  					// Collect embedded struct fields for searching the next
   181  					// lower depth, but only if we have not seen a match yet
   182  					// (if we have a match it is either the desired field or
   183  					// we have a name collision on the same depth; in either
   184  					// case we don't need to look further).
   185  					// Embedded fields are always of the form T or *T where
   186  					// T is a type name. If e.typ appeared multiple times at
   187  					// this depth, f.typ appears multiple times at the next
   188  					// depth.
   189  					if obj == nil && f.embedded {
   190  						typ, isPtr := deref(f.typ)
   191  						// TODO(gri) optimization: ignore types that can't
   192  						// have fields or methods (only Named, Struct, and
   193  						// Interface types need to be considered).
   194  						next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
   195  					}
   196  				}
   197  
   198  			case *Interface:
   199  				// look for a matching method (interface may be a type parameter)
   200  				if i, m := t.typeSet().LookupMethod(pkg, name, foldCase); m != nil {
   201  					assert(m.typ != nil)
   202  					index = concat(e.index, i)
   203  					if obj != nil || e.multiples {
   204  						return nil, index, false // collision
   205  					}
   206  					obj = m
   207  					indirect = e.indirect
   208  				}
   209  			}
   210  		}
   211  
   212  		if obj != nil {
   213  			// found a potential match
   214  			// spec: "A method call x.m() is valid if the method set of (the type of) x
   215  			//        contains m and the argument list can be assigned to the parameter
   216  			//        list of m. If x is addressable and &x's method set contains m, x.m()
   217  			//        is shorthand for (&x).m()".
   218  			if f, _ := obj.(*Func); f != nil {
   219  				// determine if method has a pointer receiver
   220  				if f.hasPtrRecv() && !indirect && !addressable {
   221  					return nil, nil, true // pointer/addressable receiver required
   222  				}
   223  			}
   224  			return
   225  		}
   226  
   227  		current = consolidateMultiples(next)
   228  	}
   229  
   230  	return nil, nil, false // not found
   231  }
   232  
   233  // embeddedType represents an embedded type
   234  type embeddedType struct {
   235  	typ       Type
   236  	index     []int // embedded field indices, starting with index at depth 0
   237  	indirect  bool  // if set, there was a pointer indirection on the path to this field
   238  	multiples bool  // if set, typ appears multiple times at this depth
   239  }
   240  
   241  // consolidateMultiples collects multiple list entries with the same type
   242  // into a single entry marked as containing multiples. The result is the
   243  // consolidated list.
   244  func consolidateMultiples(list []embeddedType) []embeddedType {
   245  	if len(list) <= 1 {
   246  		return list // at most one entry - nothing to do
   247  	}
   248  
   249  	n := 0                     // number of entries w/ unique type
   250  	prev := make(map[Type]int) // index at which type was previously seen
   251  	for _, e := range list {
   252  		if i, found := lookupType(prev, e.typ); found {
   253  			list[i].multiples = true
   254  			// ignore this entry
   255  		} else {
   256  			prev[e.typ] = n
   257  			list[n] = e
   258  			n++
   259  		}
   260  	}
   261  	return list[:n]
   262  }
   263  
   264  func lookupType(m map[Type]int, typ Type) (int, bool) {
   265  	// fast path: maybe the types are equal
   266  	if i, found := m[typ]; found {
   267  		return i, true
   268  	}
   269  
   270  	for t, i := range m {
   271  		if Identical(t, typ) {
   272  			return i, true
   273  		}
   274  	}
   275  
   276  	return 0, false
   277  }
   278  
   279  type instanceLookup struct {
   280  	// buf is used to avoid allocating the map m in the common case of a small
   281  	// number of instances.
   282  	buf [3]*Named
   283  	m   map[*Named][]*Named
   284  }
   285  
   286  func (l *instanceLookup) lookup(inst *Named) *Named {
   287  	for _, t := range l.buf {
   288  		if t != nil && Identical(inst, t) {
   289  			return t
   290  		}
   291  	}
   292  	for _, t := range l.m[inst.Origin()] {
   293  		if Identical(inst, t) {
   294  			return t
   295  		}
   296  	}
   297  	return nil
   298  }
   299  
   300  func (l *instanceLookup) add(inst *Named) {
   301  	for i, t := range l.buf {
   302  		if t == nil {
   303  			l.buf[i] = inst
   304  			return
   305  		}
   306  	}
   307  	if l.m == nil {
   308  		l.m = make(map[*Named][]*Named)
   309  	}
   310  	insts := l.m[inst.Origin()]
   311  	l.m[inst.Origin()] = append(insts, inst)
   312  }
   313  
   314  // MissingMethod returns (nil, false) if V implements T, otherwise it
   315  // returns a missing method required by T and whether it is missing or
   316  // just has the wrong type: either a pointer receiver or wrong signature.
   317  //
   318  // For non-interface types V, or if static is set, V implements T if all
   319  // methods of T are present in V. Otherwise (V is an interface and static
   320  // is not set), MissingMethod only checks that methods of T which are also
   321  // present in V have matching types (e.g., for a type assertion x.(T) where
   322  // x is of interface type V).
   323  func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
   324  	return (*Checker)(nil).missingMethod(V, T, static, Identical, nil)
   325  }
   326  
   327  // missingMethod is like MissingMethod but accepts a *Checker as receiver,
   328  // a comparator equivalent for type comparison, and a *string for error causes.
   329  // The receiver may be nil if missingMethod is invoked through an exported
   330  // API call (such as MissingMethod), i.e., when all methods have been type-
   331  // checked.
   332  // The underlying type of T must be an interface; T (rather than its under-
   333  // lying type) is used for better error messages (reported through *cause).
   334  // The comparator is used to compare signatures.
   335  // If a method is missing and cause is not nil, *cause describes the error.
   336  func (check *Checker) missingMethod(V, T Type, static bool, equivalent func(x, y Type) bool, cause *string) (method *Func, wrongType bool) {
   337  	methods := under(T).(*Interface).typeSet().methods // T must be an interface
   338  	if len(methods) == 0 {
   339  		return nil, false
   340  	}
   341  
   342  	const (
   343  		ok = iota
   344  		notFound
   345  		wrongName
   346  		unexported
   347  		wrongSig
   348  		ambigSel
   349  		ptrRecv
   350  		field
   351  	)
   352  
   353  	state := ok
   354  	var m *Func // method on T we're trying to implement
   355  	var f *Func // method on V, if found (state is one of ok, wrongName, wrongSig)
   356  
   357  	if u, _ := under(V).(*Interface); u != nil {
   358  		tset := u.typeSet()
   359  		for _, m = range methods {
   360  			_, f = tset.LookupMethod(m.pkg, m.name, false)
   361  
   362  			if f == nil {
   363  				if !static {
   364  					continue
   365  				}
   366  				state = notFound
   367  				break
   368  			}
   369  
   370  			if !equivalent(f.typ, m.typ) {
   371  				state = wrongSig
   372  				break
   373  			}
   374  		}
   375  	} else {
   376  		for _, m = range methods {
   377  			obj, index, indirect := lookupFieldOrMethodImpl(V, false, m.pkg, m.name, false)
   378  
   379  			// check if m is ambiguous, on *V, or on V with case-folding
   380  			if obj == nil {
   381  				switch {
   382  				case index != nil:
   383  					state = ambigSel
   384  				case indirect:
   385  					state = ptrRecv
   386  				default:
   387  					state = notFound
   388  					obj, _, _ = lookupFieldOrMethodImpl(V, false, m.pkg, m.name, true /* fold case */)
   389  					f, _ = obj.(*Func)
   390  					if f != nil {
   391  						state = wrongName
   392  						if f.name == m.name {
   393  							// If the names are equal, f must be unexported
   394  							// (otherwise the package wouldn't matter).
   395  							state = unexported
   396  						}
   397  					}
   398  				}
   399  				break
   400  			}
   401  
   402  			// we must have a method (not a struct field)
   403  			f, _ = obj.(*Func)
   404  			if f == nil {
   405  				state = field
   406  				break
   407  			}
   408  
   409  			// methods may not have a fully set up signature yet
   410  			if check != nil {
   411  				check.objDecl(f, nil)
   412  			}
   413  
   414  			if !equivalent(f.typ, m.typ) {
   415  				state = wrongSig
   416  				break
   417  			}
   418  		}
   419  	}
   420  
   421  	if state == ok {
   422  		return nil, false
   423  	}
   424  
   425  	if cause != nil {
   426  		if f != nil {
   427  			// This method may be formatted in funcString below, so must have a fully
   428  			// set up signature.
   429  			if check != nil {
   430  				check.objDecl(f, nil)
   431  			}
   432  		}
   433  		switch state {
   434  		case notFound:
   435  			switch {
   436  			case isInterfacePtr(V):
   437  				*cause = "(" + check.interfacePtrError(V) + ")"
   438  			case isInterfacePtr(T):
   439  				*cause = "(" + check.interfacePtrError(T) + ")"
   440  			default:
   441  				*cause = check.sprintf("(missing method %s)", m.Name())
   442  			}
   443  		case wrongName:
   444  			fs, ms := check.funcString(f, false), check.funcString(m, false)
   445  			*cause = check.sprintf("(missing method %s)\n\t\thave %s\n\t\twant %s", m.Name(), fs, ms)
   446  		case unexported:
   447  			*cause = check.sprintf("(unexported method %s)", m.Name())
   448  		case wrongSig:
   449  			fs, ms := check.funcString(f, false), check.funcString(m, false)
   450  			if fs == ms {
   451  				// Don't report "want Foo, have Foo".
   452  				// Add package information to disambiguate (go.dev/issue/54258).
   453  				fs, ms = check.funcString(f, true), check.funcString(m, true)
   454  			}
   455  			if fs == ms {
   456  				// We still have "want Foo, have Foo".
   457  				// This is most likely due to different type parameters with
   458  				// the same name appearing in the instantiated signatures
   459  				// (go.dev/issue/61685).
   460  				// Rather than reporting this misleading error cause, for now
   461  				// just point out that the method signature is incorrect.
   462  				// TODO(gri) should find a good way to report the root cause
   463  				*cause = check.sprintf("(wrong type for method %s)", m.Name())
   464  				break
   465  			}
   466  			*cause = check.sprintf("(wrong type for method %s)\n\t\thave %s\n\t\twant %s", m.Name(), fs, ms)
   467  		case ambigSel:
   468  			*cause = check.sprintf("(ambiguous selector %s.%s)", V, m.Name())
   469  		case ptrRecv:
   470  			*cause = check.sprintf("(method %s has pointer receiver)", m.Name())
   471  		case field:
   472  			*cause = check.sprintf("(%s.%s is a field, not a method)", V, m.Name())
   473  		default:
   474  			unreachable()
   475  		}
   476  	}
   477  
   478  	return m, state == wrongSig || state == ptrRecv
   479  }
   480  
   481  func isInterfacePtr(T Type) bool {
   482  	p, _ := under(T).(*Pointer)
   483  	return p != nil && IsInterface(p.base)
   484  }
   485  
   486  // check may be nil.
   487  func (check *Checker) interfacePtrError(T Type) string {
   488  	assert(isInterfacePtr(T))
   489  	if p, _ := under(T).(*Pointer); isTypeParam(p.base) {
   490  		return check.sprintf("type %s is pointer to type parameter, not type parameter", T)
   491  	}
   492  	return check.sprintf("type %s is pointer to interface, not interface", T)
   493  }
   494  
   495  // funcString returns a string of the form name + signature for f.
   496  // check may be nil.
   497  func (check *Checker) funcString(f *Func, pkgInfo bool) string {
   498  	buf := bytes.NewBufferString(f.name)
   499  	var qf Qualifier
   500  	if check != nil && !pkgInfo {
   501  		qf = check.qualifier
   502  	}
   503  	w := newTypeWriter(buf, qf)
   504  	w.pkgInfo = pkgInfo
   505  	w.paramNames = false
   506  	w.signature(f.typ.(*Signature))
   507  	return buf.String()
   508  }
   509  
   510  // assertableTo reports whether a value of type V can be asserted to have type T.
   511  // The receiver may be nil if assertableTo is invoked through an exported API call
   512  // (such as AssertableTo), i.e., when all methods have been type-checked.
   513  // The underlying type of V must be an interface.
   514  // If the result is false and cause is not nil, *cause describes the error.
   515  // TODO(gri) replace calls to this function with calls to newAssertableTo.
   516  func (check *Checker) assertableTo(V, T Type, cause *string) bool {
   517  	// no static check is required if T is an interface
   518  	// spec: "If T is an interface type, x.(T) asserts that the
   519  	//        dynamic type of x implements the interface T."
   520  	if IsInterface(T) {
   521  		return true
   522  	}
   523  	// TODO(gri) fix this for generalized interfaces
   524  	m, _ := check.missingMethod(T, V, false, Identical, cause)
   525  	return m == nil
   526  }
   527  
   528  // newAssertableTo reports whether a value of type V can be asserted to have type T.
   529  // It also implements behavior for interfaces that currently are only permitted
   530  // in constraint position (we have not yet defined that behavior in the spec).
   531  // The underlying type of V must be an interface.
   532  // If the result is false and cause is not nil, *cause is set to the error cause.
   533  func (check *Checker) newAssertableTo(pos syntax.Pos, V, T Type, cause *string) bool {
   534  	// no static check is required if T is an interface
   535  	// spec: "If T is an interface type, x.(T) asserts that the
   536  	//        dynamic type of x implements the interface T."
   537  	if IsInterface(T) {
   538  		return true
   539  	}
   540  	return check.implements(pos, T, V, false, cause)
   541  }
   542  
   543  // deref dereferences typ if it is a *Pointer (but not a *Named type
   544  // with an underlying pointer type!) and returns its base and true.
   545  // Otherwise it returns (typ, false).
   546  func deref(typ Type) (Type, bool) {
   547  	if p, _ := Unalias(typ).(*Pointer); p != nil {
   548  		// p.base should never be nil, but be conservative
   549  		if p.base == nil {
   550  			if debug {
   551  				panic("pointer with nil base type (possibly due to an invalid cyclic declaration)")
   552  			}
   553  			return Typ[Invalid], true
   554  		}
   555  		return p.base, true
   556  	}
   557  	return typ, false
   558  }
   559  
   560  // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
   561  // (named or unnamed) struct and returns its base. Otherwise it returns typ.
   562  func derefStructPtr(typ Type) Type {
   563  	if p, _ := under(typ).(*Pointer); p != nil {
   564  		if _, ok := under(p.base).(*Struct); ok {
   565  			return p.base
   566  		}
   567  	}
   568  	return typ
   569  }
   570  
   571  // concat returns the result of concatenating list and i.
   572  // The result does not share its underlying array with list.
   573  func concat(list []int, i int) []int {
   574  	var t []int
   575  	t = append(t, list...)
   576  	return append(t, i)
   577  }
   578  
   579  // fieldIndex returns the index for the field with matching package and name, or a value < 0.
   580  func fieldIndex(fields []*Var, pkg *Package, name string) int {
   581  	if name != "_" {
   582  		for i, f := range fields {
   583  			if f.sameId(pkg, name) {
   584  				return i
   585  			}
   586  		}
   587  	}
   588  	return -1
   589  }
   590  
   591  // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
   592  // If foldCase is true, method names are considered equal if they are equal with case folding
   593  // and their packages are ignored (e.g., pkg1.m, pkg1.M, pkg2.m, and pkg2.M are all equal).
   594  func lookupMethod(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func) {
   595  	if name != "_" {
   596  		for i, m := range methods {
   597  			if m.sameId(pkg, name) || foldCase && strings.EqualFold(m.name, name) {
   598  				return i, m
   599  			}
   600  		}
   601  	}
   602  	return -1, nil
   603  }
   604  

View as plain text