Source file src/go/types/typeset.go

     1  // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
     2  // Source: ../../cmd/compile/internal/types2/typeset.go
     3  
     4  // Copyright 2021 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  package types
     9  
    10  import (
    11  	"go/token"
    12  	. "internal/types/errors"
    13  	"sort"
    14  	"strings"
    15  )
    16  
    17  // ----------------------------------------------------------------------------
    18  // API
    19  
    20  // A _TypeSet represents the type set of an interface.
    21  // Because of existing language restrictions, methods can be "factored out"
    22  // from the terms. The actual type set is the intersection of the type set
    23  // implied by the methods and the type set described by the terms and the
    24  // comparable bit. To test whether a type is included in a type set
    25  // ("implements" relation), the type must implement all methods _and_ be
    26  // an element of the type set described by the terms and the comparable bit.
    27  // If the term list describes the set of all types and comparable is true,
    28  // only comparable types are meant; in all other cases comparable is false.
    29  type _TypeSet struct {
    30  	methods    []*Func  // all methods of the interface; sorted by unique ID
    31  	terms      termlist // type terms of the type set
    32  	comparable bool     // invariant: !comparable || terms.isAll()
    33  }
    34  
    35  // IsEmpty reports whether type set s is the empty set.
    36  func (s *_TypeSet) IsEmpty() bool { return s.terms.isEmpty() }
    37  
    38  // IsAll reports whether type set s is the set of all types (corresponding to the empty interface).
    39  func (s *_TypeSet) IsAll() bool { return s.IsMethodSet() && len(s.methods) == 0 }
    40  
    41  // IsMethodSet reports whether the interface t is fully described by its method set.
    42  func (s *_TypeSet) IsMethodSet() bool { return !s.comparable && s.terms.isAll() }
    43  
    44  // IsComparable reports whether each type in the set is comparable.
    45  func (s *_TypeSet) IsComparable(seen map[Type]bool) bool {
    46  	if s.terms.isAll() {
    47  		return s.comparable
    48  	}
    49  	return s.is(func(t *term) bool {
    50  		return t != nil && comparable(t.typ, false, seen, nil)
    51  	})
    52  }
    53  
    54  // NumMethods returns the number of methods available.
    55  func (s *_TypeSet) NumMethods() int { return len(s.methods) }
    56  
    57  // Method returns the i'th method of type set s for 0 <= i < s.NumMethods().
    58  // The methods are ordered by their unique ID.
    59  func (s *_TypeSet) Method(i int) *Func { return s.methods[i] }
    60  
    61  // LookupMethod returns the index of and method with matching package and name, or (-1, nil).
    62  func (s *_TypeSet) LookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) {
    63  	return methodIndex(s.methods, pkg, name, foldCase)
    64  }
    65  
    66  func (s *_TypeSet) String() string {
    67  	switch {
    68  	case s.IsEmpty():
    69  		return "∅"
    70  	case s.IsAll():
    71  		return "𝓤"
    72  	}
    73  
    74  	hasMethods := len(s.methods) > 0
    75  	hasTerms := s.hasTerms()
    76  
    77  	var buf strings.Builder
    78  	buf.WriteByte('{')
    79  	if s.comparable {
    80  		buf.WriteString("comparable")
    81  		if hasMethods || hasTerms {
    82  			buf.WriteString("; ")
    83  		}
    84  	}
    85  	for i, m := range s.methods {
    86  		if i > 0 {
    87  			buf.WriteString("; ")
    88  		}
    89  		buf.WriteString(m.String())
    90  	}
    91  	if hasMethods && hasTerms {
    92  		buf.WriteString("; ")
    93  	}
    94  	if hasTerms {
    95  		buf.WriteString(s.terms.String())
    96  	}
    97  	buf.WriteString("}")
    98  	return buf.String()
    99  }
   100  
   101  // ----------------------------------------------------------------------------
   102  // Implementation
   103  
   104  // hasTerms reports whether the type set has specific type terms.
   105  func (s *_TypeSet) hasTerms() bool { return !s.terms.isEmpty() && !s.terms.isAll() }
   106  
   107  // subsetOf reports whether s1 ⊆ s2.
   108  func (s1 *_TypeSet) subsetOf(s2 *_TypeSet) bool { return s1.terms.subsetOf(s2.terms) }
   109  
   110  // TODO(gri) TypeSet.is and TypeSet.underIs should probably also go into termlist.go
   111  
   112  // is calls f with the specific type terms of s and reports whether
   113  // all calls to f returned true. If there are no specific terms, is
   114  // returns the result of f(nil).
   115  func (s *_TypeSet) is(f func(*term) bool) bool {
   116  	if !s.hasTerms() {
   117  		return f(nil)
   118  	}
   119  	for _, t := range s.terms {
   120  		assert(t.typ != nil)
   121  		if !f(t) {
   122  			return false
   123  		}
   124  	}
   125  	return true
   126  }
   127  
   128  // underIs calls f with the underlying types of the specific type terms
   129  // of s and reports whether all calls to f returned true. If there are
   130  // no specific terms, underIs returns the result of f(nil).
   131  func (s *_TypeSet) underIs(f func(Type) bool) bool {
   132  	if !s.hasTerms() {
   133  		return f(nil)
   134  	}
   135  	for _, t := range s.terms {
   136  		assert(t.typ != nil)
   137  		// Unalias(x) == under(x) for ~x terms
   138  		u := Unalias(t.typ)
   139  		if !t.tilde {
   140  			u = under(u)
   141  		}
   142  		if debug {
   143  			assert(Identical(u, under(u)))
   144  		}
   145  		if !f(u) {
   146  			return false
   147  		}
   148  	}
   149  	return true
   150  }
   151  
   152  // topTypeSet may be used as type set for the empty interface.
   153  var topTypeSet = _TypeSet{terms: allTermlist}
   154  
   155  // computeInterfaceTypeSet may be called with check == nil.
   156  func computeInterfaceTypeSet(check *Checker, pos token.Pos, ityp *Interface) *_TypeSet {
   157  	if ityp.tset != nil {
   158  		return ityp.tset
   159  	}
   160  
   161  	// If the interface is not fully set up yet, the type set will
   162  	// not be complete, which may lead to errors when using the
   163  	// type set (e.g. missing method). Don't compute a partial type
   164  	// set (and don't store it!), so that we still compute the full
   165  	// type set eventually. Instead, return the top type set and
   166  	// let any follow-on errors play out.
   167  	//
   168  	// TODO(gri) Consider recording when this happens and reporting
   169  	// it as an error (but only if there were no other errors so to
   170  	// to not have unnecessary follow-on errors).
   171  	if !ityp.complete {
   172  		return &topTypeSet
   173  	}
   174  
   175  	if check != nil && check.conf._Trace {
   176  		// Types don't generally have position information.
   177  		// If we don't have a valid pos provided, try to use
   178  		// one close enough.
   179  		if !pos.IsValid() && len(ityp.methods) > 0 {
   180  			pos = ityp.methods[0].pos
   181  		}
   182  
   183  		check.trace(pos, "-- type set for %s", ityp)
   184  		check.indent++
   185  		defer func() {
   186  			check.indent--
   187  			check.trace(pos, "=> %s ", ityp.typeSet())
   188  		}()
   189  	}
   190  
   191  	// An infinitely expanding interface (due to a cycle) is detected
   192  	// elsewhere (Checker.validType), so here we simply assume we only
   193  	// have valid interfaces. Mark the interface as complete to avoid
   194  	// infinite recursion if the validType check occurs later for some
   195  	// reason.
   196  	ityp.tset = &_TypeSet{terms: allTermlist} // TODO(gri) is this sufficient?
   197  
   198  	var unionSets map[*Union]*_TypeSet
   199  	if check != nil {
   200  		if check.unionTypeSets == nil {
   201  			check.unionTypeSets = make(map[*Union]*_TypeSet)
   202  		}
   203  		unionSets = check.unionTypeSets
   204  	} else {
   205  		unionSets = make(map[*Union]*_TypeSet)
   206  	}
   207  
   208  	// Methods of embedded interfaces are collected unchanged; i.e., the identity
   209  	// of a method I.m's Func Object of an interface I is the same as that of
   210  	// the method m in an interface that embeds interface I. On the other hand,
   211  	// if a method is embedded via multiple overlapping embedded interfaces, we
   212  	// don't provide a guarantee which "original m" got chosen for the embedding
   213  	// interface. See also go.dev/issue/34421.
   214  	//
   215  	// If we don't care to provide this identity guarantee anymore, instead of
   216  	// reusing the original method in embeddings, we can clone the method's Func
   217  	// Object and give it the position of a corresponding embedded interface. Then
   218  	// we can get rid of the mpos map below and simply use the cloned method's
   219  	// position.
   220  
   221  	var seen objset
   222  	var allMethods []*Func
   223  	mpos := make(map[*Func]token.Pos) // method specification or method embedding position, for good error messages
   224  	addMethod := func(pos token.Pos, m *Func, explicit bool) {
   225  		switch other := seen.insert(m); {
   226  		case other == nil:
   227  			allMethods = append(allMethods, m)
   228  			mpos[m] = pos
   229  		case explicit:
   230  			if check != nil {
   231  				err := check.newError(DuplicateDecl)
   232  				err.addf(atPos(pos), "duplicate method %s", m.name)
   233  				err.addf(atPos(mpos[other.(*Func)]), "other declaration of method %s", m.name)
   234  				err.report()
   235  			}
   236  		default:
   237  			// We have a duplicate method name in an embedded (not explicitly declared) method.
   238  			// Check method signatures after all types are computed (go.dev/issue/33656).
   239  			// If we're pre-go1.14 (overlapping embeddings are not permitted), report that
   240  			// error here as well (even though we could do it eagerly) because it's the same
   241  			// error message.
   242  			if check != nil {
   243  				check.later(func() {
   244  					if pos.IsValid() && !check.allowVersion(atPos(pos), go1_14) || !Identical(m.typ, other.Type()) {
   245  						err := check.newError(DuplicateDecl)
   246  						err.addf(atPos(pos), "duplicate method %s", m.name)
   247  						err.addf(atPos(mpos[other.(*Func)]), "other declaration of method %s", m.name)
   248  						err.report()
   249  					}
   250  				}).describef(atPos(pos), "duplicate method check for %s", m.name)
   251  			}
   252  		}
   253  	}
   254  
   255  	for _, m := range ityp.methods {
   256  		addMethod(m.pos, m, true)
   257  	}
   258  
   259  	// collect embedded elements
   260  	allTerms := allTermlist
   261  	allComparable := false
   262  	for i, typ := range ityp.embeddeds {
   263  		// The embedding position is nil for imported interfaces.
   264  		// We don't need to do version checks in those cases.
   265  		var pos token.Pos // embedding position
   266  		if ityp.embedPos != nil {
   267  			pos = (*ityp.embedPos)[i]
   268  		}
   269  		var comparable bool
   270  		var terms termlist
   271  		switch u := under(typ).(type) {
   272  		case *Interface:
   273  			// For now we don't permit type parameters as constraints.
   274  			assert(!isTypeParam(typ))
   275  			tset := computeInterfaceTypeSet(check, pos, u)
   276  			// If typ is local, an error was already reported where typ is specified/defined.
   277  			if pos.IsValid() && check != nil && check.isImportedConstraint(typ) && !check.verifyVersionf(atPos(pos), go1_18, "embedding constraint interface %s", typ) {
   278  				continue
   279  			}
   280  			comparable = tset.comparable
   281  			for _, m := range tset.methods {
   282  				addMethod(pos, m, false) // use embedding position pos rather than m.pos
   283  			}
   284  			terms = tset.terms
   285  		case *Union:
   286  			if pos.IsValid() && check != nil && !check.verifyVersionf(atPos(pos), go1_18, "embedding interface element %s", u) {
   287  				continue
   288  			}
   289  			tset := computeUnionTypeSet(check, unionSets, pos, u)
   290  			if tset == &invalidTypeSet {
   291  				continue // ignore invalid unions
   292  			}
   293  			assert(!tset.comparable)
   294  			assert(len(tset.methods) == 0)
   295  			terms = tset.terms
   296  		default:
   297  			if !isValid(u) {
   298  				continue
   299  			}
   300  			if pos.IsValid() && check != nil && !check.verifyVersionf(atPos(pos), go1_18, "embedding non-interface type %s", typ) {
   301  				continue
   302  			}
   303  			terms = termlist{{false, typ}}
   304  		}
   305  
   306  		// The type set of an interface is the intersection of the type sets of all its elements.
   307  		// Due to language restrictions, only embedded interfaces can add methods, they are handled
   308  		// separately. Here we only need to intersect the term lists and comparable bits.
   309  		allTerms, allComparable = intersectTermLists(allTerms, allComparable, terms, comparable)
   310  	}
   311  
   312  	ityp.tset.comparable = allComparable
   313  	if len(allMethods) != 0 {
   314  		sortMethods(allMethods)
   315  		ityp.tset.methods = allMethods
   316  	}
   317  	ityp.tset.terms = allTerms
   318  
   319  	return ityp.tset
   320  }
   321  
   322  // TODO(gri) The intersectTermLists function belongs to the termlist implementation.
   323  //           The comparable type set may also be best represented as a term (using
   324  //           a special type).
   325  
   326  // intersectTermLists computes the intersection of two term lists and respective comparable bits.
   327  // xcomp, ycomp are valid only if xterms.isAll() and yterms.isAll() respectively.
   328  func intersectTermLists(xterms termlist, xcomp bool, yterms termlist, ycomp bool) (termlist, bool) {
   329  	terms := xterms.intersect(yterms)
   330  	// If one of xterms or yterms is marked as comparable,
   331  	// the result must only include comparable types.
   332  	comp := xcomp || ycomp
   333  	if comp && !terms.isAll() {
   334  		// only keep comparable terms
   335  		i := 0
   336  		for _, t := range terms {
   337  			assert(t.typ != nil)
   338  			if comparable(t.typ, false /* strictly comparable */, nil, nil) {
   339  				terms[i] = t
   340  				i++
   341  			}
   342  		}
   343  		terms = terms[:i]
   344  		if !terms.isAll() {
   345  			comp = false
   346  		}
   347  	}
   348  	assert(!comp || terms.isAll()) // comparable invariant
   349  	return terms, comp
   350  }
   351  
   352  func sortMethods(list []*Func) {
   353  	sort.Sort(byUniqueMethodName(list))
   354  }
   355  
   356  func assertSortedMethods(list []*Func) {
   357  	if !debug {
   358  		panic("assertSortedMethods called outside debug mode")
   359  	}
   360  	if !sort.IsSorted(byUniqueMethodName(list)) {
   361  		panic("methods not sorted")
   362  	}
   363  }
   364  
   365  // byUniqueMethodName method lists can be sorted by their unique method names.
   366  type byUniqueMethodName []*Func
   367  
   368  func (a byUniqueMethodName) Len() int           { return len(a) }
   369  func (a byUniqueMethodName) Less(i, j int) bool { return a[i].less(&a[j].object) }
   370  func (a byUniqueMethodName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
   371  
   372  // invalidTypeSet is a singleton type set to signal an invalid type set
   373  // due to an error. It's also a valid empty type set, so consumers of
   374  // type sets may choose to ignore it.
   375  var invalidTypeSet _TypeSet
   376  
   377  // computeUnionTypeSet may be called with check == nil.
   378  // The result is &invalidTypeSet if the union overflows.
   379  func computeUnionTypeSet(check *Checker, unionSets map[*Union]*_TypeSet, pos token.Pos, utyp *Union) *_TypeSet {
   380  	if tset, _ := unionSets[utyp]; tset != nil {
   381  		return tset
   382  	}
   383  
   384  	// avoid infinite recursion (see also computeInterfaceTypeSet)
   385  	unionSets[utyp] = new(_TypeSet)
   386  
   387  	var allTerms termlist
   388  	for _, t := range utyp.terms {
   389  		var terms termlist
   390  		u := under(t.typ)
   391  		if ui, _ := u.(*Interface); ui != nil {
   392  			// For now we don't permit type parameters as constraints.
   393  			assert(!isTypeParam(t.typ))
   394  			terms = computeInterfaceTypeSet(check, pos, ui).terms
   395  		} else if !isValid(u) {
   396  			continue
   397  		} else {
   398  			if t.tilde && !Identical(t.typ, u) {
   399  				// There is no underlying type which is t.typ.
   400  				// The corresponding type set is empty.
   401  				t = nil // ∅ term
   402  			}
   403  			terms = termlist{(*term)(t)}
   404  		}
   405  		// The type set of a union expression is the union
   406  		// of the type sets of each term.
   407  		allTerms = allTerms.union(terms)
   408  		if len(allTerms) > maxTermCount {
   409  			if check != nil {
   410  				check.errorf(atPos(pos), InvalidUnion, "cannot handle more than %d union terms (implementation limitation)", maxTermCount)
   411  			}
   412  			unionSets[utyp] = &invalidTypeSet
   413  			return unionSets[utyp]
   414  		}
   415  	}
   416  	unionSets[utyp].terms = allTerms
   417  
   418  	return unionSets[utyp]
   419  }
   420  

View as plain text