Skip to content

go/types: NewSignatureType mutates its TypeParams, and panics unless they are new #67293

@adonovan

Description

@adonovan

If a client of go/types uses NewSignatureType to create a variation on an existing type, it is an error to pass the TypeParams of the existing function, as bindTParams will update their index field, and panic if the field has already been set.

I think there are two separate issues here:

  1. NewSignatureType mutates its operands. It's not at all obvious that it does this; if this is unavoidable, it should be documented.
  2. If the same type parameters are re-used, their indices will be the same. In that case, bindTParams should probably just skip the update since it is unnecessary, rather than panic unnecessarily.

Offending client code:

		// Emit signature.
		//
		// Elide parameters after the third one.
		// WriteSignature is too complex to fork, so we replace
		// parameters 4+ with "invalid type", format,
		// then post-process the string.
		if sig.Params().Len() > 3 {
			sig = types.NewSignatureType(
				sig.Recv(),
				typesSeqToSlice[*types.TypeParam](sig.RecvTypeParams()),
				typesSeqToSlice[*types.TypeParam](sig.TypeParams()),
				types.NewTuple(append(
					typesSeqToSlice[*types.Var](sig.Params())[:3],
					types.NewVar(0, nil, "", types.Typ[types.Invalid]))...),
				sig.Results(),
				false) // any final ...T parameter is truncated
		}
		types.WriteSignature(&buf, sig, pkgRelative)

(Gopls uses NewSignatureType to truncate long parameter lists so that they can be formatted using TypeString or WriteSignature. If the machinery of TypeString provided more control over the traversal this would not be necessary.)

@gri @findleyr

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions