...

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

Documentation: cmd/compile/internal/types2

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

View as plain text