src/go/types/infer.go GO 798 lines View on github.com → Search inside
1// Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.2// Source: ../../cmd/compile/internal/types2/infer.go34// Copyright 2018 The Go Authors. All rights reserved.5// Use of this source code is governed by a BSD-style6// license that can be found in the LICENSE file.78// This file implements type parameter inference.910package types1112import (13	"fmt"14	"go/token"15	"slices"16	"strings"17)1819// If enableReverseTypeInference is set, uninstantiated and20// partially instantiated generic functions may be assigned21// (incl. returned) to variables of function type and type22// inference will attempt to infer the missing type arguments.23// Available with go1.21.24const enableReverseTypeInference = true // disable for debugging2526// infer attempts to infer the complete set of type arguments for generic function instantiation/call27// based on the given type parameters tparams, type arguments targs, function parameters params, and28// function arguments args, if any. There must be at least one type parameter, no more type arguments29// than type parameters, and params and args must match in number (incl. zero).30// If reverse is set, an error message's contents are reversed for a better error message for some31// errors related to reverse type inference (where the function call is synthetic).32// If successful, infer returns the complete list of given and inferred type arguments, one for each33// type parameter. Otherwise the result is nil. Errors are reported through the err parameter.34// Note: infer may fail (return nil) due to invalid args operands without reporting additional errors.35func (check *Checker) infer(posn positioner, tparams []*TypeParam, targs []Type, params *Tuple, args []*operand, reverse bool, err *error_) (inferred []Type) {36	// Don't verify result conditions if there's no error handler installed:37	// in that case, an error leads to an exit panic and the result value may38	// be incorrect. But in that case it doesn't matter because callers won't39	// be able to use it either.40	if check.conf.Error != nil {41		defer func() {42			assert(inferred == nil || len(inferred) == len(tparams) && !slices.Contains(inferred, nil))43		}()44	}4546	if traceInference {47		check.dump("== infer : %s%s ➞ %s", tparams, params, targs) // aligned with rename print below48		defer func() {49			check.dump("=> %s ➞ %s\n", tparams, inferred)50		}()51	}5253	// There must be at least one type parameter, and no more type arguments than type parameters.54	n := len(tparams)55	assert(n > 0 && len(targs) <= n)5657	// Parameters and arguments must match in number.58	assert(params.Len() == len(args))5960	// If we already have all type arguments, we're done.61	if len(targs) == n && !slices.Contains(targs, nil) {62		return targs63	}6465	// If we have invalid (ordinary) arguments, an error was reported before.66	// Avoid additional inference errors and exit early (go.dev/issue/60434).67	for _, arg := range args {68		if !arg.isValid() {69			return nil70		}71	}7273	// Make sure we have a "full" list of type arguments, some of which may74	// be nil (unknown). Make a copy so as to not clobber the incoming slice.75	if len(targs) < n {76		targs2 := make([]Type, n)77		copy(targs2, targs)78		targs = targs279	}80	// len(targs) == n8182	// Continue with the type arguments we have. Avoid matching generic83	// parameters that already have type arguments against function arguments:84	// It may fail because matching uses type identity while parameter passing85	// uses assignment rules. Instantiate the parameter list with the type86	// arguments we have, and continue with that parameter list.8788	// Substitute type arguments for their respective type parameters in params,89	// if any. Note that nil targs entries are ignored by check.subst.90	// We do this for better error messages; it's not needed for correctness.91	// For instance, given:92	//93	//   func f[P, Q any](P, Q) {}94	//95	//   func _(s string) {96	//           f[int](s, s) // ERROR97	//   }98	//99	// With substitution, we get the error:100	//   "cannot use s (variable of type string) as int value in argument to f[int]"101	//102	// Without substitution we get the (worse) error:103	//   "type string of s does not match inferred type int for P"104	// even though the type int was provided (not inferred) for P.105	//106	// TODO(gri) We might be able to finesse this in the error message reporting107	//           (which only happens in case of an error) and then avoid doing108	//           the substitution (which always happens).109	if params.Len() > 0 {110		smap := makeSubstMap(tparams, targs)111		params = check.subst(nopos, params, smap, nil, check.context()).(*Tuple)112	}113114	// Unify parameter and argument types for generic parameters with typed arguments115	// and collect the indices of generic parameters with untyped arguments.116	// Terminology: generic parameter = function parameter with a type-parameterized type117	u := newUnifier(check, tparams, targs, check.allowVersion(go1_21))118119	errorf := func(tpar, targ Type, arg *operand) {120		// provide a better error message if we can121		targs := u.inferred(tparams)122		if targs[0] == nil {123			// The first type parameter couldn't be inferred.124			// If none of them could be inferred, don't try125			// to provide the inferred type in the error msg.126			allFailed := true127			for _, targ := range targs {128				if targ != nil {129					allFailed = false130					break131				}132			}133			if allFailed {134				err.addf(arg, "type %s of %s does not match %s (cannot infer %s)", targ, arg.expr, tpar, typeParamsString(tparams))135				return136			}137		}138		smap := makeSubstMap(tparams, targs)139		// TODO(gri): pass a poser here, rather than arg.Pos().140		inferred := check.subst(arg.Pos(), tpar, smap, nil, check.context())141		// CannotInferTypeArgs indicates a failure of inference, though the actual142		// error may be better attributed to a user-provided type argument (hence143		// InvalidTypeArg). We can't differentiate these cases, so fall back on144		// the more general CannotInferTypeArgs.145		if inferred != tpar {146			if reverse {147				err.addf(arg, "inferred type %s for %s does not match type %s of %s", inferred, tpar, targ, arg.expr)148			} else {149				err.addf(arg, "type %s of %s does not match inferred type %s for %s", targ, arg.expr, inferred, tpar)150			}151		} else {152			err.addf(arg, "type %s of %s does not match %s", targ, arg.expr, tpar)153		}154	}155156	// indices of generic parameters with untyped arguments, for later use157	var untyped []int158159	// --- 1 ---160	// use information from function arguments161162	if traceInference {163		u.tracef("== function parameters: %s", params)164		u.tracef("-- function arguments : %s", args)165	}166167	for i, arg := range args {168		if !arg.isValid() {169			// An error was reported earlier. Ignore this arg170			// and continue, we may still be able to infer all171			// targs resulting in fewer follow-on errors.172			// TODO(gri) determine if we still need this check173			continue174		}175		par := params.At(i)176		if isParameterized(tparams, par.typ) || isParameterized(tparams, arg.typ()) {177			// Function parameters are always typed. Arguments may be untyped.178			// Collect the indices of untyped arguments and handle them later.179			if isTyped(arg.typ()) {180				if !u.unify(par.typ, arg.typ(), assign) {181					errorf(par.typ, arg.typ(), arg)182					return nil183				}184			} else if _, ok := par.typ.(*TypeParam); ok && !arg.isNil() {185				// Since default types are all basic (i.e., non-composite) types, an186				// untyped argument will never match a composite parameter type; the187				// only parameter type it can possibly match against is a *TypeParam.188				// Thus, for untyped arguments we only need to look at parameter types189				// that are single type parameters.190				// Also, untyped nils don't have a default type and can be ignored.191				// Finally, it's not possible to have an alias type denoting a type192				// parameter declared by the current function and use it in the same193				// function signature; hence we don't need to Unalias before the194				// .(*TypeParam) type assertion above.195				untyped = append(untyped, i)196			}197		}198	}199200	if traceInference {201		inferred := u.inferred(tparams)202		u.tracef("=> %s ➞ %s\n", tparams, inferred)203	}204205	// --- 2 ---206	// use information from type parameter constraints207208	if traceInference {209		u.tracef("== type parameters: %s", tparams)210	}211212	// Unify type parameters with their constraints as long213	// as progress is being made.214	//215	// This is an O(n^2) algorithm where n is the number of216	// type parameters: if there is progress, at least one217	// type argument is inferred per iteration, and we have218	// a doubly nested loop.219	//220	// In practice this is not a problem because the number221	// of type parameters tends to be very small (< 5 or so).222	// (It should be possible for unification to efficiently223	// signal newly inferred type arguments; then the loops224	// here could handle the respective type parameters only,225	// but that will come at a cost of extra complexity which226	// may not be worth it.)227	for i := 0; ; i++ {228		nn := u.unknowns()229		if traceInference {230			if i > 0 {231				fmt.Println()232			}233			u.tracef("-- iteration %d", i)234		}235236		for _, tpar := range tparams {237			tx := u.at(tpar)238			core, single := coreTerm(tpar)239			if traceInference {240				u.tracef("-- type parameter %s = %s: core(%s) = %s, single = %v", tpar, tx, tpar, core, single)241			}242243			// If the type parameter's constraint has a core term (i.e., a core type with tilde information)244			// try to unify the type parameter with that core type.245			if core != nil {246				// A type parameter can be unified with its constraint's core type in two cases.247				switch {248				case tx != nil:249					if traceInference {250						u.tracef("-> unify type parameter %s (type %s) with constraint core type %s", tpar, tx, core.typ)251					}252					// The corresponding type argument tx is known. There are 2 cases:253					// 1) If the core type has a tilde, per spec requirement for tilde254					//    elements, the core type is an underlying (literal) type.255					//    And because of the tilde, the underlying type of tx must match256					//    against the core type.257					//    But because unify automatically matches a defined type against258					//    an underlying literal type, we can simply unify tx with the259					//    core type.260					// 2) If the core type doesn't have a tilde, we also must unify tx261					//    with the core type.262					if !u.unify(tx, core.typ, 0) {263						// TODO(gri) Type parameters that appear in the constraint and264						//           for which we have type arguments inferred should265						//           use those type arguments for a better error message.266						err.addf(posn, "%s (type %s) does not satisfy %s", tpar, tx, tpar.Constraint())267						return nil268					}269				case single && !core.tilde:270					if traceInference {271						u.tracef("-> set type parameter %s to constraint's common underlying type %s", tpar, core.typ)272					}273					// The corresponding type argument tx is unknown and the core term274					// describes a single specific type and no tilde.275					// In this case the type argument must be that single type; set it.276					u.set(tpar, core.typ)277				}278			}279280			// Independent of whether there is a core term, if the type argument tx is known281			// it must implement the methods of the type constraint, possibly after unification282			// of the relevant method signatures, otherwise tx cannot satisfy the constraint.283			// This unification step may provide additional type arguments.284			//285			// Note: The type argument tx may be known but contain references to other type286			// parameters (i.e., tx may still be parameterized).287			// In this case the methods of tx don't correctly reflect the final method set288			// and we may get a missing method error below. Skip this step in this case.289			//290			// TODO(gri) We should be able continue even with a parameterized tx if we add291			// a simplify step beforehand (see below). This will require factoring out the292			// simplify phase so we can call it from here.293			if tx != nil && !isParameterized(tparams, tx) {294				if traceInference {295					u.tracef("-> unify type parameter %s (type %s) methods with constraint methods", tpar, tx)296				}297				// TODO(gri) Now that unification handles interfaces, this code can298				//           be reduced to calling u.unify(tx, tpar.iface(), assign)299				//           (which will compare signatures exactly as we do below).300				//           We leave it as is for now because missingMethod provides301				//           a failure cause which allows for a better error message.302				//           Eventually, unify should return an error with cause.303				var cause string304				constraint := tpar.iface()305				if !check.hasAllMethods(tx, constraint, true, func(x, y Type) bool { return u.unify(x, y, exact) }, &cause) {306					// TODO(gri) better error message (see TODO above)307					err.addf(posn, "%s (type %s) does not satisfy %s %s", tpar, tx, tpar.Constraint(), cause)308					return nil309				}310			}311		}312313		if u.unknowns() == nn {314			break // no progress315		}316	}317318	if traceInference {319		inferred := u.inferred(tparams)320		u.tracef("=> %s ➞ %s\n", tparams, inferred)321	}322323	// --- 3 ---324	// use information from untyped constants325326	if traceInference {327		u.tracef("== untyped arguments: %v", untyped)328	}329330	// Some generic parameters with untyped arguments may have been given a type by now.331	// Collect all remaining parameters that don't have a type yet and determine the332	// maximum untyped type for each of those parameters, if possible.333	var maxUntyped map[*TypeParam]Type // lazily allocated (we may not need it)334	for _, index := range untyped {335		tpar := params.At(index).typ.(*TypeParam) // is type parameter (no alias) by construction of untyped336		if u.at(tpar) == nil {337			arg := args[index] // arg corresponding to tpar338			if maxUntyped == nil {339				maxUntyped = make(map[*TypeParam]Type)340			}341			max := maxUntyped[tpar]342			if max == nil {343				max = arg.typ()344			} else {345				m := maxType(max, arg.typ())346				if m == nil {347					err.addf(arg, "mismatched types %s and %s (cannot infer %s)", max, arg.typ(), tpar)348					return nil349				}350				max = m351			}352			maxUntyped[tpar] = max353		}354	}355	// maxUntyped contains the maximum untyped type for each type parameter356	// which doesn't have a type yet. Set the respective default types.357	for tpar, typ := range maxUntyped {358		d := Default(typ)359		assert(isTyped(d))360		u.set(tpar, d)361	}362363	// --- simplify ---364365	// u.inferred(tparams) now contains the incoming type arguments plus any additional type366	// arguments which were inferred. The inferred non-nil entries may still contain367	// references to other type parameters found in constraints.368	// For instance, for [A any, B interface{ []C }, C interface{ *A }], if A == int369	// was given, unification produced the type list [int, []C, *A]. We eliminate the370	// remaining type parameters by substituting the type parameters in this type list371	// until nothing changes anymore.372	inferred = u.inferred(tparams)373	if debug {374		for i, targ := range targs {375			assert(targ == nil || inferred[i] == targ)376		}377	}378379	// The data structure of each (provided or inferred) type represents a graph, where380	// each node corresponds to a type and each (directed) vertex points to a component381	// type. The substitution process described above repeatedly replaces type parameter382	// nodes in these graphs with the graphs of the types the type parameters stand for,383	// which creates a new (possibly bigger) graph for each type.384	// The substitution process will not stop if the replacement graph for a type parameter385	// also contains that type parameter.386	// For instance, for [A interface{ *A }], without any type argument provided for A,387	// unification produces the type list [*A]. Substituting A in *A with the value for388	// A will lead to infinite expansion by producing [**A], [****A], [********A], etc.,389	// because the graph A -> *A has a cycle through A.390	// Generally, cycles may occur across multiple type parameters and inferred types391	// (for instance, consider [P interface{ *Q }, Q interface{ func(P) }]).392	// We eliminate cycles by walking the graphs for all type parameters. If a cycle393	// through a type parameter is detected, killCycles nils out the respective type394	// (in the inferred list) which kills the cycle, and marks the corresponding type395	// parameter as not inferred.396	//397	// TODO(gri) If useful, we could report the respective cycle as an error. We don't398	//           do this now because type inference will fail anyway, and furthermore,399	//           constraints with cycles of this kind cannot currently be satisfied by400	//           any user-supplied type. But should that change, reporting an error401	//           would be wrong.402	killCycles(tparams, inferred)403404	// dirty tracks the indices of all types that may still contain type parameters.405	// We know that nil type entries and entries corresponding to provided (non-nil)406	// type arguments are clean, so exclude them from the start.407	var dirty []int408	for i, typ := range inferred {409		if typ != nil && (i >= len(targs) || targs[i] == nil) {410			dirty = append(dirty, i)411		}412	}413414	for len(dirty) > 0 {415		if traceInference {416			u.tracef("-- simplify %s ➞ %s", tparams, inferred)417		}418		// TODO(gri) Instead of creating a new substMap for each iteration,419		// provide an update operation for substMaps and only change when420		// needed. Optimization.421		smap := makeSubstMap(tparams, inferred)422		n := 0423		for _, index := range dirty {424			t0 := inferred[index]425			if t1 := check.subst(nopos, t0, smap, nil, check.context()); t1 != t0 {426				// t0 was simplified to t1.427				// If t0 was a generic function, but the simplified signature t1 does428				// not contain any type parameters anymore, the function is not generic429				// anymore. Remove its type parameters. (go.dev/issue/59953)430				// Note that if t0 was a signature, t1 must be a signature, and t1431				// can only be a generic signature if it originated from a generic432				// function argument. Those signatures are never defined types and433				// thus there is no need to call Underlying below.434				// TODO(gri) Consider doing this in Checker.subst.435				//           Then this would fall out automatically here and also436				//           in instantiation (where we also explicitly nil out437				//           type parameters).438				if sig, _ := t1.(*Signature); sig != nil && sig.TypeParams().Len() > 0 && !isParameterized(tparams, sig) {439					sig.tparams = nil440				}441				inferred[index] = t1442				dirty[n] = index443				n++444			}445		}446		dirty = dirty[:n]447	}448449	// Once nothing changes anymore, we may still have type parameters left;450	// e.g., a constraint with core type *P may match a type parameter Q but451	// we don't have any type arguments to fill in for *P or Q (go.dev/issue/45548).452	// Don't let such inferences escape; instead treat them as unresolved.453	for i, typ := range inferred {454		if typ == nil || isParameterized(tparams, typ) {455			obj := tparams[i].obj456			err.addf(posn, "cannot infer %s (declared at %v)", obj.name, obj.pos)457			return nil458		}459	}460461	return462}463464// renameTParams renames the type parameters in the given type such that each type465// parameter is given a new identity. renameTParams returns the new type parameters466// and updated type. If the result type is unchanged from the argument type, none467// of the type parameters in tparams occurred in the type.468// If typ is a generic function, type parameters held with typ are not changed and469// must be updated separately if desired.470// The positions is only used for debug traces.471func (check *Checker) renameTParams(pos token.Pos, tparams []*TypeParam, typ Type) ([]*TypeParam, Type) {472	// For the purpose of type inference we must differentiate type parameters473	// occurring in explicit type or value function arguments from the type474	// parameters we are solving for via unification because they may be the475	// same in self-recursive calls:476	//477	//   func f[P constraint](x P) {478	//           f(x)479	//   }480	//481	// In this example, without type parameter renaming, the P used in the482	// instantiation f[P] has the same pointer identity as the P we are trying483	// to solve for through type inference. This causes problems for type484	// unification. Because any such self-recursive call is equivalent to485	// a mutually recursive call, type parameter renaming can be used to486	// create separate, disentangled type parameters. The above example487	// can be rewritten into the following equivalent code:488	//489	//   func f[P constraint](x P) {490	//           f2(x)491	//   }492	//493	//   func f2[P2 constraint](x P2) {494	//           f(x)495	//   }496	//497	// Type parameter renaming turns the first example into the second498	// example by renaming the type parameter P into P2.499	if len(tparams) == 0 {500		return nil, typ // nothing to do501	}502503	tparams2 := make([]*TypeParam, len(tparams))504	for i, tparam := range tparams {505		tname := NewTypeName(tparam.Obj().Pos(), tparam.Obj().Pkg(), tparam.Obj().Name(), nil)506		tparams2[i] = NewTypeParam(tname, nil)507		tparams2[i].index = tparam.index // == i508	}509510	renameMap := makeRenameMap(tparams, tparams2)511	for i, tparam := range tparams {512		tparams2[i].bound = check.subst(pos, tparam.bound, renameMap, nil, check.context())513	}514515	return tparams2, check.subst(pos, typ, renameMap, nil, check.context())516}517518// typeParamsString produces a string containing all the type parameter names519// in list suitable for human consumption.520func typeParamsString(list []*TypeParam) string {521	// common cases522	n := len(list)523	switch n {524	case 0:525		return ""526	case 1:527		return list[0].obj.name528	case 2:529		return list[0].obj.name + " and " + list[1].obj.name530	}531532	// general case (n > 2)533	var buf strings.Builder534	for i, tname := range list[:n-1] {535		if i > 0 {536			buf.WriteString(", ")537		}538		buf.WriteString(tname.obj.name)539	}540	buf.WriteString(", and ")541	buf.WriteString(list[n-1].obj.name)542	return buf.String()543}544545// isParameterized reports whether typ contains any of the type parameters of tparams.546// If typ is a generic function, isParameterized ignores the type parameter declarations;547// it only considers the signature proper (incoming and result parameters).548func isParameterized(tparams []*TypeParam, typ Type) bool {549	w := tpWalker{550		tparams: tparams,551		seen:    make(map[Type]bool),552	}553	return w.isParameterized(typ)554}555556type tpWalker struct {557	tparams []*TypeParam558	seen    map[Type]bool559}560561func (w *tpWalker) isParameterized(typ Type) (res bool) {562	// detect cycles563	if x, ok := w.seen[typ]; ok {564		return x565	}566	w.seen[typ] = false567	defer func() {568		w.seen[typ] = res569	}()570571	switch t := typ.(type) {572	case *Basic:573		// nothing to do574575	case *Alias:576		return w.isParameterized(Unalias(t))577578	case *Array:579		return w.isParameterized(t.elem)580581	case *Slice:582		return w.isParameterized(t.elem)583584	case *Struct:585		return w.varList(t.fields)586587	case *Pointer:588		return w.isParameterized(t.base)589590	case *Tuple:591		// This case does not occur from within isParameterized592		// because tuples only appear in signatures where they593		// are handled explicitly. But isParameterized is also594		// called by Checker.callExpr with a function result tuple595		// if instantiation failed (go.dev/issue/59890).596		return t != nil && w.varList(t.vars)597598	case *Signature:599		// t.tparams may not be nil if we are looking at a signature600		// of a generic function type (or an interface method) that is601		// part of the type we're testing. We don't care about these type602		// parameters.603		// Similarly, the receiver of a method may declare (rather than604		// use) type parameters, we don't care about those either.605		// Thus, we only need to look at the input and result parameters.606		return t.params != nil && w.varList(t.params.vars) || t.results != nil && w.varList(t.results.vars)607608	case *Interface:609		tset := t.typeSet()610		for _, m := range tset.methods {611			if w.isParameterized(m.typ) {612				return true613			}614		}615		return tset.is(func(t *term) bool {616			return t != nil && w.isParameterized(t.typ)617		})618619	case *Map:620		return w.isParameterized(t.key) || w.isParameterized(t.elem)621622	case *Chan:623		return w.isParameterized(t.elem)624625	case *Named:626		for _, t := range t.TypeArgs().list() {627			if w.isParameterized(t) {628				return true629			}630		}631632	case *TypeParam:633		return slices.Index(w.tparams, t) >= 0634635	default:636		panic(fmt.Sprintf("unexpected %T", typ))637	}638639	return false640}641642func (w *tpWalker) varList(list []*Var) bool {643	for _, v := range list {644		if w.isParameterized(v.typ) {645			return true646		}647	}648	return false649}650651// If the type parameter has a single specific type S, coreTerm returns (S, true).652// Otherwise, if tpar has a core type T, it returns a term corresponding to that653// core type and false. In that case, if any term of tpar has a tilde, the core654// term has a tilde. In all other cases coreTerm returns (nil, false).655func coreTerm(tpar *TypeParam) (*term, bool) {656	n := 0657	var single *term // valid if n == 1658	var tilde bool659	tpar.is(func(t *term) bool {660		if t == nil {661			assert(n == 0)662			return false // no terms663		}664		n++665		single = t666		if t.tilde {667			tilde = true668		}669		return true670	})671	if n == 1 {672		if debug {673			u, _ := commonUnder(tpar, nil)674			assert(single.typ.Underlying() == u)675		}676		return single, true677	}678	if typ, _ := commonUnder(tpar, nil); typ != nil {679		// A core type is always an underlying type.680		// If any term of tpar has a tilde, we don't681		// have a precise core type and we must return682		// a tilde as well.683		return &term{tilde, typ}, false684	}685	return nil, false686}687688// killCycles walks through the given type parameters and looks for cycles689// created by type parameters whose inferred types refer back to that type690// parameter, either directly or indirectly. If such a cycle is detected,691// it is killed by setting the corresponding inferred type to nil.692//693// TODO(gri) Determine if we can simply abort inference as soon as we have694// found a single cycle.695func killCycles(tparams []*TypeParam, inferred []Type) {696	w := cycleFinder{tparams, inferred, make(map[Type]bool)}697	for _, t := range tparams {698		w.typ(t) // t != nil699	}700}701702type cycleFinder struct {703	tparams  []*TypeParam704	inferred []Type705	seen     map[Type]bool706}707708func (w *cycleFinder) typ(typ Type) {709	typ = Unalias(typ)710	if w.seen[typ] {711		// We have seen typ before. If it is one of the type parameters712		// in w.tparams, iterative substitution will lead to infinite expansion.713		// Nil out the corresponding type which effectively kills the cycle.714		if tpar, _ := typ.(*TypeParam); tpar != nil {715			if i := slices.Index(w.tparams, tpar); i >= 0 {716				// cycle through tpar717				w.inferred[i] = nil718			}719		}720		// If we don't have one of our type parameters, the cycle is due721		// to an ordinary recursive type and we can just stop walking it.722		return723	}724	w.seen[typ] = true725	defer delete(w.seen, typ)726727	switch t := typ.(type) {728	case *Basic:729		// nothing to do730731	// *Alias:732	//      This case should not occur because of Unalias(typ) at the top.733734	case *Array:735		w.typ(t.elem)736737	case *Slice:738		w.typ(t.elem)739740	case *Struct:741		w.varList(t.fields)742743	case *Pointer:744		w.typ(t.base)745746	// case *Tuple:747	//      This case should not occur because tuples only appear748	//      in signatures where they are handled explicitly.749750	case *Signature:751		if t.params != nil {752			w.varList(t.params.vars)753		}754		if t.results != nil {755			w.varList(t.results.vars)756		}757758	case *Union:759		for _, t := range t.terms {760			w.typ(t.typ)761		}762763	case *Interface:764		for _, m := range t.methods {765			w.typ(m.typ)766		}767		for _, t := range t.embeddeds {768			w.typ(t)769		}770771	case *Map:772		w.typ(t.key)773		w.typ(t.elem)774775	case *Chan:776		w.typ(t.elem)777778	case *Named:779		for _, tpar := range t.TypeArgs().list() {780			w.typ(tpar)781		}782783	case *TypeParam:784		if i := slices.Index(w.tparams, t); i >= 0 && w.inferred[i] != nil {785			w.typ(w.inferred[i])786		}787788	default:789		panic(fmt.Sprintf("unexpected %T", typ))790	}791}792793func (w *cycleFinder) varList(list []*Var) {794	for _, v := range list {795		w.typ(v.typ)796	}797}

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.