Source file src/go/types/validtype.go

     1  // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
     2  // Source: ../../cmd/compile/internal/types2/validtype.go
     3  
     4  // Copyright 2022 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 "go/token"
    11  
    12  // validType verifies that the given type does not "expand" indefinitely
    13  // producing a cycle in the type graph.
    14  // (Cycles involving alias types, as in "type A = [10]A" are detected
    15  // earlier, via the objDecl cycle detection mechanism.)
    16  func (check *Checker) validType(typ *Named) {
    17  	check.validType0(nopos, typ, nil, nil)
    18  }
    19  
    20  // validType0 checks if the given type is valid. If typ is a type parameter
    21  // its value is looked up in the type argument list of the instantiated
    22  // (enclosing) type, if it exists. Otherwise the type parameter must be from
    23  // an enclosing function and can be ignored.
    24  // The nest list describes the stack (the "nest in memory") of types which
    25  // contain (or embed in the case of interfaces) other types. For instance, a
    26  // struct named S which contains a field of named type F contains (the memory
    27  // of) F in S, leading to the nest S->F. If a type appears in its own nest
    28  // (say S->F->S) we have an invalid recursive type. The path list is the full
    29  // path of named types in a cycle, it is only needed for error reporting.
    30  func (check *Checker) validType0(pos token.Pos, typ Type, nest, path []*Named) bool {
    31  	typ = Unalias(typ)
    32  
    33  	if check.conf._Trace {
    34  		if t, _ := typ.(*Named); t != nil && t.obj != nil /* obj should always exist but be conservative */ {
    35  			pos = t.obj.pos
    36  		}
    37  		check.indent++
    38  		check.trace(pos, "validType(%s) nest %v, path %v", typ, pathString(makeObjList(nest)), pathString(makeObjList(path)))
    39  		defer func() {
    40  			check.indent--
    41  		}()
    42  	}
    43  
    44  	switch t := typ.(type) {
    45  	case nil:
    46  		// We should never see a nil type but be conservative and panic
    47  		// only in debug mode.
    48  		if debug {
    49  			panic("validType0(nil)")
    50  		}
    51  
    52  	case *Array:
    53  		return check.validType0(pos, t.elem, nest, path)
    54  
    55  	case *Struct:
    56  		for _, f := range t.fields {
    57  			if !check.validType0(pos, f.typ, nest, path) {
    58  				return false
    59  			}
    60  		}
    61  
    62  	case *Union:
    63  		for _, t := range t.terms {
    64  			if !check.validType0(pos, t.typ, nest, path) {
    65  				return false
    66  			}
    67  		}
    68  
    69  	case *Interface:
    70  		for _, etyp := range t.embeddeds {
    71  			if !check.validType0(pos, etyp, nest, path) {
    72  				return false
    73  			}
    74  		}
    75  
    76  	case *Named:
    77  		// TODO(gri) The optimization below is incorrect (see go.dev/issue/65711):
    78  		//           in that issue `type A[P any] [1]P` is a valid type on its own
    79  		//           and the (uninstantiated) A is recorded in check.valids. As a
    80  		//           consequence, when checking the remaining declarations, which
    81  		//           are not valid, the validity check ends prematurely because A
    82  		//           is considered valid, even though its validity depends on the
    83  		//           type argument provided to it.
    84  		//
    85  		//           A correct optimization is important for pathological cases.
    86  		//           Keep code around for reference until we found an optimization.
    87  		//
    88  		// // Exit early if we already know t is valid.
    89  		// // This is purely an optimization but it prevents excessive computation
    90  		// // times in pathological cases such as testdata/fixedbugs/issue6977.go.
    91  		// // (Note: The valids map could also be allocated locally, once for each
    92  		// // validType call.)
    93  		// if check.valids.lookup(t) != nil {
    94  		// 	break
    95  		// }
    96  
    97  		// If the current type t is also found in nest, (the memory of) t is
    98  		// embedded in itself, indicating an invalid recursive type.
    99  		for _, e := range nest {
   100  			if Identical(e, t) {
   101  				// We have a cycle. If t != t.Origin() then t is an instance of
   102  				// the generic type t.Origin(). Because t is in the nest, t must
   103  				// occur within the definition (RHS) of the generic type t.Origin(),
   104  				// directly or indirectly, after expansion of the RHS.
   105  				// Therefore t.Origin() must be invalid, no matter how it is
   106  				// instantiated since the instantiation t of t.Origin() happens
   107  				// inside t.Origin()'s RHS and thus is always the same and always
   108  				// present.
   109  				// Therefore we can mark the underlying of both t and t.Origin()
   110  				// as invalid. If t is not an instance of a generic type, t and
   111  				// t.Origin() are the same.
   112  				// Furthermore, because we check all types in a package for validity
   113  				// before type checking is complete, any exported type that is invalid
   114  				// will have an invalid underlying type and we can't reach here with
   115  				// such a type (invalid types are excluded above).
   116  				// Thus, if we reach here with a type t, both t and t.Origin() (if
   117  				// different in the first place) must be from the current package;
   118  				// they cannot have been imported.
   119  				// Therefore it is safe to change their underlying types; there is
   120  				// no chance for a race condition (the types of the current package
   121  				// are not yet available to other goroutines).
   122  				assert(t.obj.pkg == check.pkg)
   123  				assert(t.Origin().obj.pkg == check.pkg)
   124  
   125  				// let t become invalid when it is unpacked
   126  				t.Origin().fromRHS = Typ[Invalid]
   127  
   128  				// Find the starting point of the cycle and report it.
   129  				// Because each type in nest must also appear in path (see invariant below),
   130  				// type t must be in path since it was found in nest. But not every type in path
   131  				// is in nest. Specifically t may appear in path with an earlier index than the
   132  				// index of t in nest. Search again.
   133  				for start, p := range path {
   134  					if Identical(p, t) {
   135  						check.cycleError(makeObjList(path[start:]), 0)
   136  						return false
   137  					}
   138  				}
   139  				panic("cycle start not found")
   140  			}
   141  		}
   142  
   143  		// No cycle was found. Check the RHS of t.
   144  		// Every type added to nest is also added to path; thus every type that is in nest
   145  		// must also be in path (invariant). But not every type in path is in nest, since
   146  		// nest may be pruned (see below, *TypeParam case).
   147  		t.Origin().unpack()
   148  		if !check.validType0(pos, t.Origin().rhs(), append(nest, t), append(path, t)) {
   149  			return false
   150  		}
   151  
   152  		// see TODO above
   153  		// check.valids.add(t) // t is valid
   154  
   155  	case *TypeParam:
   156  		// A type parameter stands for the type (argument) it was instantiated with.
   157  		// Check the corresponding type argument for validity if we are in an
   158  		// instantiated type.
   159  		if d := len(nest) - 1; d >= 0 {
   160  			inst := nest[d] // the type instance
   161  			// Find the corresponding type argument for the type parameter
   162  			// and proceed with checking that type argument.
   163  			for i, tparam := range inst.TypeParams().list() {
   164  				// The type parameter and type argument lists should
   165  				// match in length but be careful in case of errors.
   166  				if t == tparam && i < inst.TypeArgs().Len() {
   167  					targ := inst.TypeArgs().At(i)
   168  					// The type argument must be valid in the enclosing
   169  					// type (where inst was instantiated), hence we must
   170  					// check targ's validity in the type nest excluding
   171  					// the current (instantiated) type (see the example
   172  					// at the end of this file).
   173  					// For error reporting we keep the full path.
   174  					res := check.validType0(pos, targ, nest[:d], path)
   175  					// The check.validType0 call with nest[:d] may have
   176  					// overwritten the entry at the current depth d.
   177  					// Restore the entry (was issue go.dev/issue/66323).
   178  					nest[d] = inst
   179  					return res
   180  				}
   181  			}
   182  		}
   183  	}
   184  
   185  	return true
   186  }
   187  
   188  // makeObjList returns the list of type name objects for the given
   189  // list of named types.
   190  func makeObjList(tlist []*Named) []Object {
   191  	olist := make([]Object, len(tlist))
   192  	for i, t := range tlist {
   193  		olist[i] = t.obj
   194  	}
   195  	return olist
   196  }
   197  
   198  // Here is an example illustrating why we need to exclude the
   199  // instantiated type from nest when evaluating the validity of
   200  // a type parameter. Given the declarations
   201  //
   202  //   var _ A[A[string]]
   203  //
   204  //   type A[P any] struct { _ B[P] }
   205  //   type B[P any] struct { _ P }
   206  //
   207  // we want to determine if the type A[A[string]] is valid.
   208  // We start evaluating A[A[string]] outside any type nest:
   209  //
   210  //   A[A[string]]
   211  //         nest =
   212  //         path =
   213  //
   214  // The RHS of A is now evaluated in the A[A[string]] nest:
   215  //
   216  //   struct{_ B[P₁]}
   217  //         nest = A[A[string]]
   218  //         path = A[A[string]]
   219  //
   220  // The struct has a single field of type B[P₁] with which
   221  // we continue:
   222  //
   223  //   B[P₁]
   224  //         nest = A[A[string]]
   225  //         path = A[A[string]]
   226  //
   227  //   struct{_ P₂}
   228  //         nest = A[A[string]]->B[P]
   229  //         path = A[A[string]]->B[P]
   230  //
   231  // Eventually we reach the type parameter P of type B (P₂):
   232  //
   233  //   P₂
   234  //         nest = A[A[string]]->B[P]
   235  //         path = A[A[string]]->B[P]
   236  //
   237  // The type argument for P of B is the type parameter P of A (P₁).
   238  // It must be evaluated in the type nest that existed when B was
   239  // instantiated:
   240  //
   241  //   P₁
   242  //         nest = A[A[string]]        <== type nest at B's instantiation time
   243  //         path = A[A[string]]->B[P]
   244  //
   245  // If we'd use the current nest it would correspond to the path
   246  // which will be wrong as we will see shortly. P's type argument
   247  // is A[string], which again must be evaluated in the type nest
   248  // that existed when A was instantiated with A[string]. That type
   249  // nest is empty:
   250  //
   251  //   A[string]
   252  //         nest =                     <== type nest at A's instantiation time
   253  //         path = A[A[string]]->B[P]
   254  //
   255  // Evaluation then proceeds as before for A[string]:
   256  //
   257  //   struct{_ B[P₁]}
   258  //         nest = A[string]
   259  //         path = A[A[string]]->B[P]->A[string]
   260  //
   261  // Now we reach B[P] again. If we had not adjusted nest, it would
   262  // correspond to path, and we would find B[P] in nest, indicating
   263  // a cycle, which would clearly be wrong since there's no cycle in
   264  // A[string]:
   265  //
   266  //   B[P₁]
   267  //         nest = A[string]
   268  //         path = A[A[string]]->B[P]->A[string]  <== path contains B[P]!
   269  //
   270  // But because we use the correct type nest, evaluation proceeds without
   271  // errors and we get the evaluation sequence:
   272  //
   273  //   struct{_ P₂}
   274  //         nest = A[string]->B[P]
   275  //         path = A[A[string]]->B[P]->A[string]->B[P]
   276  //   P₂
   277  //         nest = A[string]->B[P]
   278  //         path = A[A[string]]->B[P]->A[string]->B[P]
   279  //   P₁
   280  //         nest = A[string]
   281  //         path = A[A[string]]->B[P]->A[string]->B[P]
   282  //   string
   283  //         nest =
   284  //         path = A[A[string]]->B[P]->A[string]->B[P]
   285  //
   286  // At this point we're done and A[A[string]] and is valid.
   287  

View as plain text