github.com/AndrienkoAleksandr/go@v0.0.19/src/go/types/typeset.go (about)

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