...

Source file src/go/types/interface.go

Documentation: go/types

     1  // Copyright 2021 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 types
     6  
     7  import (
     8  	"go/ast"
     9  	"go/token"
    10  )
    11  
    12  // ----------------------------------------------------------------------------
    13  // API
    14  
    15  // An Interface represents an interface type.
    16  type Interface struct {
    17  	check     *Checker     // for error reporting; nil once type set is computed
    18  	methods   []*Func      // ordered list of explicitly declared methods
    19  	embeddeds []Type       // ordered list of explicitly embedded elements
    20  	embedPos  *[]token.Pos // positions of embedded elements; or nil (for error messages) - use pointer to save space
    21  	implicit  bool         // interface is wrapper for type set literal (non-interface T, ~T, or A|B)
    22  	complete  bool         // indicates that obj, methods, and embeddeds are set and type set can be computed
    23  
    24  	tset *_TypeSet // type set described by this interface, computed lazily
    25  }
    26  
    27  // typeSet returns the type set for interface t.
    28  func (t *Interface) typeSet() *_TypeSet { return computeInterfaceTypeSet(t.check, token.NoPos, t) }
    29  
    30  // emptyInterface represents the empty (completed) interface
    31  var emptyInterface = Interface{complete: true, tset: &topTypeSet}
    32  
    33  // NewInterface returns a new interface for the given methods and embedded types.
    34  // NewInterface takes ownership of the provided methods and may modify their types
    35  // by setting missing receivers.
    36  //
    37  // Deprecated: Use NewInterfaceType instead which allows arbitrary embedded types.
    38  func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
    39  	tnames := make([]Type, len(embeddeds))
    40  	for i, t := range embeddeds {
    41  		tnames[i] = t
    42  	}
    43  	return NewInterfaceType(methods, tnames)
    44  }
    45  
    46  // NewInterfaceType returns a new interface for the given methods and embedded
    47  // types. NewInterfaceType takes ownership of the provided methods and may
    48  // modify their types by setting missing receivers.
    49  //
    50  // To avoid race conditions, the interface's type set should be computed before
    51  // concurrent use of the interface, by explicitly calling Complete.
    52  func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
    53  	if len(methods) == 0 && len(embeddeds) == 0 {
    54  		return &emptyInterface
    55  	}
    56  
    57  	// set method receivers if necessary
    58  	typ := (*Checker)(nil).newInterface()
    59  	for _, m := range methods {
    60  		if sig := m.typ.(*Signature); sig.recv == nil {
    61  			sig.recv = NewVar(m.pos, m.pkg, "", typ)
    62  		}
    63  	}
    64  
    65  	// sort for API stability
    66  	sortMethods(methods)
    67  
    68  	typ.methods = methods
    69  	typ.embeddeds = embeddeds
    70  	typ.complete = true
    71  
    72  	return typ
    73  }
    74  
    75  // check may be nil
    76  func (check *Checker) newInterface() *Interface {
    77  	typ := &Interface{check: check}
    78  	if check != nil {
    79  		check.needsCleanup(typ)
    80  	}
    81  	return typ
    82  }
    83  
    84  // MarkImplicit marks the interface t as implicit, meaning this interface
    85  // corresponds to a constraint literal such as ~T or A|B without explicit
    86  // interface embedding. MarkImplicit should be called before any concurrent use
    87  // of implicit interfaces.
    88  func (t *Interface) MarkImplicit() {
    89  	t.implicit = true
    90  }
    91  
    92  // NumExplicitMethods returns the number of explicitly declared methods of interface t.
    93  func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
    94  
    95  // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
    96  // The methods are ordered by their unique Id.
    97  func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
    98  
    99  // NumEmbeddeds returns the number of embedded types in interface t.
   100  func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
   101  
   102  // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
   103  // The result is nil if the i'th embedded type is not a defined type.
   104  //
   105  // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
   106  func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
   107  
   108  // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
   109  func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
   110  
   111  // NumMethods returns the total number of methods of interface t.
   112  func (t *Interface) NumMethods() int { return t.typeSet().NumMethods() }
   113  
   114  // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
   115  // The methods are ordered by their unique Id.
   116  func (t *Interface) Method(i int) *Func { return t.typeSet().Method(i) }
   117  
   118  // Empty reports whether t is the empty interface.
   119  func (t *Interface) Empty() bool { return t.typeSet().IsAll() }
   120  
   121  // IsComparable reports whether each type in interface t's type set is comparable.
   122  func (t *Interface) IsComparable() bool { return t.typeSet().IsComparable(nil) }
   123  
   124  // IsMethodSet reports whether the interface t is fully described by its method
   125  // set.
   126  func (t *Interface) IsMethodSet() bool { return t.typeSet().IsMethodSet() }
   127  
   128  // IsImplicit reports whether the interface t is a wrapper for a type set literal.
   129  func (t *Interface) IsImplicit() bool { return t.implicit }
   130  
   131  // Complete computes the interface's type set. It must be called by users of
   132  // NewInterfaceType and NewInterface after the interface's embedded types are
   133  // fully defined and before using the interface type in any way other than to
   134  // form other types. The interface must not contain duplicate methods or a
   135  // panic occurs. Complete returns the receiver.
   136  //
   137  // Interface types that have been completed are safe for concurrent use.
   138  func (t *Interface) Complete() *Interface {
   139  	if !t.complete {
   140  		t.complete = true
   141  	}
   142  	t.typeSet() // checks if t.tset is already set
   143  	return t
   144  }
   145  
   146  func (t *Interface) Underlying() Type { return t }
   147  func (t *Interface) String() string   { return TypeString(t, nil) }
   148  
   149  // ----------------------------------------------------------------------------
   150  // Implementation
   151  
   152  func (t *Interface) cleanup() {
   153  	t.check = nil
   154  	t.embedPos = nil
   155  }
   156  
   157  func (check *Checker) interfaceType(ityp *Interface, iface *ast.InterfaceType, def *Named) {
   158  	addEmbedded := func(pos token.Pos, typ Type) {
   159  		ityp.embeddeds = append(ityp.embeddeds, typ)
   160  		if ityp.embedPos == nil {
   161  			ityp.embedPos = new([]token.Pos)
   162  		}
   163  		*ityp.embedPos = append(*ityp.embedPos, pos)
   164  	}
   165  
   166  	for _, f := range iface.Methods.List {
   167  		if len(f.Names) == 0 {
   168  			addEmbedded(f.Type.Pos(), parseUnion(check, f.Type))
   169  			continue
   170  		}
   171  		// f.Name != nil
   172  
   173  		// We have a method with name f.Names[0].
   174  		name := f.Names[0]
   175  		if name.Name == "_" {
   176  			check.errorf(name, _BlankIfaceMethod, "methods must have a unique non-blank name")
   177  			continue // ignore
   178  		}
   179  
   180  		typ := check.typ(f.Type)
   181  		sig, _ := typ.(*Signature)
   182  		if sig == nil {
   183  			if typ != Typ[Invalid] {
   184  				check.invalidAST(f.Type, "%s is not a method signature", typ)
   185  			}
   186  			continue // ignore
   187  		}
   188  
   189  		// Always type-check method type parameters but complain if they are not enabled.
   190  		// (This extra check is needed here because interface method signatures don't have
   191  		// a receiver specification.)
   192  		if sig.tparams != nil {
   193  			var at positioner = f.Type
   194  			if ftyp, _ := f.Type.(*ast.FuncType); ftyp != nil && ftyp.TypeParams != nil {
   195  				at = ftyp.TypeParams
   196  			}
   197  			check.errorf(at, _InvalidMethodTypeParams, "methods cannot have type parameters")
   198  		}
   199  
   200  		// use named receiver type if available (for better error messages)
   201  		var recvTyp Type = ityp
   202  		if def != nil {
   203  			recvTyp = def
   204  		}
   205  		sig.recv = NewVar(name.Pos(), check.pkg, "", recvTyp)
   206  
   207  		m := NewFunc(name.Pos(), check.pkg, name.Name, sig)
   208  		check.recordDef(name, m)
   209  		ityp.methods = append(ityp.methods, m)
   210  	}
   211  
   212  	// All methods and embedded elements for this interface are collected;
   213  	// i.e., this interface may be used in a type set computation.
   214  	ityp.complete = true
   215  
   216  	if len(ityp.methods) == 0 && len(ityp.embeddeds) == 0 {
   217  		// empty interface
   218  		ityp.tset = &topTypeSet
   219  		return
   220  	}
   221  
   222  	// sort for API stability
   223  	sortMethods(ityp.methods)
   224  	// (don't sort embeddeds: they must correspond to *embedPos entries)
   225  
   226  	// Compute type set as soon as possible to report any errors.
   227  	// Subsequent uses of type sets will use this computed type
   228  	// set and won't need to pass in a *Checker.
   229  	check.later(func() {
   230  		computeInterfaceTypeSet(check, iface.Pos(), ityp)
   231  	}).describef(iface, "compute type set for %s", ityp)
   232  }
   233  

View as plain text