Fix crash inferring constrained variadic tuples with optional elements#3943
Fix crash inferring constrained variadic tuples with optional elements#3943Andarist wants to merge 4 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
This PR ports microsoft/TypeScript#63014 as a follow-up to #2928. It adds arity guards in inferFromObjectTypes so that when inferring a [...T, ...rest] or [...rest, ...T] shaped target (where T is constrained by a fixed-size tuple) against a source tuple, inference is only performed if the source actually has enough fixed elements to support the implied arity. This prevents incorrect/spurious inferences (and crashes) when the source's fixed-element count is smaller than the constraint's fixed length—particularly common with optional elements in the constraint.
Changes:
- Guard the
[...T, ...rest]middle case withstartLength+impliedArity <= source.fixedLength. - Guard the
[...rest, ...T]middle case withendLength+impliedArity <= getEndElementCount(source, ElementFlagsFixed)and move the trailing-slice inference inside the guard. - Add a new compiler test (
inferTypesWithFixedTupleExtendsAtVariadicPosition2.ts) plus its.types,.symbols, and.errors.txtbaselines.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| internal/checker/inference.go | Adds arity guards in the two variadic+constrained-tuple inference branches |
| testdata/tests/cases/compiler/inferTypesWithFixedTupleExtendsAtVariadicPosition2.ts | New test covering many infer B extends [..] variadic tuple shapes incl. optional elements |
| testdata/baselines/reference/compiler/inferTypesWithFixedTupleExtendsAtVariadicPosition2.types | Type baseline for the new test |
| testdata/baselines/reference/compiler/inferTypesWithFixedTupleExtendsAtVariadicPosition2.symbols | Symbol baseline for the new test |
| testdata/baselines/reference/compiler/inferTypesWithFixedTupleExtendsAtVariadicPosition2.errors.txt | Errors baseline for the new test |
| @@ -712,9 +712,11 @@ func (c *Checker) inferFromObjectTypes(n *InferenceState, source *Type, target * | |||
| constraint := c.getBaseConstraintOfType(info.typeParameter) | |||
| if constraint != nil && isTupleType(constraint) && constraint.TargetTupleType().combinedFlags&ElementFlagsVariable == 0 { | |||
| impliedArity := constraint.TargetTupleType().fixedLength | |||
There was a problem hiding this comment.
fixedLength still includes optional elements. In those cases, the checker could assume it needed more fixed source elements even when fewer were guaranteed, and that led to invalid slice math and crashing
followup to #2928
ports microsoft/TypeScript#63014