From e3fe3914ad308c4af73cd55359b952d1df7e44f7 Mon Sep 17 00:00:00 2001 From: magic-akari Date: Sun, 15 Nov 2026 20:09:44 +0800 Subject: [PATCH 1/4] Reject incomplete type arguments during expression speculation Propagate structural failures during speculative type parsing while preserving recoverable diagnostics on recognized types. This lets typed arrows and nested relational expressions fall back to expression parsing. Add TS/TSX compiler baselines and focused parser state rollback tests. --- tsc/internal/parser/parser.go | 676 +++++++++++----- tsc/internal/parser/type_parser.go | 125 +++ tsc/internal/parser/type_parser_test.go | 49 ++ ...typeArgumentSpeculationRecovery.errors.txt | 204 +++++ .../typeArgumentSpeculationRecovery.js | 181 +++++ .../typeArgumentSpeculationRecovery.symbols | 332 ++++++++ .../typeArgumentSpeculationRecovery.types | 336 ++++++++ ...ArgumentSpeculationRelationalExpression.js | 211 +++++ ...entSpeculationRelationalExpression.symbols | 570 ++++++++++++++ ...umentSpeculationRelationalExpression.types | 738 ++++++++++++++++++ .../typeArgumentSpeculationRecovery.ts | 117 +++ ...ArgumentSpeculationRelationalExpression.ts | 121 +++ 12 files changed, 3486 insertions(+), 174 deletions(-) create mode 100644 tsc/internal/parser/type_parser.go create mode 100644 tsc/internal/parser/type_parser_test.go create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.errors.txt create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.js create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.symbols create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.types create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.js create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.symbols create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.types create mode 100644 tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRecovery.ts create mode 100644 tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts diff --git a/tsc/internal/parser/parser.go b/tsc/internal/parser/parser.go index a58db02e5c70f..11bf53a262561 100644 --- a/tsc/internal/parser/parser.go +++ b/tsc/internal/parser/parser.go @@ -63,6 +63,10 @@ const ( ) type Parser struct { + // Grammar policies stay immutable during a parse, including nested speculation. + recoveringTypes typeParser + speculativeTypes typeParser + scanner *scanner.Scanner factory ast.NodeFactory @@ -291,6 +295,8 @@ func ParseIsolatedEntityName(text string) *ast.EntityName { } func (p *Parser) initializeState(opts ast.SourceFileParseOptions, sourceText string, scriptKind core.ScriptKind) { + p.recoveringTypes = typeParser{Parser: p, allowAmbiguity: true} + p.speculativeTypes = typeParser{Parser: p} if scriptKind == core.ScriptKindUnknown { panic("ScriptKind must be specified when parsing source file: " + opts.FileName.AsString()) } @@ -670,6 +676,11 @@ func (p *Parser) reparseTopLevelAwait(sourceFile *ast.SourceFile) *ast.Node { } func (p *Parser) parseListIndex(kind ParsingContext, parseElement func(p *Parser, index int) *ast.Node) []*ast.Node { + result, _ := p.parseListIndexEx(kind, parseElement, true /*allowAmbiguity*/) + return result +} + +func (p *Parser) parseListIndexEx(kind ParsingContext, parseElement func(p *Parser, index int) *ast.Node, allowAmbiguity bool) ([]*ast.Node, bool) { saveParsingContexts := p.parsingContexts p.parsingContexts |= 1 << kind outerReparseList := p.reparseList @@ -678,6 +689,12 @@ func (p *Parser) parseListIndex(kind ParsingContext, parseElement func(p *Parser for i := 0; !p.isListTerminator(kind); i++ { if p.isListElement(kind, false /*inErrorRecovery*/) { elt := parseElement(p, len(list)) + if elt == nil && !allowAmbiguity { + p.reparseList = outerReparseList + p.parsingContexts = saveParsingContexts + return nil, false + } + debug.Assert(elt != nil, "Recovering list elements must produce a node") if len(p.reparseList) != 0 { for _, e := range p.reparseList { // Propagate @typedef type alias declarations outwards to a context that permits them. @@ -692,23 +709,39 @@ func (p *Parser) parseListIndex(kind ParsingContext, parseElement func(p *Parser list = append(list, elt) continue } + if !allowAmbiguity { + p.reparseList = outerReparseList + p.parsingContexts = saveParsingContexts + return nil, false + } if p.abortParsingListOrMoveToNextToken(kind) { break } } p.reparseList = outerReparseList p.parsingContexts = saveParsingContexts - return p.nodeSliceArena.Clone(list) + return p.nodeSliceArena.Clone(list), true } func (p *Parser) parseList(kind ParsingContext, parseElement func(p *Parser) *ast.Node) *ast.NodeList { + return p.parseListEx(kind, parseElement, true /*allowAmbiguity*/) +} + +func (p *Parser) parseListEx(kind ParsingContext, parseElement func(p *Parser) *ast.Node, allowAmbiguity bool) *ast.NodeList { pos := p.nodePos() - nodes := p.parseListIndex(kind, func(p *Parser, _ int) *ast.Node { return parseElement(p) }) + nodes, ok := p.parseListIndexEx(kind, func(p *Parser, _ int) *ast.Node { return parseElement(p) }, allowAmbiguity) + if !ok { + return nil + } return p.newNodeList(core.NewTextRange(pos, p.nodePos()), nodes) } // Return a non-nil (but possibly empty) slice if parsing was successful, or nil if parseElement returned nil func (p *Parser) parseDelimitedList(kind ParsingContext, parseElement func(p *Parser) *ast.Node) *ast.NodeList { + return p.parseDelimitedListEx(kind, parseElement, true /*allowAmbiguity*/) +} + +func (p *Parser) parseDelimitedListEx(kind ParsingContext, parseElement func(p *Parser) *ast.Node, allowAmbiguity bool) *ast.NodeList { pos := p.nodePos() saveParsingContexts := p.parsingContexts p.parsingContexts |= 1 << kind @@ -734,8 +767,9 @@ func (p *Parser) parseDelimitedList(kind ParsingContext, parseElement func(p *Pa // out a comma so we give a good error message. if p.token != ast.KindCommaToken && kind == PCEnumMembers { p.parseErrorAtCurrentToken(diagnostics.An_enum_member_name_must_be_followed_by_a_or) - } else { - p.parseExpected(ast.KindCommaToken) + } else if !p.parseExpected(ast.KindCommaToken) && !allowAmbiguity { + p.parsingContexts = saveParsingContexts + return nil } // If the token was a semicolon, and the caller allows that, then skip it and // continue. This ensures we get back on track and don't result in tons of @@ -757,6 +791,10 @@ func (p *Parser) parseDelimitedList(kind ParsingContext, parseElement func(p *Pa if p.isListTerminator(kind) { break } + if !allowAmbiguity { + p.parsingContexts = saveParsingContexts + return nil + } if p.abortParsingListOrMoveToNextToken(kind) { break } @@ -768,11 +806,23 @@ func (p *Parser) parseDelimitedList(kind ParsingContext, parseElement func(p *Pa // Return a non-nil (but possibly empty) NodeList if parsing was successful, a missing NodeList if the opening // token wasn't found, or nil if parseElement returned nil. func (p *Parser) parseBracketedList(kind ParsingContext, parseElement func(p *Parser) *ast.Node, opening ast.Kind, closing ast.Kind) *ast.NodeList { + return p.parseBracketedListEx(kind, parseElement, opening, closing, true /*allowAmbiguity*/) +} + +func (p *Parser) parseBracketedListEx(kind ParsingContext, parseElement func(p *Parser) *ast.Node, opening ast.Kind, closing ast.Kind, allowAmbiguity bool) *ast.NodeList { if p.parseExpected(opening) { - result := p.parseDelimitedList(kind, parseElement) - p.parseExpected(closing) + result := p.parseDelimitedListEx(kind, parseElement, allowAmbiguity) + if result == nil { + return nil + } + if !p.parseExpected(closing) && !allowAmbiguity { + return nil + } return result } + if !allowAmbiguity { + return nil + } return p.createMissingList() } @@ -1764,11 +1814,12 @@ func (p *Parser) parseInitializer() *ast.Expression { return nil } -func (p *Parser) parseTypeAnnotation() *ast.TypeNode { - if p.parseOptional(ast.KindColonToken) { - return p.parseType() +func (p *typeParser) parseTypeAnnotation() (*ast.TypeNode, bool) { + if !p.parseOptional(ast.KindColonToken) { + return nil, true } - return nil + typeNode := p.parseType() + return typeNode, typeNode != nil } func (p *Parser) parseFunctionDeclaration(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList) *ast.Node { @@ -2737,40 +2788,59 @@ func (p *Parser) parseExportSpecifier() *ast.Node { // TYPES -func (p *Parser) parseType() *ast.TypeNode { +func (p *typeParser) parseType() *ast.TypeNode { saveContextFlags := p.contextFlags p.setContextFlags(ast.NodeFlagsTypeExcludesFlags, false) + result := p.parseTypeWorker() + p.contextFlags = saveContextFlags + return result +} + +func (p *typeParser) parseTypeWorker() *ast.TypeNode { var typeNode *ast.TypeNode if p.isStartOfFunctionTypeOrConstructorType() { typeNode = p.parseFunctionOrConstructorType() } else { pos := p.nodePos() typeNode = p.parseUnionTypeOrHigher() + if typeNode == nil { + return nil + } if !p.inDisallowConditionalTypesContext() && !p.hasPrecedingLineBreak() && p.parseOptional(ast.KindExtendsKeyword) { // The type following 'extends' is not permitted to be another conditional type - extendsType := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, true, (*Parser).parseType) + extendsType := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, true, (*typeParser).parseType) + if extendsType == nil { + return nil + } + // `extends` determines the conditional-type production. Keep its + // branches when only a separator is missing. p.parseExpected(ast.KindQuestionToken) - trueType := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*Parser).parseType) + trueType := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*typeParser).parseType) + if trueType == nil { + return nil + } p.parseExpected(ast.KindColonToken) - falseType := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*Parser).parseType) + falseType := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*typeParser).parseType) + if falseType == nil { + return nil + } conditionalType := p.factory.NewConditionalTypeNode(typeNode, extendsType, trueType, falseType) p.finishNode(conditionalType, pos) typeNode = conditionalType } } - p.contextFlags = saveContextFlags return typeNode } -func (p *Parser) parseUnionTypeOrHigher() *ast.TypeNode { - return p.parseUnionOrIntersectionType(ast.KindBarToken, (*Parser).parseIntersectionTypeOrHigher) +func (p *typeParser) parseUnionTypeOrHigher() *ast.TypeNode { + return p.parseUnionOrIntersectionType(ast.KindBarToken, (*typeParser).parseIntersectionTypeOrHigher) } -func (p *Parser) parseIntersectionTypeOrHigher() *ast.TypeNode { - return p.parseUnionOrIntersectionType(ast.KindAmpersandToken, (*Parser).parseTypeOperatorOrHigher) +func (p *typeParser) parseIntersectionTypeOrHigher() *ast.TypeNode { + return p.parseUnionOrIntersectionType(ast.KindAmpersandToken, (*typeParser).parseTypeOperatorOrHigher) } -func (p *Parser) parseUnionOrIntersectionType(operator ast.Kind, parseConstituentType func(p *Parser) *ast.TypeNode) *ast.TypeNode { +func (p *typeParser) parseUnionOrIntersectionType(operator ast.Kind, parseConstituentType func(p *typeParser) *ast.TypeNode) *ast.TypeNode { pos := p.nodePos() isUnionType := operator == ast.KindBarToken hasLeadingOperator := p.parseOptional(operator) @@ -2780,11 +2850,18 @@ func (p *Parser) parseUnionOrIntersectionType(operator ast.Kind, parseConstituen } else { typeNode = parseConstituentType(p) } + if typeNode == nil { + return nil + } if p.token == operator || hasLeadingOperator { types := make([]*ast.Node, 1, 8) types[0] = typeNode for p.parseOptional(operator) { - types = append(types, p.parseFunctionOrConstructorTypeToError(isUnionType, parseConstituentType)) + constituent := p.parseFunctionOrConstructorTypeToError(isUnionType, parseConstituentType) + if constituent == nil { + return nil + } + types = append(types, constituent) } typeNode = p.createUnionOrIntersectionTypeNode(operator, p.newNodeList(core.NewTextRange(pos, p.nodePos()), p.nodeSliceArena.Clone(types))) p.finishNode(typeNode, pos) @@ -2803,7 +2880,7 @@ func (p *Parser) createUnionOrIntersectionTypeNode(operator ast.Kind, types *ast } } -func (p *Parser) parseTypeOperatorOrHigher() *ast.TypeNode { +func (p *typeParser) parseTypeOperatorOrHigher() *ast.TypeNode { operator := p.token switch operator { case ast.KindKeyOfKeyword, ast.KindUniqueKeyword, ast.KindReadonlyKeyword: @@ -2811,43 +2888,63 @@ func (p *Parser) parseTypeOperatorOrHigher() *ast.TypeNode { case ast.KindInferKeyword: return p.parseInferType() } - return p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*Parser).parsePostfixTypeOrHigher) + return p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*typeParser).parsePostfixTypeOrHigher) } -func (p *Parser) parseTypeOperator(operator ast.Kind) *ast.Node { +func (p *typeParser) parseTypeOperator(operator ast.Kind) *ast.Node { pos := p.nodePos() p.parseExpected(operator) - return p.finishNode(p.factory.NewTypeOperatorNode(operator, p.parseTypeOperatorOrHigher()), pos) + typeNode := p.parseTypeOperatorOrHigher() + if typeNode == nil { + return nil + } + return p.finishNode(p.factory.NewTypeOperatorNode(operator, typeNode), pos) } -func (p *Parser) parseInferType() *ast.Node { +func (p *typeParser) parseInferType() *ast.Node { pos := p.nodePos() p.parseExpected(ast.KindInferKeyword) - return p.finishNode(p.factory.NewInferTypeNode(p.parseTypeParameterOfInferType()), pos) + parameter := p.parseTypeParameterOfInferType() + if parameter == nil { + return nil + } + return p.finishNode(p.factory.NewInferTypeNode(parameter), pos) } -func (p *Parser) parseTypeParameterOfInferType() *ast.Node { +func (p *typeParser) parseTypeParameterOfInferType() *ast.Node { pos := p.nodePos() name := p.parseIdentifier() - constraint := p.tryParseConstraintOfInferType() + constraint, ok := p.tryParseConstraintOfInferType() + if !ok { + return nil + } return p.finishNode(p.factory.NewTypeParameterDeclaration(nil /*modifiers*/, name, constraint, nil /*expression*/, nil /*defaultType*/), pos) } -func (p *Parser) tryParseConstraintOfInferType() *ast.Node { +func (p *typeParser) tryParseConstraintOfInferType() (*ast.Node, bool) { state := p.mark() if p.parseOptional(ast.KindExtendsKeyword) { - constraint := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, true, (*Parser).parseType) + constraint := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, true, (*typeParser).parseType) + if constraint == nil { + // A failed constraint cannot become the same extends type of a conditional. + // Propagate failure instead of reparsing it at every enclosing infer type. + p.rewind(state) + return nil, false + } if p.inDisallowConditionalTypesContext() || p.token != ast.KindQuestionToken { - return constraint + return constraint, true } } p.rewind(state) - return nil + return nil, true } -func (p *Parser) parsePostfixTypeOrHigher() *ast.Node { +func (p *typeParser) parsePostfixTypeOrHigher() *ast.Node { pos := p.nodePos() typeNode := p.parseNonArrayType() + if typeNode == nil { + return nil + } for !p.hasPrecedingLineBreak() { switch p.token { case ast.KindExclamationToken: @@ -2855,7 +2952,7 @@ func (p *Parser) parsePostfixTypeOrHigher() *ast.Node { typeNode = p.finishNode(p.factory.NewJSDocNonNullableType(typeNode), pos) case ast.KindQuestionToken: // If next token is start of a type we have a conditional type - if p.lookAhead((*Parser).nextIsStartOfType) { + if p.lookAhead((*typeParser).nextIsStartOfType) { return typeNode } p.nextToken() @@ -2864,10 +2961,17 @@ func (p *Parser) parsePostfixTypeOrHigher() *ast.Node { p.parseExpected(ast.KindOpenBracketToken) if p.isStartOfType(false /*isStartOfParameter*/) { indexType := p.parseType() - p.parseExpected(ast.KindCloseBracketToken) + if indexType == nil { + return nil + } + if !p.parseExpected(ast.KindCloseBracketToken) && !p.allowAmbiguity { + return nil + } typeNode = p.finishNode(p.factory.NewIndexedAccessTypeNode(typeNode, indexType), pos) } else { - p.parseExpected(ast.KindCloseBracketToken) + if !p.parseExpected(ast.KindCloseBracketToken) && !p.allowAmbiguity { + return nil + } typeNode = p.finishNode(p.factory.NewArrayTypeNode(typeNode), pos) } default: @@ -2882,7 +2986,7 @@ func (p *Parser) nextIsStartOfType() bool { return p.isStartOfType(false /*inStartOfParameter*/) } -func (p *Parser) parseNonArrayType() *ast.Node { +func (p *typeParser) parseNonArrayType() *ast.Node { switch p.token { case ast.KindAnyKeyword, ast.KindUnknownKeyword, ast.KindStringKeyword, ast.KindNumberKeyword, ast.KindBigIntKeyword, ast.KindSymbolKeyword, ast.KindBooleanKeyword, ast.KindUndefinedKeyword, ast.KindNeverKeyword, ast.KindObjectKeyword: @@ -2912,7 +3016,7 @@ func (p *Parser) parseNonArrayType() *ast.Node { ast.KindFalseKeyword, ast.KindNullKeyword: return p.parseLiteralTypeNode(false /*negative*/) case ast.KindMinusToken: - if p.lookAhead((*Parser).nextTokenIsNumericOrBigIntLiteral) { + if p.lookAhead((*typeParser).nextTokenIsNumericOrBigIntLiteral) { return p.parseLiteralTypeNode(true /*negative*/) } return p.parseTypeReference() @@ -2925,12 +3029,12 @@ func (p *Parser) parseNonArrayType() *ast.Node { } return thisKeyword case ast.KindTypeOfKeyword: - if p.lookAhead((*Parser).nextIsStartOfTypeOfImportType) { + if p.lookAhead((*typeParser).nextIsStartOfTypeOfImportType) { return p.parseImportType() } return p.parseTypeQuery() case ast.KindOpenBraceToken: - if p.lookAhead((*Parser).nextIsStartOfMappedType) { + if p.lookAhead((*typeParser).nextIsStartOfMappedType) { return p.parseMappedType() } return p.parseTypeLiteral() @@ -2941,7 +3045,7 @@ func (p *Parser) parseNonArrayType() *ast.Node { case ast.KindImportKeyword: return p.parseImportType() case ast.KindAssertsKeyword: - if p.lookAhead((*Parser).nextTokenIsIdentifierOrKeywordOnSameLine) { + if p.lookAhead((*typeParser).nextTokenIsIdentifierOrKeywordOnSameLine) { return p.parseAssertsTypePredicate() } return p.parseTypeReference() @@ -2965,9 +3069,13 @@ func (p *Parser) parseThisTypeNode() *ast.Node { return p.finishNode(p.factory.NewThisTypeNode(), pos) } -func (p *Parser) parseThisTypePredicate(lhs *ast.Node) *ast.Node { +func (p *typeParser) parseThisTypePredicate(lhs *ast.Node) *ast.Node { p.nextToken() - return p.finishNode(p.factory.NewTypePredicateNode(nil /*assertsModifier*/, lhs, p.parseType()), lhs.Pos()) + typeNode := p.parseType() + if typeNode == nil { + return nil + } + return p.finishNode(p.factory.NewTypePredicateNode(nil /*assertsModifier*/, lhs, typeNode), lhs.Pos()) } func (p *Parser) parseJSDocAllType() *ast.Node { @@ -2976,17 +3084,25 @@ func (p *Parser) parseJSDocAllType() *ast.Node { return p.finishNode(p.factory.NewJSDocAllType(), pos) } -func (p *Parser) parseJSDocNonNullableType() *ast.TypeNode { +func (p *typeParser) parseJSDocNonNullableType() *ast.TypeNode { pos := p.nodePos() p.nextToken() - return p.finishNode(p.factory.NewJSDocNonNullableType(p.parseTypeOperatorOrHigher()), pos) + typeNode := p.parseTypeOperatorOrHigher() + if typeNode == nil { + return nil + } + return p.finishNode(p.factory.NewJSDocNonNullableType(typeNode), pos) } -func (p *Parser) parseJSDocNullableType() *ast.Node { +func (p *typeParser) parseJSDocNullableType() *ast.Node { pos := p.nodePos() // skip the ? p.nextToken() - return p.finishNode(p.factory.NewJSDocNullableType(p.parseTypeOperatorOrHigher()), pos) + typeNode := p.parseTypeOperatorOrHigher() + if typeNode == nil { + return nil + } + return p.finishNode(p.factory.NewJSDocNullableType(typeNode), pos) } func (p *Parser) parseJSDocType() *ast.TypeNode { @@ -3023,9 +3139,14 @@ func (p *Parser) parseLiteralTypeNode(negative bool) *ast.Node { return p.finishNode(p.factory.NewLiteralTypeNode(expression), pos) } -func (p *Parser) parseTypeReference() *ast.Node { +func (p *typeParser) parseTypeReference() *ast.Node { pos := p.nodePos() - return p.finishNode(p.factory.NewTypeReferenceNode(p.parseEntityNameOfTypeReference(), p.parseTypeArgumentsOfTypeReference()), pos) + name := p.parseEntityNameOfTypeReference() + arguments, ok := p.parseTypeArgumentsOfTypeReference() + if !ok { + return nil + } + return p.finishNode(p.factory.NewTypeReferenceNode(name, arguments), pos) } func (p *Parser) parseEntityNameOfTypeReference() *ast.Node { @@ -3138,16 +3259,17 @@ func (p *Parser) reScanTemplateToken(isTaggedTemplate bool) ast.Kind { return p.token } -func (p *Parser) parseTypeArgumentsOfTypeReference() *ast.NodeList { - if !p.hasPrecedingLineBreak() && p.reScanLessThanToken() == ast.KindLessThanToken { - return p.parseTypeArguments() +func (p *typeParser) parseTypeArgumentsOfTypeReference() (*ast.NodeList, bool) { + if p.hasPrecedingLineBreak() || p.reScanLessThanToken() != ast.KindLessThanToken { + return nil, true } - return nil + arguments := p.parseTypeArguments() + return arguments, arguments != nil } -func (p *Parser) parseTypeArguments() *ast.NodeList { +func (p *typeParser) parseTypeArguments() *ast.NodeList { if p.token == ast.KindLessThanToken { - return p.parseBracketedList(PCTypeArguments, (*Parser).parseType, ast.KindLessThanToken, ast.KindGreaterThanToken) + return p.parseBracketedList(PCTypeArguments, (*typeParser).parseType, ast.KindLessThanToken, ast.KindGreaterThanToken) } return nil } @@ -3157,17 +3279,24 @@ func (p *Parser) nextIsStartOfTypeOfImportType() bool { return p.token == ast.KindImportKeyword } -func (p *Parser) parseImportType() *ast.Node { +func (p *typeParser) parseImportType() *ast.Node { p.sourceFlags |= ast.NodeFlagsPossiblyContainsDynamicImport pos := p.nodePos() isTypeOf := p.parseOptional(ast.KindTypeOfKeyword) p.parseExpected(ast.KindImportKeyword) - p.parseExpected(ast.KindOpenParenToken) + if !p.parseExpected(ast.KindOpenParenToken) && !p.allowAmbiguity { + return nil + } typeNode := p.parseType() + if typeNode == nil { + return nil + } var attributes *ast.Node if p.parseOptional(ast.KindCommaToken) { openBracePosition := p.scanner.TokenStart() - p.parseExpected(ast.KindOpenBraceToken) + if !p.parseExpected(ast.KindOpenBraceToken) && !p.allowAmbiguity { + return nil + } currentToken := p.token if currentToken == ast.KindWithKeyword || currentToken == ast.KindAssertKeyword { if currentToken == ast.KindAssertKeyword { @@ -3175,12 +3304,23 @@ func (p *Parser) parseImportType() *ast.Node { } p.nextToken() } else { + if !p.allowAmbiguity { + return nil + } p.parseErrorAtCurrentToken(diagnostics.X_0_expected, scanner.TokenToString(ast.KindWithKeyword)) } - p.parseExpected(ast.KindColonToken) + if !p.parseExpected(ast.KindColonToken) && !p.allowAmbiguity { + return nil + } attributes = p.parseImportAttributes(currentToken, true /*skipKeyword*/) + if attributes == nil { + return nil + } p.parseOptional(ast.KindCommaToken) if !p.parseExpected(ast.KindCloseBraceToken) { + if !p.allowAmbiguity { + return nil + } if len(p.diagnostics) != 0 { lastDiagnostic := p.diagnostics[len(p.diagnostics)-1] if lastDiagnostic.Code() == diagnostics.X_0_expected.Code() { @@ -3190,16 +3330,21 @@ func (p *Parser) parseImportType() *ast.Node { } } } - p.parseExpected(ast.KindCloseParenToken) + if !p.parseExpected(ast.KindCloseParenToken) && !p.allowAmbiguity { + return nil + } var qualifier *ast.Node if p.parseOptional(ast.KindDotToken) { qualifier = p.parseEntityNameOfTypeReference() } - typeArguments := p.parseTypeArgumentsOfTypeReference() + typeArguments, ok := p.parseTypeArgumentsOfTypeReference() + if !ok { + return nil + } return p.finishNode(p.factory.NewImportTypeNode(isTypeOf, typeNode, attributes, qualifier, typeArguments), pos) } -func (p *Parser) parseImportAttribute() *ast.Node { +func (p *typeParser) parseImportAttribute() *ast.Node { pos := p.nodePos() var name *ast.Node if tokenIsIdentifierOrKeyword(p.token) { @@ -3208,15 +3353,20 @@ func (p *Parser) parseImportAttribute() *ast.Node { name = p.parseLiteralExpression() } if name != nil { - p.parseExpected(ast.KindColonToken) + if !p.parseExpected(ast.KindColonToken) && !p.allowAmbiguity { + return nil + } } else { + if !p.allowAmbiguity { + return nil + } p.parseErrorAtCurrentToken(diagnostics.Identifier_or_string_literal_expected) } value := p.parseAssignmentExpressionOrHigher() return p.finishNode(p.factory.NewImportAttribute(name, value), pos) } -func (p *Parser) parseImportAttributes(token ast.Kind, skipKeyword bool) *ast.Node { +func (p *typeParser) parseImportAttributes(token ast.Kind, skipKeyword bool) *ast.Node { pos := p.nodePos() if !skipKeyword { p.parseExpected(token) @@ -3226,8 +3376,14 @@ func (p *Parser) parseImportAttributes(token ast.Kind, skipKeyword bool) *ast.No openBracePosition := p.scanner.TokenStart() if p.parseExpected(ast.KindOpenBraceToken) { multiLine = p.hasPrecedingLineBreak() - elements = p.parseDelimitedList(PCImportAttributes, (*Parser).parseImportAttribute) + elements = p.parseDelimitedList(PCImportAttributes, (*typeParser).parseImportAttribute) + if elements == nil { + return nil + } if !p.parseExpected(ast.KindCloseBraceToken) { + if !p.allowAmbiguity { + return nil + } if len(p.diagnostics) != 0 { lastDiagnostic := p.diagnostics[len(p.diagnostics)-1] if lastDiagnostic.Code() == diagnostics.X_0_expected.Code() { @@ -3237,19 +3393,25 @@ func (p *Parser) parseImportAttributes(token ast.Kind, skipKeyword bool) *ast.No } } } else { + if !p.allowAmbiguity { + return nil + } elements = p.parseEmptyNodeList() } return p.finishNode(p.factory.NewImportAttributes(token, elements, multiLine), pos) } -func (p *Parser) parseTypeQuery() *ast.Node { +func (p *typeParser) parseTypeQuery() *ast.Node { pos := p.nodePos() p.parseExpected(ast.KindTypeOfKeyword) entityName := p.parseEntityName(true /*allowReservedWords*/, true /*allowPrivateName*/, nil) // Make sure we perform ASI to prevent parsing the next line's type arguments as part of an instantiation expression var typeArguments *ast.NodeList - if !p.hasPrecedingLineBreak() { + if !p.hasPrecedingLineBreak() && p.token == ast.KindLessThanToken { typeArguments = p.parseTypeArguments() + if typeArguments == nil { + return nil + } } return p.finishNode(p.factory.NewTypeQueryNode(entityName, typeArguments), pos) } @@ -3265,50 +3427,81 @@ func (p *Parser) nextIsStartOfMappedType() bool { return p.token == ast.KindOpenBracketToken && p.nextTokenIsIdentifier() && p.nextToken() == ast.KindInKeyword } -func (p *Parser) parseMappedType() *ast.Node { +func (p *typeParser) parseMappedType() *ast.Node { pos := p.nodePos() - p.parseExpected(ast.KindOpenBraceToken) + if !p.parseExpected(ast.KindOpenBraceToken) && !p.allowAmbiguity { + return nil + } var readonlyToken *ast.Node // ReadonlyKeyword | PlusToken | MinusToken if p.token == ast.KindReadonlyKeyword || p.token == ast.KindPlusToken || p.token == ast.KindMinusToken { readonlyToken = p.parseTokenNode() if readonlyToken.Kind != ast.KindReadonlyKeyword { - p.parseExpected(ast.KindReadonlyKeyword) + if !p.parseExpected(ast.KindReadonlyKeyword) && !p.allowAmbiguity { + return nil + } } } - p.parseExpected(ast.KindOpenBracketToken) + if !p.parseExpected(ast.KindOpenBracketToken) && !p.allowAmbiguity { + return nil + } typeParameter := p.parseMappedTypeParameter() + if typeParameter == nil { + return nil + } var nameType *ast.TypeNode if p.parseOptional(ast.KindAsKeyword) { nameType = p.parseType() + if nameType == nil { + return nil + } + } + if !p.parseExpected(ast.KindCloseBracketToken) && !p.allowAmbiguity { + return nil } - p.parseExpected(ast.KindCloseBracketToken) var questionToken *ast.Node // QuestionToken | PlusToken | MinusToken if p.token == ast.KindQuestionToken || p.token == ast.KindPlusToken || p.token == ast.KindMinusToken { questionToken = p.parseTokenNode() if questionToken.Kind != ast.KindQuestionToken { - p.parseExpected(ast.KindQuestionToken) + if !p.parseExpected(ast.KindQuestionToken) && !p.allowAmbiguity { + return nil + } } } - typeNode := p.parseTypeAnnotation() - p.parseSemicolon() - members := p.parseList(PCTypeMembers, (*Parser).parseTypeMember) - p.parseExpected(ast.KindCloseBraceToken) + typeNode, ok := p.parseTypeAnnotation() + if !ok { + return nil + } + if !p.parseSemicolon() && !p.allowAmbiguity { + return nil + } + members := p.parseList(PCTypeMembers, (*typeParser).parseTypeMember) + if members == nil { + return nil + } + if !p.parseExpected(ast.KindCloseBraceToken) && !p.allowAmbiguity { + return nil + } return p.finishNode(p.factory.NewMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, typeNode, members), pos) } -func (p *Parser) parseMappedTypeParameter() *ast.Node { +func (p *typeParser) parseMappedTypeParameter() *ast.Node { pos := p.nodePos() name := p.parseIdentifierName() - p.parseExpected(ast.KindInKeyword) + if !p.parseExpected(ast.KindInKeyword) && !p.allowAmbiguity { + return nil + } typeNode := p.parseType() + if typeNode == nil { + return nil + } return p.finishNode(p.factory.NewTypeParameterDeclaration(nil /*modifiers*/, name, typeNode, nil /*expression*/, nil /*defaultType*/), pos) } -func (p *Parser) parseTypeMember() *ast.Node { +func (p *typeParser) parseTypeMember() *ast.Node { if p.token == ast.KindOpenParenToken || p.token == ast.KindLessThanToken { return p.parseSignatureMember(ast.KindCallSignature) } - if p.token == ast.KindNewKeyword && p.lookAhead((*Parser).nextTokenIsOpenParenOrLessThan) { + if p.token == ast.KindNewKeyword && p.lookAhead((*typeParser).nextTokenIsOpenParenOrLessThan) { return p.parseSignatureMember(ast.KindConstructSignature) } pos := p.nodePos() @@ -3331,16 +3524,27 @@ func (p *Parser) nextTokenIsOpenParenOrLessThan() bool { return p.token == ast.KindOpenParenToken || p.token == ast.KindLessThanToken } -func (p *Parser) parseSignatureMember(kind ast.Kind) *ast.Node { +func (p *typeParser) parseSignatureMember(kind ast.Kind) *ast.Node { pos := p.nodePos() jsdoc := p.jsdocScannerInfo() if kind == ast.KindConstructSignature { p.parseExpected(ast.KindNewKeyword) } - typeParameters := p.parseTypeParameters() + typeParameters, ok := p.parseTypeParameters() + if !ok { + return nil + } parameters := p.parseParameters(ParseFlagsType) - typeNode := p.parseReturnType(ast.KindColonToken /*isType*/, true) - p.parseTypeMemberSemicolon() + if parameters == nil { + return nil + } + typeNode, ok := p.parseReturnType(ast.KindColonToken /*isType*/, true) + if !ok { + return nil + } + if !p.parseTypeMemberSemicolon() { + return nil + } var result *ast.Node if kind == ast.KindCallSignature { result = p.factory.NewCallSignatureDeclaration(typeParameters, parameters, typeNode) @@ -3352,14 +3556,15 @@ func (p *Parser) parseSignatureMember(kind ast.Kind) *ast.Node { return result } -func (p *Parser) parseTypeParameters() *ast.NodeList { - if p.token == ast.KindLessThanToken { - return p.parseBracketedList(PCTypeParameters, (*Parser).parseTypeParameter, ast.KindLessThanToken, ast.KindGreaterThanToken) +func (p *typeParser) parseTypeParameters() (*ast.NodeList, bool) { + if p.token != ast.KindLessThanToken { + return nil, true } - return nil + parameters := p.parseBracketedList(PCTypeParameters, (*typeParser).parseTypeParameter, ast.KindLessThanToken, ast.KindGreaterThanToken) + return parameters, parameters != nil } -func (p *Parser) parseTypeParameter() *ast.Node { +func (p *typeParser) parseTypeParameter() *ast.Node { pos := p.nodePos() modifiers := p.parseModifiersEx(false /*allowDecorators*/, true /*permitConstAsModifier*/, false /*stopOnStartOfClassStaticBlock*/) name := p.parseIdentifier() @@ -3372,6 +3577,9 @@ func (p *Parser) parseTypeParameter() *ast.Node { // instead. if p.isStartOfType(false /*inStartOfParameter*/) || !p.isStartOfExpression() { constraint = p.parseType() + if constraint == nil { + return nil + } } else { // It was not a type, and it looked like an expression. Parse out an expression // here so we recover well. Note: it is important that we call parseUnaryExpression @@ -3386,12 +3594,15 @@ func (p *Parser) parseTypeParameter() *ast.Node { var defaultType *ast.TypeNode if p.parseOptional(ast.KindEqualsToken) { defaultType = p.parseType() + if defaultType == nil { + return nil + } } result := p.factory.NewTypeParameterDeclaration(modifiers, name, constraint, expression, defaultType) return p.finishNode(result, pos) } -func (p *Parser) parseParameters(flags ParseFlags) *ast.NodeList { +func (p *typeParser) parseParameters(flags ParseFlags) *ast.NodeList { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -3406,14 +3617,22 @@ func (p *Parser) parseParameters(flags ParseFlags) *ast.NodeList { // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt if p.parseExpected(ast.KindOpenParenToken) { - parameters := p.parseParametersWorker(flags, true /*allowAmbiguity*/) - p.parseExpected(ast.KindCloseParenToken) + parameters := p.parseParametersWorker(flags, p.allowAmbiguity) + if parameters == nil { + return nil + } + if !p.parseExpected(ast.KindCloseParenToken) && !p.allowAmbiguity { + return nil + } return parameters } + if !p.allowAmbiguity { + return nil + } return p.createMissingList() } -func (p *Parser) parseParametersWorker(flags ParseFlags, allowAmbiguity bool) *ast.NodeList { +func (p *typeParser) parseParametersWorker(flags ParseFlags, allowAmbiguity bool) *ast.NodeList { // FormalParameters [Yield,Await]: (modified) // [empty] // FormalParameterList[?Yield,Await] @@ -3431,7 +3650,7 @@ func (p *Parser) parseParametersWorker(flags ParseFlags, allowAmbiguity bool) *a saveContextFlags := p.contextFlags p.setContextFlags(ast.NodeFlagsYieldContext, flags&ParseFlagsYield != 0) p.setContextFlags(ast.NodeFlagsAwaitContext, flags&ParseFlagsAwait != 0) - parameters := p.parseDelimitedList(PCParameters, func(p *Parser) *ast.Node { + parameters := p.parseDelimitedList(PCParameters, func(p *typeParser) *ast.Node { parameter := p.parseParameterEx(inAwaitContext, allowAmbiguity) if parameter != nil && flags&ParseFlagsType == 0 { p.checkJSSyntax(parameter) @@ -3442,29 +3661,24 @@ func (p *Parser) parseParametersWorker(flags ParseFlags, allowAmbiguity bool) *a return parameters } -func (p *Parser) parseParameter() *ast.Node { +func (p *typeParser) parseParameter() *ast.Node { return p.parseParameterEx(false /*inOuterAwaitContext*/, true /*allowAmbiguity*/) } -func (p *Parser) parseParameterEx(inOuterAwaitContext bool, allowAmbiguity bool) *ast.Node { +func (p *typeParser) parseParameterEx(inOuterAwaitContext bool, allowAmbiguity bool) *ast.Node { pos := p.nodePos() jsdoc := p.jsdocScannerInfo() - // FormalParameter [Yield,Await]: - // BindingElement[?Yield,?Await] - // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context. saveContextFlags := p.contextFlags p.setContextFlags(ast.NodeFlagsAwaitContext, inOuterAwaitContext) modifiers := p.parseModifiersEx(true /*allowDecorators*/, false /*permitConstAsModifier*/, false /*stopOnStartOfClassStaticBlock*/) p.contextFlags = saveContextFlags if p.token == ast.KindThisKeyword { - result := p.factory.NewParameterDeclaration( - modifiers, - nil, /*dotDotDotToken*/ - p.createIdentifier(true /*isIdentifier*/), - nil, /*questionToken*/ - p.parseTypeAnnotation(), - nil, /*initializer*/ - ) + name := p.createIdentifier(true /*isIdentifier*/) + typeNode, ok := p.parseTypeAnnotation() + if !ok { + return nil + } + result := p.factory.NewParameterDeclaration(modifiers, nil /*dotDotDotToken*/, name, nil /*questionToken*/, typeNode, nil /*initializer*/) if modifiers != nil { p.parseErrorAtRange(modifiers.Nodes[0].Loc, diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters) } @@ -3475,14 +3689,14 @@ func (p *Parser) parseParameterEx(inOuterAwaitContext bool, allowAmbiguity bool) if !allowAmbiguity && !p.isParameterNameStart() { return nil } - result := p.factory.NewParameterDeclaration( - modifiers, - dotDotDotToken, - p.parseNameOfParameter(modifiers), - p.parseOptionalToken(ast.KindQuestionToken), - p.parseTypeAnnotation(), - p.parseInitializer(), - ) + name := p.parseNameOfParameter(modifiers) + questionToken := p.parseOptionalToken(ast.KindQuestionToken) + typeNode, ok := p.parseTypeAnnotation() + if !ok { + return nil + } + initializer := p.parseInitializer() + result := p.factory.NewParameterDeclaration(modifiers, dotDotDotToken, name, questionToken, typeNode, initializer) p.withJSDoc(p.finishNode(result, pos), jsdoc) return result } @@ -3512,11 +3726,16 @@ func (p *Parser) parseNameOfParameter(modifiers *ast.ModifierList) *ast.Node { return name } -func (p *Parser) parseReturnType(returnToken ast.Kind, isType bool) *ast.TypeNode { - if p.shouldParseReturnType(returnToken, isType) { - return p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*Parser).parseTypeOrTypePredicate) +func (p *typeParser) parseReturnType(returnToken ast.Kind, isType bool) (*ast.TypeNode, bool) { + if returnToken == ast.KindEqualsGreaterThanToken { + if !p.parseExpected(returnToken) && !p.allowAmbiguity { + return nil, false + } + } else if !p.shouldParseReturnType(returnToken, isType) { + return nil, true } - return nil + typeNode := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*typeParser).parseTypeOrTypePredicate) + return typeNode, typeNode != nil } func (p *Parser) shouldParseReturnType(returnToken ast.Kind, isType bool) bool { @@ -3534,36 +3753,57 @@ func (p *Parser) shouldParseReturnType(returnToken ast.Kind, isType bool) bool { return false } -func (p *Parser) parseTypeOrTypePredicate() *ast.TypeNode { +func (p *typeParser) parseTypeOrTypePredicate() *ast.TypeNode { if p.isIdentifier() { state := p.mark() pos := p.nodePos() id := p.parseIdentifier() if p.token == ast.KindIsKeyword && !p.hasPrecedingLineBreak() { p.nextToken() - return p.finishNode(p.factory.NewTypePredicateNode(nil /*assertsModifier*/, id, p.parseType()), pos) + typeNode := p.parseType() + if typeNode == nil { + return nil + } + return p.finishNode(p.factory.NewTypePredicateNode(nil /*assertsModifier*/, id, typeNode), pos) } p.rewind(state) } return p.parseType() } -func (p *Parser) parseTypeMemberSemicolon() { - // We allow type members to be separated by commas or (possibly ASI) semicolons. - // First check if it was a comma. If so, we're done with the member. +func (p *typeParser) parseTypeMemberSemicolon() bool { + // A comma or an explicit/implicit semicolon separates type members. if p.parseOptional(ast.KindCommaToken) { - return + return true } - // Didn't have a comma. We must have a (possible ASI) semicolon. - p.parseSemicolon() + return p.parseSemicolon() || p.allowAmbiguity } -func (p *Parser) parseAccessorDeclaration(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList, kind ast.Kind, flags ParseFlags) *ast.Node { +func (p *typeParser) parseAccessorDeclaration(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList, kind ast.Kind, flags ParseFlags) *ast.Node { name := p.parsePropertyName() - typeParameters := p.parseTypeParameters() + if name == nil { + return nil + } + typeParameters, ok := p.parseTypeParameters() + if !ok { + return nil + } parameters := p.parseParameters(ParseFlagsNone) - returnType := p.parseReturnType(ast.KindColonToken, false /*isType*/) - body := p.parseFunctionBlockOrSemicolon(flags, nil /*diagnosticMessage*/) + if parameters == nil { + return nil + } + returnType, ok := p.parseReturnType(ast.KindColonToken, false /*isType*/) + if !ok { + return nil + } + var body *ast.Node + if flags&ParseFlagsType != 0 && !p.allowAmbiguity { + if !p.parseTypeMemberSemicolon() { + return nil + } + } else { + body = p.parseFunctionBlockOrSemicolon(flags, nil /*diagnosticMessage*/) + } var result *ast.Node // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors if kind == ast.KindGetAccessor { @@ -3578,14 +3818,14 @@ func (p *Parser) parseAccessorDeclaration(pos int, jsdoc jsdocScannerInfo, modif return result } -func (p *Parser) parsePropertyName() *ast.Node { +func (p *typeParser) parsePropertyName() *ast.Node { saveHasAwaitIdentifier := p.statementHasAwaitIdentifier prop := p.parsePropertyNameWorker(true /*allowComputedPropertyNames*/) p.statementHasAwaitIdentifier = saveHasAwaitIdentifier return prop } -func (p *Parser) parsePropertyNameWorker(allowComputedPropertyNames bool) *ast.Node { +func (p *typeParser) parsePropertyNameWorker(allowComputedPropertyNames bool) *ast.Node { if p.token == ast.KindStringLiteral || p.token == ast.KindNumericLiteral || p.token == ast.KindBigIntLiteral { return p.parseLiteralExpression() } @@ -3598,7 +3838,7 @@ func (p *Parser) parsePropertyNameWorker(allowComputedPropertyNames bool) *ast.N return p.parseIdentifierName() } -func (p *Parser) parseComputedPropertyName() *ast.Node { +func (p *typeParser) parseComputedPropertyName() *ast.Node { // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] @@ -3608,7 +3848,9 @@ func (p *Parser) parseComputedPropertyName() *ast.Node { // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. expression := p.parseExpressionAllowIn() - p.parseExpected(ast.KindCloseBracketToken) + if !p.parseExpected(ast.KindCloseBracketToken) && !p.allowAmbiguity { + return nil + } return p.finishNode(p.factory.NewComputedPropertyName(expression), pos) } @@ -3693,28 +3935,48 @@ func (p *Parser) nextIsUnambiguouslyIndexSignature() bool { return p.token == ast.KindColonToken || p.token == ast.KindCommaToken || p.token == ast.KindCloseBracketToken } -func (p *Parser) parseIndexSignatureDeclaration(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList) *ast.Node { - parameters := p.parseBracketedList(PCParameters, (*Parser).parseParameter, ast.KindOpenBracketToken, ast.KindCloseBracketToken) - typeNode := p.parseTypeAnnotation() - p.parseTypeMemberSemicolon() +func (p *typeParser) parseIndexSignatureDeclaration(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList) *ast.Node { + parameters := p.parseBracketedList(PCParameters, (*typeParser).parseParameter, ast.KindOpenBracketToken, ast.KindCloseBracketToken) + if parameters == nil { + return nil + } + typeNode, ok := p.parseTypeAnnotation() + if !ok || !p.parseTypeMemberSemicolon() { + return nil + } result := p.finishNode(p.factory.NewIndexSignatureDeclaration(modifiers, parameters, typeNode), pos) p.withJSDoc(result, jsdoc) return result } -func (p *Parser) parsePropertyOrMethodSignature(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList) *ast.Node { +func (p *typeParser) parsePropertyOrMethodSignature(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList) *ast.Node { name := p.parsePropertyName() + if name == nil { + return nil + } questionToken := p.parseOptionalToken(ast.KindQuestionToken) var result *ast.Node if p.token == ast.KindOpenParenToken || p.token == ast.KindLessThanToken { // Method signatures don't exist in expression contexts. So they have neither // [Yield] nor [Await] - typeParameters := p.parseTypeParameters() + typeParameters, ok := p.parseTypeParameters() + if !ok { + return nil + } parameters := p.parseParameters(ParseFlagsType) - returnType := p.parseReturnType(ast.KindColonToken /*isType*/, true) + if parameters == nil { + return nil + } + returnType, ok := p.parseReturnType(ast.KindColonToken /*isType*/, true) + if !ok { + return nil + } result = p.factory.NewMethodSignatureDeclaration(modifiers, name, questionToken, typeParameters, parameters, returnType) } else { - typeNode := p.parseTypeAnnotation() + typeNode, ok := p.parseTypeAnnotation() + if !ok { + return nil + } // Although type literal properties cannot not have initializers, we attempt // to parse an initializer so we can report in the checker that an interface // property or type literal property cannot have an initializer. @@ -3724,40 +3986,62 @@ func (p *Parser) parsePropertyOrMethodSignature(pos int, jsdoc jsdocScannerInfo, } result = p.factory.NewPropertySignatureDeclaration(modifiers, name, questionToken, typeNode, initializer) } - p.parseTypeMemberSemicolon() + if !p.parseTypeMemberSemicolon() { + return nil + } p.withJSDoc(p.finishNode(result, pos), jsdoc) return result } -func (p *Parser) parseTypeLiteral() *ast.Node { +func (p *typeParser) parseTypeLiteral() *ast.Node { pos := p.nodePos() - result := p.finishNode(p.factory.NewTypeLiteralNode(p.parseObjectTypeMembers()), pos) - return result + members := p.parseObjectTypeMembers() + if members == nil { + return nil + } + return p.finishNode(p.factory.NewTypeLiteralNode(members), pos) } -func (p *Parser) parseObjectTypeMembers() *ast.NodeList { +func (p *typeParser) parseObjectTypeMembers() *ast.NodeList { if p.parseExpected(ast.KindOpenBraceToken) { - members := p.parseList(PCTypeMembers, (*Parser).parseTypeMember) - p.parseExpected(ast.KindCloseBraceToken) + members := p.parseList(PCTypeMembers, (*typeParser).parseTypeMember) + if members == nil { + return nil + } + if !p.parseExpected(ast.KindCloseBraceToken) && !p.allowAmbiguity { + return nil + } return members } + if !p.allowAmbiguity { + return nil + } return p.createMissingList() } -func (p *Parser) parseTupleType() *ast.Node { +func (p *typeParser) parseTupleType() *ast.Node { pos := p.nodePos() - return p.finishNode(p.factory.NewTupleTypeNode(p.parseBracketedList(PCTupleElementTypes, (*Parser).parseTupleElementNameOrTupleElementType, ast.KindOpenBracketToken, ast.KindCloseBracketToken)), pos) + elements := p.parseBracketedList(PCTupleElementTypes, (*typeParser).parseTupleElementNameOrTupleElementType, ast.KindOpenBracketToken, ast.KindCloseBracketToken) + if elements == nil { + return nil + } + return p.finishNode(p.factory.NewTupleTypeNode(elements), pos) } -func (p *Parser) parseTupleElementNameOrTupleElementType() *ast.Node { - if p.lookAhead((*Parser).scanStartOfNamedTupleElement) { +func (p *typeParser) parseTupleElementNameOrTupleElementType() *ast.Node { + if p.lookAhead((*typeParser).scanStartOfNamedTupleElement) { pos := p.nodePos() jsdoc := p.jsdocScannerInfo() dotDotDotToken := p.parseOptionalToken(ast.KindDotDotDotToken) name := p.parseIdentifierName() questionToken := p.parseOptionalToken(ast.KindQuestionToken) - p.parseExpected(ast.KindColonToken) + if !p.parseExpected(ast.KindColonToken) && !p.allowAmbiguity { + return nil + } typeNode := p.parseTupleElementType() + if typeNode == nil { + return nil + } result := p.finishNode(p.factory.NewNamedTupleMember(dotDotDotToken, name, questionToken, typeNode), pos) p.withJSDoc(result, jsdoc) return result @@ -3776,12 +4060,19 @@ func (p *Parser) nextTokenIsColonOrQuestionColon() bool { return p.nextToken() == ast.KindColonToken || p.token == ast.KindQuestionToken && p.nextToken() == ast.KindColonToken } -func (p *Parser) parseTupleElementType() *ast.TypeNode { +func (p *typeParser) parseTupleElementType() *ast.TypeNode { pos := p.nodePos() if p.parseOptional(ast.KindDotDotDotToken) { - return p.finishNode(p.factory.NewRestTypeNode(p.parseType()), pos) + typeNode := p.parseType() + if typeNode == nil { + return nil + } + return p.finishNode(p.factory.NewRestTypeNode(typeNode), pos) } typeNode := p.parseType() + if typeNode == nil { + return nil + } if ast.IsJSDocNullableType(typeNode) && typeNode.Pos() == typeNode.Type().Pos() { node := p.factory.NewOptionalTypeNode(typeNode.Type()) node.Flags = typeNode.Flags @@ -3792,15 +4083,20 @@ func (p *Parser) parseTupleElementType() *ast.TypeNode { return typeNode } -func (p *Parser) parseParenthesizedType() *ast.Node { +func (p *typeParser) parseParenthesizedType() *ast.Node { pos := p.nodePos() p.parseExpected(ast.KindOpenParenToken) typeNode := p.parseType() - p.parseExpected(ast.KindCloseParenToken) + if typeNode == nil { + return nil + } + if !p.parseExpected(ast.KindCloseParenToken) && !p.allowAmbiguity { + return nil + } return p.finishNode(p.factory.NewParenthesizedTypeNode(typeNode), pos) } -func (p *Parser) parseAssertsTypePredicate() *ast.TypeNode { +func (p *typeParser) parseAssertsTypePredicate() *ast.TypeNode { pos := p.nodePos() assertsModifier := p.parseExpectedToken(ast.KindAssertsKeyword) var parameterName *ast.Node @@ -3812,13 +4108,21 @@ func (p *Parser) parseAssertsTypePredicate() *ast.TypeNode { var typeNode *ast.TypeNode if p.parseOptional(ast.KindIsKeyword) { typeNode = p.parseType() + if typeNode == nil { + return nil + } } return p.finishNode(p.factory.NewTypePredicateNode(assertsModifier, parameterName, typeNode), pos) } -func (p *Parser) parseTemplateType() *ast.Node { +func (p *typeParser) parseTemplateType() *ast.Node { pos := p.nodePos() - return p.finishNode(p.factory.NewTemplateLiteralTypeNode(p.parseTemplateHead(false /*isTaggedTemplate*/), p.parseTemplateTypeSpans()), pos) + head := p.parseTemplateHead(false /*isTaggedTemplate*/) + spans := p.parseTemplateTypeSpans() + if spans == nil { + return nil + } + return p.finishNode(p.factory.NewTemplateLiteralTypeNode(head, spans), pos) } func (p *Parser) parseTemplateHead(isTaggedTemplate bool) *ast.Node { @@ -3839,11 +4143,14 @@ func (p *Parser) getTemplateLiteralRawText(endLength int) string { return tokenText[1 : len(tokenText)-endLength] } -func (p *Parser) parseTemplateTypeSpans() *ast.NodeList { +func (p *typeParser) parseTemplateTypeSpans() *ast.NodeList { pos := p.nodePos() var list []*ast.Node for { span := p.parseTemplateTypeSpan() + if span == nil { + return nil + } list = append(list, span) if span.AsTemplateLiteralTypeSpan().Literal.Kind != ast.KindTemplateMiddle { break @@ -3852,9 +4159,17 @@ func (p *Parser) parseTemplateTypeSpans() *ast.NodeList { return p.newNodeList(core.NewTextRange(pos, p.nodePos()), list) } -func (p *Parser) parseTemplateTypeSpan() *ast.Node { +func (p *typeParser) parseTemplateTypeSpan() *ast.Node { pos := p.nodePos() - return p.finishNode(p.factory.NewTemplateLiteralTypeSpan(p.parseType(), p.parseLiteralOfTemplateSpan(false /*isTaggedTemplate*/)), pos) + typeNode := p.parseType() + if typeNode == nil { + return nil + } + literal := p.parseLiteralOfTemplateSpan(false /*isTaggedTemplate*/) + if literal == nil { + return nil + } + return p.finishNode(p.factory.NewTemplateLiteralTypeSpan(typeNode, literal), pos) } func (p *Parser) parseLiteralOfTemplateSpan(isTaggedTemplate bool) *ast.Node { @@ -3878,12 +4193,15 @@ func (p *Parser) parseTemplateMiddleOrTail() *ast.Node { return p.finishNode(result, pos) } -func (p *Parser) parseFunctionOrConstructorTypeToError(isInUnionType bool, parseConstituentType func(p *Parser) *ast.TypeNode) *ast.TypeNode { +func (p *typeParser) parseFunctionOrConstructorTypeToError(isInUnionType bool, parseConstituentType func(p *typeParser) *ast.TypeNode) *ast.TypeNode { // the function type and constructor type shorthand notation // are not allowed directly in unions and intersections, but we'll // try to parse them gracefully and issue a helpful message. if p.isStartOfFunctionTypeOrConstructorType() { typeNode := p.parseFunctionOrConstructorType() + if typeNode == nil { + return nil + } var diagnostic *diagnostics.Message if typeNode.Kind == ast.KindFunctionType { diagnostic = core.IfElse(isInUnionType, @@ -3907,15 +4225,24 @@ func (p *Parser) isStartOfFunctionTypeOrConstructorType() bool { p.token == ast.KindAbstractKeyword && p.lookAhead((*Parser).nextTokenIsNewKeyword) } -func (p *Parser) parseFunctionOrConstructorType() *ast.TypeNode { +func (p *typeParser) parseFunctionOrConstructorType() *ast.TypeNode { pos := p.nodePos() jsdoc := p.jsdocScannerInfo() modifiers := p.parseModifiersForConstructorType() isConstructorType := p.parseOptional(ast.KindNewKeyword) debug.Assert(modifiers == nil || isConstructorType, "Per isStartOfFunctionOrConstructorType, a function type cannot have modifiers.") - typeParameters := p.parseTypeParameters() + typeParameters, ok := p.parseTypeParameters() + if !ok { + return nil + } parameters := p.parseParameters(ParseFlagsType) - returnType := p.parseReturnType(ast.KindEqualsGreaterThanToken, false /*isType*/) + if parameters == nil { + return nil + } + returnType, ok := p.parseReturnType(ast.KindEqualsGreaterThanToken, false /*isType*/) + if !ok { + return nil + } var result *ast.TypeNode if isConstructorType { result = p.factory.NewConstructorTypeNode(modifiers, typeParameters, parameters, returnType) @@ -5427,9 +5754,10 @@ func (p *Parser) tryParseTypeArgumentsInExpression() *ast.NodeList { state := p.mark() if p.reScanLessThanToken() == ast.KindLessThanToken { p.nextToken() - typeArguments := p.parseDelimitedList(PCTypeArguments, (*Parser).parseType) - // If it doesn't have the closing `>` then it's definitely not an type argument list. - if p.reScanGreaterThanToken() == ast.KindGreaterThanToken { + typeArguments := p.speculativeTypes.parseDelimitedList(PCTypeArguments, (*typeParser).parseType) + // Only a completed type production can establish the type argument interpretation. + // Diagnostics from a recoverable type do not make speculation fail. + if typeArguments != nil && p.reScanGreaterThanToken() == ast.KindGreaterThanToken { p.nextToken() // We successfully parsed a type argument list. The next token determines whether we want to // treat it as such. If the type argument list is followed by `(` or a template literal, as in diff --git a/tsc/internal/parser/type_parser.go b/tsc/internal/parser/type_parser.go new file mode 100644 index 0000000000000..d062f65509c0c --- /dev/null +++ b/tsc/internal/parser/type_parser.go @@ -0,0 +1,125 @@ +package parser + +import "github.com/microsoft/TypeScript/tsc/internal/ast" + +// typeParser is an immutable grammar context shared by type productions without changing +// the recovering parser used by nested expressions or JSDoc. A speculative type +// production returns nil when its structure cannot be established. Diagnostics +// on a recognized type, such as an invalid literal, do not imply failure. +// Optional productions return (nil, true) when absent and (nil, false) on failure. +type typeParser struct { + *Parser + allowAmbiguity bool +} + +func (p *typeParser) lookAhead(callback func(p *typeParser) bool) bool { + state := p.mark() + result := callback(p) + p.rewind(state) + return result +} + +func (p *typeParser) doInContext(flags ast.NodeFlags, value bool, callback func(p *typeParser) *ast.Node) *ast.Node { + saveContextFlags := p.contextFlags + p.setContextFlags(flags, value) + result := callback(p) + p.contextFlags = saveContextFlags + return result +} + +func (p *typeParser) parseDelimitedList(kind ParsingContext, parseElement func(p *typeParser) *ast.Node) *ast.NodeList { + return p.Parser.parseDelimitedListEx(kind, func(_ *Parser) *ast.Node { return parseElement(p) }, p.allowAmbiguity) +} + +func (p *typeParser) parseBracketedList(kind ParsingContext, parseElement func(p *typeParser) *ast.Node, opening ast.Kind, closing ast.Kind) *ast.NodeList { + return p.Parser.parseBracketedListEx(kind, func(_ *Parser) *ast.Node { return parseElement(p) }, opening, closing, p.allowAmbiguity) +} + +func (p *typeParser) parseList(kind ParsingContext, parseElement func(p *typeParser) *ast.Node) *ast.NodeList { + return p.Parser.parseListEx(kind, func(_ *Parser) *ast.Node { return parseElement(p) }, p.allowAmbiguity) +} + +func (p *Parser) parseType() *ast.TypeNode { + types := &p.recoveringTypes + return types.parseType() +} + +func (p *Parser) parseTypeArguments() *ast.NodeList { + types := &p.recoveringTypes + return types.parseTypeArguments() +} + +func (p *Parser) parseImportAttributes(token ast.Kind, skipKeyword bool) *ast.Node { + types := &p.recoveringTypes + return types.parseImportAttributes(token, skipKeyword) +} + +func (p *Parser) parseTypeParameters() *ast.NodeList { + types := &p.recoveringTypes + result, _ := types.parseTypeParameters() + return result +} + +func (p *Parser) parseParameters(flags ParseFlags) *ast.NodeList { + types := &p.recoveringTypes + return types.parseParameters(flags) +} + +func (p *Parser) parseParametersWorker(flags ParseFlags, allowAmbiguity bool) *ast.NodeList { + types := &p.recoveringTypes + return types.parseParametersWorker(flags, allowAmbiguity) +} + +func (p *Parser) parseReturnType(returnToken ast.Kind, isType bool) *ast.TypeNode { + types := &p.recoveringTypes + result, _ := types.parseReturnType(returnToken, isType) + return result +} + +func (p *Parser) parseTypeOrTypePredicate() *ast.TypeNode { + types := &p.recoveringTypes + return types.parseTypeOrTypePredicate() +} + +func (p *Parser) parseTypeMemberSemicolon() { + types := &p.recoveringTypes + types.parseTypeMemberSemicolon() +} + +func (p *Parser) parseAccessorDeclaration(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList, kind ast.Kind, flags ParseFlags) *ast.Node { + types := &p.recoveringTypes + return types.parseAccessorDeclaration(pos, jsdoc, modifiers, kind, flags) +} + +func (p *Parser) parsePropertyName() *ast.Node { + types := &p.recoveringTypes + return types.parsePropertyName() +} + +func (p *Parser) parseObjectTypeMembers() *ast.NodeList { + types := &p.recoveringTypes + return types.parseObjectTypeMembers() +} + +func (p *Parser) parseTypeLiteral() *ast.Node { + types := &p.recoveringTypes + return types.parseTypeLiteral() +} + +func (p *Parser) parseIndexSignatureDeclaration(pos int, jsdoc jsdocScannerInfo, modifiers *ast.ModifierList) *ast.Node { + types := &p.recoveringTypes + return types.parseIndexSignatureDeclaration(pos, jsdoc, modifiers) +} + +func (p *Parser) parseTypeAnnotation() *ast.TypeNode { + types := &p.recoveringTypes + result, _ := types.parseTypeAnnotation() + return result +} + +func (p *typeParser) parseLiteralOfTemplateSpan(isTaggedTemplate bool) *ast.Node { + if !p.allowAmbiguity && p.token != ast.KindCloseBraceToken { + return nil + } + return p.Parser.parseLiteralOfTemplateSpan(isTaggedTemplate) +} diff --git a/tsc/internal/parser/type_parser_test.go b/tsc/internal/parser/type_parser_test.go new file mode 100644 index 0000000000000..254c91cfc3b0a --- /dev/null +++ b/tsc/internal/parser/type_parser_test.go @@ -0,0 +1,49 @@ +package parser + +import ( + "reflect" + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/ast" + "github.com/microsoft/TypeScript/tsc/internal/core" + "gotest.tools/v3/assert" +) + +func TestTypeArgumentSpeculationRollback(t *testing.T) { + t.Parallel() + for _, source := range []string{ + "(x)", + ">(x)", + "<{ m(x: [T): U }>(x)", + "<{ [K in (T]: U }>(x)", + "(x)", + "(x)", + `(x)`, + "<`prefix${(T}`>(x)", + } { + t.Run(source, func(t *testing.T) { + t.Parallel() + p := newParser() + p.initializeState(ast.SourceFileParseOptions{FileName: "/index.ts", PathKey: "/index.ts"}, source, core.ScriptKindTS) + p.parsingContexts = 1 << PCSourceElements + p.nextToken() + state := p.mark() + arguments := p.tryParseTypeArgumentsInExpression() + assert.Assert(t, arguments == nil) + assert.Assert(t, reflect.DeepEqual(p.mark(), state)) + assert.Equal(t, p.parsingContexts, ParsingContexts(1<(...args: any[]): any; + declare function g(...args: any[]): any; + + // Recovery and rollback preserve diagnostics and the following call. + f(); + ~ +!!! error TS1110: Type expected. + g<(T)>(); + + f; + ~ +!!! error TS1110: Type expected. + g<(T)>(); + + f<"\xZ">(); + +!!! error TS1125: Hexadecimal digit expected. + g<(T)>(); + + f<010>(); + ~~~ +!!! error TS1121: Octal literals are not allowed. Use the syntax '0o10'. + g<(T)>(); + + f<("\xZ")>(); + +!!! error TS1125: Hexadecimal digit expected. + g<(T)>(); + + f<(010)>(); + ~~~ +!!! error TS1121: Octal literals are not allowed. Use the syntax '0o10'. + g<(T)>(); + + f<((x: T) => "\xZ")>(); + +!!! error TS1125: Hexadecimal digit expected. + g<(T)>(); + + f(); + ~~~~~~ +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. + g<(T)>(); + + f<("\xZ" > (x)); + +!!! error TS1125: Hexadecimal digit expected. + g<(T)>(); + + f(); + ~ +!!! error TS1005: '?' expected. + g<(T)>(); + + f(); + ~ +!!! error TS1005: ':' expected. + g<(T)>(); + + f U>(); + ~~~~~~~~ +!!! error TS1385: Function type notation must be parenthesized when used in a union type. + g<(T)>(); + + f<() => >(); + ~ +!!! error TS1110: Type expected. + g<(T)>(); + + f(); + ~ +!!! error TS1003: Identifier expected. + g<(T)>(); + + f<{ [(() => { type Bad = (T; return key; })()]: U }>(); + ~ +!!! error TS1005: ')' expected. + g<(T)>(); + +==== recovery.tsx (15 errors) ==== + export {}; + declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; + type T = any; + type U = string; + type X = number; + type Y = string; + declare function f(...args: any[]): any; + declare function g(...args: any[]): any; + + // Recovery and rollback preserve diagnostics and the following call. + f(); + ~ +!!! error TS1110: Type expected. + g<(T)>(); + + f; + ~ +!!! error TS1110: Type expected. + g<(T)>(); + + f<"\xZ">(); + +!!! error TS1125: Hexadecimal digit expected. + g<(T)>(); + + f<010>(); + ~~~ +!!! error TS1121: Octal literals are not allowed. Use the syntax '0o10'. + g<(T)>(); + + f<("\xZ")>(); + +!!! error TS1125: Hexadecimal digit expected. + g<(T)>(); + + f<(010)>(); + ~~~ +!!! error TS1121: Octal literals are not allowed. Use the syntax '0o10'. + g<(T)>(); + + f<((x: T) => "\xZ")>(); + +!!! error TS1125: Hexadecimal digit expected. + g<(T)>(); + + f(); + ~~~~~~ +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. + g<(T)>(); + + f<("\xZ" > (x)); + +!!! error TS1125: Hexadecimal digit expected. + g<(T)>(); + + f(); + ~ +!!! error TS1005: '?' expected. + g<(T)>(); + + f(); + ~ +!!! error TS1005: ':' expected. + g<(T)>(); + + f U>(); + ~~~~~~~~ +!!! error TS1385: Function type notation must be parenthesized when used in a union type. + g<(T)>(); + + f<() => >(); + ~ +!!! error TS1110: Type expected. + g<(T)>(); + + f(); + ~ +!!! error TS1003: Identifier expected. + g<(T)>(); + + f<{ [(() => { type Bad = (T; return key; })()]: U }>(); + ~ +!!! error TS1005: ')' expected. + g<(T)>(); + \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.js b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.js new file mode 100644 index 0000000000000..f97b17865b97a --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.js @@ -0,0 +1,181 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRecovery.ts] //// + +//// [recovery.ts] +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +type T = any; +type U = string; +type X = number; +type Y = string; +declare function f(...args: any[]): any; +declare function g(...args: any[]): any; + +// Recovery and rollback preserve diagnostics and the following call. +f(); +g<(T)>(); + +f; +g<(T)>(); + +f<"\xZ">(); +g<(T)>(); + +f<010>(); +g<(T)>(); + +f<("\xZ")>(); +g<(T)>(); + +f<(010)>(); +g<(T)>(); + +f<((x: T) => "\xZ")>(); +g<(T)>(); + +f(); +g<(T)>(); + +f<("\xZ" > (x)); +g<(T)>(); + +f(); +g<(T)>(); + +f(); +g<(T)>(); + +f U>(); +g<(T)>(); + +f<() => >(); +g<(T)>(); + +f(); +g<(T)>(); + +f<{ [(() => { type Bad = (T; return key; })()]: U }>(); +g<(T)>(); + +//// [recovery.tsx] +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +type T = any; +type U = string; +type X = number; +type Y = string; +declare function f(...args: any[]): any; +declare function g(...args: any[]): any; + +// Recovery and rollback preserve diagnostics and the following call. +f(); +g<(T)>(); + +f; +g<(T)>(); + +f<"\xZ">(); +g<(T)>(); + +f<010>(); +g<(T)>(); + +f<("\xZ")>(); +g<(T)>(); + +f<(010)>(); +g<(T)>(); + +f<((x: T) => "\xZ")>(); +g<(T)>(); + +f(); +g<(T)>(); + +f<("\xZ" > (x)); +g<(T)>(); + +f(); +g<(T)>(); + +f(); +g<(T)>(); + +f U>(); +g<(T)>(); + +f<() => >(); +g<(T)>(); + +f(); +g<(T)>(); + +f<{ [(() => { type Bad = (T; return key; })()]: U }>(); +g<(T)>(); + + +//// [recovery.js] +// Recovery and rollback preserve diagnostics and the following call. +f(); +g(); +f; +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f < ("\xZ" > (x)); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +export {}; +//// [recovery.jsx] +// Recovery and rollback preserve diagnostics and the following call. +f(); +g(); +f; +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f < ("\xZ" > (x)); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +f(); +g(); +export {}; diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.symbols b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.symbols new file mode 100644 index 0000000000000..e75ed46bd7e57 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.symbols @@ -0,0 +1,332 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRecovery.ts] //// + +=== recovery.ts === +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +>a : Symbol(a, Decl(recovery.ts, 1, 13)) +>b : Symbol(b, Decl(recovery.ts, 1, 21)) +>c : Symbol(c, Decl(recovery.ts, 1, 29)) +>d : Symbol(d, Decl(recovery.ts, 1, 37)) +>e : Symbol(e, Decl(recovery.ts, 1, 45)) +>B : Symbol(B, Decl(recovery.ts, 1, 53)) +>options : Symbol(options, Decl(recovery.ts, 1, 61)) +>x : Symbol(x, Decl(recovery.ts, 1, 75)) + +type T = any; +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +type U = string; +>U : Symbol(U, Decl(recovery.ts, 2, 13)) + +type X = number; +>X : Symbol(X, Decl(recovery.ts, 3, 16)) + +type Y = string; +>Y : Symbol(Y, Decl(recovery.ts, 4, 16)) + +declare function f(...args: any[]): any; +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>A : Symbol(A, Decl(recovery.ts, 6, 19)) +>B : Symbol(B, Decl(recovery.ts, 6, 31)) +>args : Symbol(args, Decl(recovery.ts, 6, 45)) + +declare function g(...args: any[]): any; +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>A : Symbol(A, Decl(recovery.ts, 7, 19)) +>args : Symbol(args, Decl(recovery.ts, 7, 22)) + +// Recovery and rollback preserve diagnostics and the following call. +f(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>a : Symbol(a) +> : Symbol(unknown) +>b : Symbol(b) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f; +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +> : Symbol(unknown) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f<"\xZ">(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f<010>(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f<("\xZ")>(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f<(010)>(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f<((x: T) => "\xZ")>(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>x : Symbol(x, Decl(recovery.ts, 28, 4)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f<("\xZ" > (x)); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>x : Symbol(x, Decl(recovery.ts, 1, 75)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) +>U : Symbol(U, Decl(recovery.ts, 2, 13)) +>X : Symbol(X, Decl(recovery.ts, 3, 16)) +>Y : Symbol(Y, Decl(recovery.ts, 4, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) +>U : Symbol(U, Decl(recovery.ts, 2, 13)) +>X : Symbol(X, Decl(recovery.ts, 3, 16)) +>Y : Symbol(Y, Decl(recovery.ts, 4, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f U>(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) +>U : Symbol(U, Decl(recovery.ts, 2, 13)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f<() => >(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +> : Symbol(unknown) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>T : Symbol(T) +> : Symbol(unknown) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +f<{ [(() => { type Bad = (T; return key; })()]: U }>(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>[(() => { type Bad = (T; return key; })()] : Symbol([(() => { type Bad = (T; return key; })()], Decl(recovery.ts, 52, 3)) +>Bad : Symbol(Bad, Decl(recovery.ts, 52, 13)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) +>U : Symbol(U, Decl(recovery.ts, 2, 13)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + +=== recovery.tsx === +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +>a : Symbol(a, Decl(recovery.tsx, 1, 13)) +>b : Symbol(b, Decl(recovery.tsx, 1, 21)) +>c : Symbol(c, Decl(recovery.tsx, 1, 29)) +>d : Symbol(d, Decl(recovery.tsx, 1, 37)) +>e : Symbol(e, Decl(recovery.tsx, 1, 45)) +>B : Symbol(B, Decl(recovery.tsx, 1, 53)) +>options : Symbol(options, Decl(recovery.tsx, 1, 61)) +>x : Symbol(x, Decl(recovery.tsx, 1, 75)) + +type T = any; +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +type U = string; +>U : Symbol(U, Decl(recovery.tsx, 2, 13)) + +type X = number; +>X : Symbol(X, Decl(recovery.tsx, 3, 16)) + +type Y = string; +>Y : Symbol(Y, Decl(recovery.tsx, 4, 16)) + +declare function f(...args: any[]): any; +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>A : Symbol(A, Decl(recovery.tsx, 6, 19)) +>B : Symbol(B, Decl(recovery.tsx, 6, 31)) +>args : Symbol(args, Decl(recovery.tsx, 6, 45)) + +declare function g(...args: any[]): any; +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>A : Symbol(A, Decl(recovery.tsx, 7, 19)) +>args : Symbol(args, Decl(recovery.tsx, 7, 22)) + +// Recovery and rollback preserve diagnostics and the following call. +f(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>a : Symbol(a) +> : Symbol(unknown) +>b : Symbol(b) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f; +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +> : Symbol(unknown) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f<"\xZ">(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f<010>(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f<("\xZ")>(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f<(010)>(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f<((x: T) => "\xZ")>(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>x : Symbol(x, Decl(recovery.tsx, 28, 4)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f<("\xZ" > (x)); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>x : Symbol(x, Decl(recovery.tsx, 1, 75)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) +>U : Symbol(U, Decl(recovery.tsx, 2, 13)) +>X : Symbol(X, Decl(recovery.tsx, 3, 16)) +>Y : Symbol(Y, Decl(recovery.tsx, 4, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) +>U : Symbol(U, Decl(recovery.tsx, 2, 13)) +>X : Symbol(X, Decl(recovery.tsx, 3, 16)) +>Y : Symbol(Y, Decl(recovery.tsx, 4, 16)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f U>(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) +>U : Symbol(U, Decl(recovery.tsx, 2, 13)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f<() => >(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +> : Symbol(unknown) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>T : Symbol(T) +> : Symbol(unknown) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + +f<{ [(() => { type Bad = (T; return key; })()]: U }>(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>[(() => { type Bad = (T; return key; })()] : Symbol([(() => { type Bad = (T; return key; })()], Decl(recovery.tsx, 52, 3)) +>Bad : Symbol(Bad, Decl(recovery.tsx, 52, 13)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) +>U : Symbol(U, Decl(recovery.tsx, 2, 13)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.types b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.types new file mode 100644 index 0000000000000..6df7cc8504452 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.types @@ -0,0 +1,336 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRecovery.ts] //// + +=== recovery.ts === +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +>a : any +>b : any +>c : any +>d : any +>e : any +>B : any +>options : any +>x : any + +type T = any; +>T : any + +type U = string; +>U : string + +type X = number; +>X : number + +type Y = string; +>Y : string + +declare function f(...args: any[]): any; +>f : (...args: any[]) => any +>args : any[] + +declare function g(...args: any[]): any; +>g : (...args: any[]) => any +>args : any[] + +// Recovery and rollback preserve diagnostics and the following call. +f(); +>f() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f; +>f : (...args: any[]) => any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<"\xZ">(); +>f<"\xZ">() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<010>(); +>f<010>() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<("\xZ")>(); +>f<("\xZ")>() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<(010)>(); +>f<(010)>() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<((x: T) => "\xZ")>(); +>f<((x: T) => "\xZ")>() : any +>f : (...args: any[]) => any +>x : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any +>type : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<("\xZ" > (x)); +>f<("\xZ" > (x)) : boolean +>f : (...args: any[]) => any +>("\xZ" > (x)) : boolean +>"\xZ" > (x) : boolean +>"\xZ" : "\\xZ" +>(x) : any +>x : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f U>(); +>f U>() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<() => >(); +>f<() => >() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any +>T : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<{ [(() => { type Bad = (T; return key; })()]: U }>(); +>f<{ [(() => { type Bad = (T; return key; })()]: U }>() : any +>f : (...args: any[]) => any +>[(() => { type Bad = (T; return key; })()] : string +>(() => { type Bad = (T; return key; })() : any +>(() => { type Bad = (T; return key; }) : () => any +>() => { type Bad = (T; return key; } : () => any +>Bad : any +>key : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +=== recovery.tsx === +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +>a : any +>b : any +>c : any +>d : any +>e : any +>B : any +>options : any +>x : any + +type T = any; +>T : any + +type U = string; +>U : string + +type X = number; +>X : number + +type Y = string; +>Y : string + +declare function f(...args: any[]): any; +>f : (...args: any[]) => any +>args : any[] + +declare function g(...args: any[]): any; +>g : (...args: any[]) => any +>args : any[] + +// Recovery and rollback preserve diagnostics and the following call. +f(); +>f() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f; +>f : (...args: any[]) => any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<"\xZ">(); +>f<"\xZ">() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<010>(); +>f<010>() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<("\xZ")>(); +>f<("\xZ")>() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<(010)>(); +>f<(010)>() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<((x: T) => "\xZ")>(); +>f<((x: T) => "\xZ")>() : any +>f : (...args: any[]) => any +>x : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any +>type : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<("\xZ" > (x)); +>f<("\xZ" > (x)) : boolean +>f : (...args: any[]) => any +>("\xZ" > (x)) : boolean +>"\xZ" > (x) : boolean +>"\xZ" : "\\xZ" +>(x) : any +>x : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f U>(); +>f U>() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<() => >(); +>f<() => >() : any +>f : (...args: any[]) => any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any +>T : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + +f<{ [(() => { type Bad = (T; return key; })()]: U }>(); +>f<{ [(() => { type Bad = (T; return key; })()]: U }>() : any +>f : (...args: any[]) => any +>[(() => { type Bad = (T; return key; })()] : string +>(() => { type Bad = (T; return key; })() : any +>(() => { type Bad = (T; return key; }) : () => any +>() => { type Bad = (T; return key; } : () => any +>Bad : any +>key : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.js b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.js new file mode 100644 index 0000000000000..1b8350969202f --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.js @@ -0,0 +1,211 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts] //// + +//// [expressions.ts] +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +type T = any; +type U = string; +type X = number; +type Y = string; +declare function f(...args: any[]): any; +declare function g(...args: any[]): any; + +// Typed, empty, and async arrows remain expressions. +a < ((x: T) => c > (d)); +a < ((x: T) => c > d); +a < (() => c > (d)); +a < (() => c > d); +a < (async (x: T) => c > (d)); +a < (async (x: T) => c > d); + +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +a < [b > `c`]; +a < b[c > (d)]; +a < c[d > (e) ? 0 : 1]; +a < {b: c > (d)}; +a < new B > (c); +a < keyof [b > (c)]; +a < import("m", options) > (c); + +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +console.log(a < b, (((c > (d & e))))); +f(a < b, [c > (d)]); +f(a < b, {c: d > (e)}); +f(a < b, [g(c > (d))]); + +// Completed type arguments still take precedence over relational expressions. +f(1); +f<(x: T) => T>(1); +f<() => T>(1); +f<((x: T) => T)>(1); +f<(x: T) => (T)>(x); +f<{ [a < ((x: T) => c > (d))]: T }>(); +f<{ [a < [b > (c)]]: T }>(); +f(); +f<[T, U]>(); +f<{ x: T; m(x: T): U }>(); +f<{ [K in keyof T]: T[K] }>(); +f U>(); +f(); +f(); +f<`prefix${T}`>(); +f(); +f(); +f<{ /** @type {(T} @see x */ x: T }>(); +f<() => T>`text`; +f<() => T>`text${1}`; +f<() => T>; + +//// [expressions.tsx] +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +type T = any; +type U = string; +type X = number; +type Y = string; +declare function f(...args: any[]): any; +declare function g(...args: any[]): any; + +// Typed, empty, and async arrows remain expressions. +a < ((x: T) => c > (d)); +a < ((x: T) => c > d); +a < (() => c > (d)); +a < (() => c > d); +a < (async (x: T) => c > (d)); +a < (async (x: T) => c > d); + +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +a < [b > `c`]; +a < b[c > (d)]; +a < c[d > (e) ? 0 : 1]; +a < {b: c > (d)}; +a < new B > (c); +a < keyof [b > (c)]; +a < import("m", options) > (c); + +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +console.log(a < b, (((c > (d & e))))); +f(a < b, [c > (d)]); +f(a < b, {c: d > (e)}); +f(a < b, [g(c > (d))]); + +// Completed type arguments still take precedence over relational expressions. +f(1); +f<(x: T) => T>(1); +f<() => T>(1); +f<((x: T) => T)>(1); +f<(x: T) => (T)>(x); +f<{ [a < ((x: T) => c > (d))]: T }>(); +f<{ [a < [b > (c)]]: T }>(); +f(); +f<[T, U]>(); +f<{ x: T; m(x: T): U }>(); +f<{ [K in keyof T]: T[K] }>(); +f U>(); +f(); +f(); +f<`prefix${T}`>(); +f(); +f(); +f<{ /** @type {(T} @see x */ x: T }>(); +f<() => T>`text`; +f<() => T>`text${1}`; +f<() => T>; + + +//// [expressions.js] +// Typed, empty, and async arrows remain expressions. +a < ((x) => c > (d)); +a < ((x) => c > d); +a < (() => c > (d)); +a < (() => c > d); +a < (async (x) => c > (d)); +a < (async (x) => c > d); +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +a < [b > `c`]; +a < b[c > (d)]; +a < c[d > (e) ? 0 : 1]; +a < { b: c > (d) }; +a < new B > (c); +a < keyof[b > (c)]; +a < import("m", options) > (c); +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +console.log(a < b, (((c > (d & e))))); +f(a < b, [c > (d)]); +f(a < b, { c: d > (e) }); +f(a < b, [g(c > (d))]); +// Completed type arguments still take precedence over relational expressions. +f(1); +f(1); +f(1); +f(1); +f(x); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f `text`; +f `text${1}`; +f; +export {}; +//// [expressions.jsx] +// Typed, empty, and async arrows remain expressions. +a < ((x) => c > (d)); +a < ((x) => c > d); +a < (() => c > (d)); +a < (() => c > d); +a < (async (x) => c > (d)); +a < (async (x) => c > d); +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +a < [b > `c`]; +a < b[c > (d)]; +a < c[d > (e) ? 0 : 1]; +a < { b: c > (d) }; +a < new B > (c); +a < keyof[b > (c)]; +a < import("m", options) > (c); +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +console.log(a < b, (((c > (d & e))))); +f(a < b, [c > (d)]); +f(a < b, { c: d > (e) }); +f(a < b, [g(c > (d))]); +// Completed type arguments still take precedence over relational expressions. +f(1); +f(1); +f(1); +f(1); +f(x); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f(); +f `text`; +f `text${1}`; +f; +export {}; diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.symbols b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.symbols new file mode 100644 index 0000000000000..0697ba99aa2ad --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.symbols @@ -0,0 +1,570 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts] //// + +=== expressions.ts === +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) +>e : Symbol(e, Decl(expressions.ts, 1, 45)) +>B : Symbol(B, Decl(expressions.ts, 1, 53)) +>options : Symbol(options, Decl(expressions.ts, 1, 61)) +>x : Symbol(x, Decl(expressions.ts, 1, 75)) + +type T = any; +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +type U = string; +>U : Symbol(U, Decl(expressions.ts, 2, 13)) + +type X = number; +>X : Symbol(X, Decl(expressions.ts, 3, 16)) + +type Y = string; +>Y : Symbol(Y, Decl(expressions.ts, 4, 16)) + +declare function f(...args: any[]): any; +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>A : Symbol(A, Decl(expressions.ts, 6, 19)) +>B : Symbol(B, Decl(expressions.ts, 6, 31)) +>args : Symbol(args, Decl(expressions.ts, 6, 45)) + +declare function g(...args: any[]): any; +>g : Symbol(g, Decl(expressions.ts, 6, 66)) +>A : Symbol(A, Decl(expressions.ts, 7, 19)) +>args : Symbol(args, Decl(expressions.ts, 7, 22)) + +// Typed, empty, and async arrows remain expressions. +a < ((x: T) => c > (d)); +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>x : Symbol(x, Decl(expressions.ts, 10, 6)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +a < ((x: T) => c > d); +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>x : Symbol(x, Decl(expressions.ts, 11, 6)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +a < (() => c > (d)); +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +a < (() => c > d); +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +a < (async (x: T) => c > (d)); +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>x : Symbol(x, Decl(expressions.ts, 14, 12)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +a < (async (x: T) => c > d); +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>x : Symbol(x, Decl(expressions.ts, 15, 12)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) + +a < [b > `c`]; +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) + +a < b[c > (d)]; +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +a < c[d > (e) ? 0 : 1]; +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) +>e : Symbol(e, Decl(expressions.ts, 1, 45)) + +a < {b: c > (d)}; +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 22, 5)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +a < new B > (c); +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>B : Symbol(B, Decl(expressions.ts, 1, 53)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) + +a < keyof [b > (c)]; +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) + +a < import("m", options) > (c); +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>options : Symbol(options, Decl(expressions.ts, 1, 61)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) + +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) +>e : Symbol(e, Decl(expressions.ts, 1, 45)) + +console.log(a < b, (((c > (d & e))))); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) +>e : Symbol(e, Decl(expressions.ts, 1, 45)) + +f(a < b, [c > (d)]); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +f(a < b, {c: d > (e)}); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 31, 10)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) +>e : Symbol(e, Decl(expressions.ts, 1, 45)) + +f(a < b, [g(c > (d))]); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>g : Symbol(g, Decl(expressions.ts, 6, 66)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) + +// Completed type arguments still take precedence over relational expressions. +f(1); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f<(x: T) => T>(1); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>x : Symbol(x, Decl(expressions.ts, 36, 3)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f<() => T>(1); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f<((x: T) => T)>(1); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>x : Symbol(x, Decl(expressions.ts, 38, 4)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f<(x: T) => (T)>(x); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 39, 3)) +>x : Symbol(x, Decl(expressions.ts, 39, 6)) +>T : Symbol(T, Decl(expressions.ts, 39, 3)) +>T : Symbol(T, Decl(expressions.ts, 39, 3)) +>x : Symbol(x, Decl(expressions.ts, 1, 75)) + +f<{ [a < ((x: T) => c > (d))]: T }>(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>[a < ((x: T) => c > (d))] : Symbol([a < ((x: T) => c > (d))], Decl(expressions.ts, 40, 3)) +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>x : Symbol(x, Decl(expressions.ts, 40, 11)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>d : Symbol(d, Decl(expressions.ts, 1, 37)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f<{ [a < [b > (c)]]: T }>(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>[a < [b > (c)]] : Symbol([a < [b > (c)]], Decl(expressions.ts, 41, 3)) +>a : Symbol(a, Decl(expressions.ts, 1, 13)) +>b : Symbol(b, Decl(expressions.ts, 1, 21)) +>c : Symbol(c, Decl(expressions.ts, 1, 29)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>U : Symbol(U, Decl(expressions.ts, 2, 13)) + +f<[T, U]>(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>U : Symbol(U, Decl(expressions.ts, 2, 13)) + +f<{ x: T; m(x: T): U }>(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>x : Symbol(x, Decl(expressions.ts, 44, 3)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>m : Symbol(m, Decl(expressions.ts, 44, 9)) +>x : Symbol(x, Decl(expressions.ts, 44, 12)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>U : Symbol(U, Decl(expressions.ts, 2, 13)) + +f<{ [K in keyof T]: T[K] }>(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>K : Symbol(K, Decl(expressions.ts, 45, 5)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>K : Symbol(K, Decl(expressions.ts, 45, 5)) + +f U>(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>x : Symbol(x, Decl(expressions.ts, 46, 7)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>U : Symbol(U, Decl(expressions.ts, 2, 13)) + +f(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>U : Symbol(U, Decl(expressions.ts, 2, 13)) +>X : Symbol(X, Decl(expressions.ts, 3, 16)) +>Y : Symbol(Y, Decl(expressions.ts, 4, 16)) + +f(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) + +f<`prefix${T}`>(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>X : Symbol(X, Decl(expressions.ts, 50, 7)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>X : Symbol(X, Decl(expressions.ts, 51, 7)) +>U : Symbol(U, Decl(expressions.ts, 2, 13)) +>X : Symbol(X, Decl(expressions.ts, 3, 16)) + +f<{ /** @type {(T} @see x */ x: T }>(); +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>x : Symbol(x, Decl(expressions.ts, 52, 3)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f<() => T>`text`; +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f<() => T>`text${1}`; +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +f<() => T>; +>f : Symbol(f, Decl(expressions.ts, 5, 16)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) + +=== expressions.tsx === +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) +>e : Symbol(e, Decl(expressions.tsx, 1, 45)) +>B : Symbol(B, Decl(expressions.tsx, 1, 53)) +>options : Symbol(options, Decl(expressions.tsx, 1, 61)) +>x : Symbol(x, Decl(expressions.tsx, 1, 75)) + +type T = any; +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +type U = string; +>U : Symbol(U, Decl(expressions.tsx, 2, 13)) + +type X = number; +>X : Symbol(X, Decl(expressions.tsx, 3, 16)) + +type Y = string; +>Y : Symbol(Y, Decl(expressions.tsx, 4, 16)) + +declare function f(...args: any[]): any; +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>A : Symbol(A, Decl(expressions.tsx, 6, 19)) +>B : Symbol(B, Decl(expressions.tsx, 6, 31)) +>args : Symbol(args, Decl(expressions.tsx, 6, 45)) + +declare function g(...args: any[]): any; +>g : Symbol(g, Decl(expressions.tsx, 6, 66)) +>A : Symbol(A, Decl(expressions.tsx, 7, 19)) +>args : Symbol(args, Decl(expressions.tsx, 7, 22)) + +// Typed, empty, and async arrows remain expressions. +a < ((x: T) => c > (d)); +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>x : Symbol(x, Decl(expressions.tsx, 10, 6)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +a < ((x: T) => c > d); +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>x : Symbol(x, Decl(expressions.tsx, 11, 6)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +a < (() => c > (d)); +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +a < (() => c > d); +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +a < (async (x: T) => c > (d)); +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>x : Symbol(x, Decl(expressions.tsx, 14, 12)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +a < (async (x: T) => c > d); +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>x : Symbol(x, Decl(expressions.tsx, 15, 12)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) + +a < [b > `c`]; +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) + +a < b[c > (d)]; +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +a < c[d > (e) ? 0 : 1]; +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) +>e : Symbol(e, Decl(expressions.tsx, 1, 45)) + +a < {b: c > (d)}; +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 22, 5)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +a < new B > (c); +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>B : Symbol(B, Decl(expressions.tsx, 1, 53)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) + +a < keyof [b > (c)]; +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) + +a < import("m", options) > (c); +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>options : Symbol(options, Decl(expressions.tsx, 1, 61)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) + +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) +>e : Symbol(e, Decl(expressions.tsx, 1, 45)) + +console.log(a < b, (((c > (d & e))))); +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) +>e : Symbol(e, Decl(expressions.tsx, 1, 45)) + +f(a < b, [c > (d)]); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +f(a < b, {c: d > (e)}); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 31, 10)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) +>e : Symbol(e, Decl(expressions.tsx, 1, 45)) + +f(a < b, [g(c > (d))]); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>g : Symbol(g, Decl(expressions.tsx, 6, 66)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) + +// Completed type arguments still take precedence over relational expressions. +f(1); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f<(x: T) => T>(1); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>x : Symbol(x, Decl(expressions.tsx, 36, 3)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f<() => T>(1); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f<((x: T) => T)>(1); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>x : Symbol(x, Decl(expressions.tsx, 38, 4)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f<(x: T) => (T)>(x); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 39, 3)) +>x : Symbol(x, Decl(expressions.tsx, 39, 6)) +>T : Symbol(T, Decl(expressions.tsx, 39, 3)) +>T : Symbol(T, Decl(expressions.tsx, 39, 3)) +>x : Symbol(x, Decl(expressions.tsx, 1, 75)) + +f<{ [a < ((x: T) => c > (d))]: T }>(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>[a < ((x: T) => c > (d))] : Symbol([a < ((x: T) => c > (d))], Decl(expressions.tsx, 40, 3)) +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>x : Symbol(x, Decl(expressions.tsx, 40, 11)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>d : Symbol(d, Decl(expressions.tsx, 1, 37)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f<{ [a < [b > (c)]]: T }>(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>[a < [b > (c)]] : Symbol([a < [b > (c)]], Decl(expressions.tsx, 41, 3)) +>a : Symbol(a, Decl(expressions.tsx, 1, 13)) +>b : Symbol(b, Decl(expressions.tsx, 1, 21)) +>c : Symbol(c, Decl(expressions.tsx, 1, 29)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>U : Symbol(U, Decl(expressions.tsx, 2, 13)) + +f<[T, U]>(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>U : Symbol(U, Decl(expressions.tsx, 2, 13)) + +f<{ x: T; m(x: T): U }>(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>x : Symbol(x, Decl(expressions.tsx, 44, 3)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>m : Symbol(m, Decl(expressions.tsx, 44, 9)) +>x : Symbol(x, Decl(expressions.tsx, 44, 12)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>U : Symbol(U, Decl(expressions.tsx, 2, 13)) + +f<{ [K in keyof T]: T[K] }>(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>K : Symbol(K, Decl(expressions.tsx, 45, 5)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>K : Symbol(K, Decl(expressions.tsx, 45, 5)) + +f U>(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>x : Symbol(x, Decl(expressions.tsx, 46, 7)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>U : Symbol(U, Decl(expressions.tsx, 2, 13)) + +f(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>U : Symbol(U, Decl(expressions.tsx, 2, 13)) +>X : Symbol(X, Decl(expressions.tsx, 3, 16)) +>Y : Symbol(Y, Decl(expressions.tsx, 4, 16)) + +f(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) + +f<`prefix${T}`>(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>X : Symbol(X, Decl(expressions.tsx, 50, 7)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>X : Symbol(X, Decl(expressions.tsx, 51, 7)) +>U : Symbol(U, Decl(expressions.tsx, 2, 13)) +>X : Symbol(X, Decl(expressions.tsx, 3, 16)) + +f<{ /** @type {(T} @see x */ x: T }>(); +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>x : Symbol(x, Decl(expressions.tsx, 52, 3)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f<() => T>`text`; +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f<() => T>`text${1}`; +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + +f<() => T>; +>f : Symbol(f, Decl(expressions.tsx, 5, 16)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) + diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.types b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.types new file mode 100644 index 0000000000000..8178806f47282 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.types @@ -0,0 +1,738 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts] //// + +=== expressions.ts === +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +>a : any +>b : any +>c : any +>d : any +>e : any +>B : any +>options : any +>x : any + +type T = any; +>T : any + +type U = string; +>U : string + +type X = number; +>X : number + +type Y = string; +>Y : string + +declare function f(...args: any[]): any; +>f : (...args: any[]) => any +>args : any[] + +declare function g(...args: any[]): any; +>g : (...args: any[]) => any +>args : any[] + +// Typed, empty, and async arrows remain expressions. +a < ((x: T) => c > (d)); +>a < ((x: T) => c > (d)) : boolean +>a : any +>((x: T) => c > (d)) : (x: T) => boolean +>(x: T) => c > (d) : (x: T) => boolean +>x : any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < ((x: T) => c > d); +>a < ((x: T) => c > d) : boolean +>a : any +>((x: T) => c > d) : (x: T) => boolean +>(x: T) => c > d : (x: T) => boolean +>x : any +>c > d : boolean +>c : any +>d : any + +a < (() => c > (d)); +>a < (() => c > (d)) : boolean +>a : any +>(() => c > (d)) : () => boolean +>() => c > (d) : () => boolean +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < (() => c > d); +>a < (() => c > d) : boolean +>a : any +>(() => c > d) : () => boolean +>() => c > d : () => boolean +>c > d : boolean +>c : any +>d : any + +a < (async (x: T) => c > (d)); +>a < (async (x: T) => c > (d)) : boolean +>a : any +>(async (x: T) => c > (d)) : (x: T) => Promise +>async (x: T) => c > (d) : (x: T) => Promise +>x : any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < (async (x: T) => c > d); +>a < (async (x: T) => c > d) : boolean +>a : any +>(async (x: T) => c > d) : (x: T) => Promise +>async (x: T) => c > d : (x: T) => Promise +>x : any +>c > d : boolean +>c : any +>d : any + +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +>a < [b > (c)] : boolean +>a : any +>[b > (c)] : boolean[] +>b > (c) : boolean +>b : any +>(c) : any +>c : any + +a < [b > `c`]; +>a < [b > `c`] : boolean +>a : any +>[b > `c`] : boolean[] +>b > `c` : boolean +>b : any +>`c` : "c" + +a < b[c > (d)]; +>a < b[c > (d)] : boolean +>a : any +>b[c > (d)] : error +>b : any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < c[d > (e) ? 0 : 1]; +>a < c[d > (e) ? 0 : 1] : boolean +>a : any +>c[d > (e) ? 0 : 1] : any +>c : any +>d > (e) ? 0 : 1 : 0 | 1 +>d > (e) : boolean +>d : any +>(e) : any +>e : any +>0 : 0 +>1 : 1 + +a < {b: c > (d)}; +>a < {b: c > (d)} : boolean +>a : any +>{b: c > (d)} : { b: boolean; } +>b : boolean +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < new B > (c); +>a < new B > (c) : boolean +>a < new B : boolean +>a : any +>new B : any +>B : any +>(c) : any +>c : any + +a < keyof [b > (c)]; +>a < keyof [b > (c)] : boolean +>a : any +>keyof [b > (c)] : error +>keyof : error +>b > (c) : boolean +>b : any +>(c) : any +>c : any + +a < import("m", options) > (c); +>a < import("m", options) > (c) : boolean +>a < import("m", options) : boolean +>a : any +>import("m", options) : Promise +>"m" : "m" +>options : any +>(c) : any +>c : any + +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +>console.log(a < b, (c > (d & e))) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>a < b : boolean +>a : any +>b : any +>(c > (d & e)) : boolean +>c > (d & e) : boolean +>c : any +>(d & e) : number +>d & e : number +>d : any +>e : any + +console.log(a < b, (((c > (d & e))))); +>console.log(a < b, (((c > (d & e))))) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>a < b : boolean +>a : any +>b : any +>(((c > (d & e)))) : boolean +>((c > (d & e))) : boolean +>(c > (d & e)) : boolean +>c > (d & e) : boolean +>c : any +>(d & e) : number +>d & e : number +>d : any +>e : any + +f(a < b, [c > (d)]); +>f(a < b, [c > (d)]) : any +>f : (...args: any[]) => any +>a < b : boolean +>a : any +>b : any +>[c > (d)] : boolean[] +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +f(a < b, {c: d > (e)}); +>f(a < b, {c: d > (e)}) : any +>f : (...args: any[]) => any +>a < b : boolean +>a : any +>b : any +>{c: d > (e)} : { c: boolean; } +>c : boolean +>d > (e) : boolean +>d : any +>(e) : any +>e : any + +f(a < b, [g(c > (d))]); +>f(a < b, [g(c > (d))]) : any +>f : (...args: any[]) => any +>a < b : boolean +>a : any +>b : any +>[g(c > (d))] : any[] +>g(c > (d)) : any +>g : (...args: any[]) => any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +// Completed type arguments still take precedence over relational expressions. +f(1); +>f(1) : any +>f : (...args: any[]) => any +>1 : 1 + +f<(x: T) => T>(1); +>f<(x: T) => T>(1) : any +>f : (...args: any[]) => any +>x : any +>1 : 1 + +f<() => T>(1); +>f<() => T>(1) : any +>f : (...args: any[]) => any +>1 : 1 + +f<((x: T) => T)>(1); +>f<((x: T) => T)>(1) : any +>f : (...args: any[]) => any +>x : any +>1 : 1 + +f<(x: T) => (T)>(x); +>f<(x: T) => (T)>(x) : any +>f : (...args: any[]) => any +>x : T +>x : any + +f<{ [a < ((x: T) => c > (d))]: T }>(); +>f<{ [a < ((x: T) => c > (d))]: T }>() : any +>f : (...args: any[]) => any +>[a < ((x: T) => c > (d))] : any +>a < ((x: T) => c > (d)) : boolean +>a : any +>((x: T) => c > (d)) : (x: T) => boolean +>(x: T) => c > (d) : (x: T) => boolean +>x : any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +f<{ [a < [b > (c)]]: T }>(); +>f<{ [a < [b > (c)]]: T }>() : any +>f : (...args: any[]) => any +>[a < [b > (c)]] : any +>a < [b > (c)] : boolean +>a : any +>[b > (c)] : boolean[] +>b > (c) : boolean +>b : any +>(c) : any +>c : any + +f(); +>f() : any +>f : (...args: any[]) => any + +f<[T, U]>(); +>f<[T, U]>() : any +>f : (...args: any[]) => any + +f<{ x: T; m(x: T): U }>(); +>f<{ x: T; m(x: T): U }>() : any +>f : (...args: any[]) => any +>x : any +>m : (x: T) => U +>x : any + +f<{ [K in keyof T]: T[K] }>(); +>f<{ [K in keyof T]: T[K] }>() : any +>f : (...args: any[]) => any + +f U>(); +>f U>() : any +>f : (...args: any[]) => any +>x : any + +f(); +>f() : any +>f : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any +>type : error + +f<`prefix${T}`>(); +>f<`prefix${T}`>() : any +>f : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any + +f<{ /** @type {(T} @see x */ x: T }>(); +>f<{ /** @type {(T} @see x */ x: T }>() : any +>f : (...args: any[]) => any +>x : any + +f<() => T>`text`; +>f<() => T>`text` : any +>f : (...args: any[]) => any +>`text` : "text" + +f<() => T>`text${1}`; +>f<() => T>`text${1}` : any +>f : (...args: any[]) => any +>`text${1}` : string +>1 : 1 + +f<() => T>; +>f<() => T> : (...args: any[]) => any +>f : (...args: any[]) => any + +=== expressions.tsx === +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +>a : any +>b : any +>c : any +>d : any +>e : any +>B : any +>options : any +>x : any + +type T = any; +>T : any + +type U = string; +>U : string + +type X = number; +>X : number + +type Y = string; +>Y : string + +declare function f(...args: any[]): any; +>f : (...args: any[]) => any +>args : any[] + +declare function g(...args: any[]): any; +>g : (...args: any[]) => any +>args : any[] + +// Typed, empty, and async arrows remain expressions. +a < ((x: T) => c > (d)); +>a < ((x: T) => c > (d)) : boolean +>a : any +>((x: T) => c > (d)) : (x: T) => boolean +>(x: T) => c > (d) : (x: T) => boolean +>x : any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < ((x: T) => c > d); +>a < ((x: T) => c > d) : boolean +>a : any +>((x: T) => c > d) : (x: T) => boolean +>(x: T) => c > d : (x: T) => boolean +>x : any +>c > d : boolean +>c : any +>d : any + +a < (() => c > (d)); +>a < (() => c > (d)) : boolean +>a : any +>(() => c > (d)) : () => boolean +>() => c > (d) : () => boolean +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < (() => c > d); +>a < (() => c > d) : boolean +>a : any +>(() => c > d) : () => boolean +>() => c > d : () => boolean +>c > d : boolean +>c : any +>d : any + +a < (async (x: T) => c > (d)); +>a < (async (x: T) => c > (d)) : boolean +>a : any +>(async (x: T) => c > (d)) : (x: T) => Promise +>async (x: T) => c > (d) : (x: T) => Promise +>x : any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < (async (x: T) => c > d); +>a < (async (x: T) => c > d) : boolean +>a : any +>(async (x: T) => c > d) : (x: T) => Promise +>async (x: T) => c > d : (x: T) => Promise +>x : any +>c > d : boolean +>c : any +>d : any + +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +>a < [b > (c)] : boolean +>a : any +>[b > (c)] : boolean[] +>b > (c) : boolean +>b : any +>(c) : any +>c : any + +a < [b > `c`]; +>a < [b > `c`] : boolean +>a : any +>[b > `c`] : boolean[] +>b > `c` : boolean +>b : any +>`c` : "c" + +a < b[c > (d)]; +>a < b[c > (d)] : boolean +>a : any +>b[c > (d)] : error +>b : any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < c[d > (e) ? 0 : 1]; +>a < c[d > (e) ? 0 : 1] : boolean +>a : any +>c[d > (e) ? 0 : 1] : any +>c : any +>d > (e) ? 0 : 1 : 0 | 1 +>d > (e) : boolean +>d : any +>(e) : any +>e : any +>0 : 0 +>1 : 1 + +a < {b: c > (d)}; +>a < {b: c > (d)} : boolean +>a : any +>{b: c > (d)} : { b: boolean; } +>b : boolean +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +a < new B > (c); +>a < new B > (c) : boolean +>a < new B : boolean +>a : any +>new B : any +>B : any +>(c) : any +>c : any + +a < keyof [b > (c)]; +>a < keyof [b > (c)] : boolean +>a : any +>keyof [b > (c)] : error +>keyof : error +>b > (c) : boolean +>b : any +>(c) : any +>c : any + +a < import("m", options) > (c); +>a < import("m", options) > (c) : boolean +>a < import("m", options) : boolean +>a : any +>import("m", options) : Promise +>"m" : "m" +>options : any +>(c) : any +>c : any + +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +>console.log(a < b, (c > (d & e))) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>a < b : boolean +>a : any +>b : any +>(c > (d & e)) : boolean +>c > (d & e) : boolean +>c : any +>(d & e) : number +>d & e : number +>d : any +>e : any + +console.log(a < b, (((c > (d & e))))); +>console.log(a < b, (((c > (d & e))))) : void +>console.log : (...data: any[]) => void +>console : Console +>log : (...data: any[]) => void +>a < b : boolean +>a : any +>b : any +>(((c > (d & e)))) : boolean +>((c > (d & e))) : boolean +>(c > (d & e)) : boolean +>c > (d & e) : boolean +>c : any +>(d & e) : number +>d & e : number +>d : any +>e : any + +f(a < b, [c > (d)]); +>f(a < b, [c > (d)]) : any +>f : (...args: any[]) => any +>a < b : boolean +>a : any +>b : any +>[c > (d)] : boolean[] +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +f(a < b, {c: d > (e)}); +>f(a < b, {c: d > (e)}) : any +>f : (...args: any[]) => any +>a < b : boolean +>a : any +>b : any +>{c: d > (e)} : { c: boolean; } +>c : boolean +>d > (e) : boolean +>d : any +>(e) : any +>e : any + +f(a < b, [g(c > (d))]); +>f(a < b, [g(c > (d))]) : any +>f : (...args: any[]) => any +>a < b : boolean +>a : any +>b : any +>[g(c > (d))] : any[] +>g(c > (d)) : any +>g : (...args: any[]) => any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +// Completed type arguments still take precedence over relational expressions. +f(1); +>f(1) : any +>f : (...args: any[]) => any +>1 : 1 + +f<(x: T) => T>(1); +>f<(x: T) => T>(1) : any +>f : (...args: any[]) => any +>x : any +>1 : 1 + +f<() => T>(1); +>f<() => T>(1) : any +>f : (...args: any[]) => any +>1 : 1 + +f<((x: T) => T)>(1); +>f<((x: T) => T)>(1) : any +>f : (...args: any[]) => any +>x : any +>1 : 1 + +f<(x: T) => (T)>(x); +>f<(x: T) => (T)>(x) : any +>f : (...args: any[]) => any +>x : T +>x : any + +f<{ [a < ((x: T) => c > (d))]: T }>(); +>f<{ [a < ((x: T) => c > (d))]: T }>() : any +>f : (...args: any[]) => any +>[a < ((x: T) => c > (d))] : any +>a < ((x: T) => c > (d)) : boolean +>a : any +>((x: T) => c > (d)) : (x: T) => boolean +>(x: T) => c > (d) : (x: T) => boolean +>x : any +>c > (d) : boolean +>c : any +>(d) : any +>d : any + +f<{ [a < [b > (c)]]: T }>(); +>f<{ [a < [b > (c)]]: T }>() : any +>f : (...args: any[]) => any +>[a < [b > (c)]] : any +>a < [b > (c)] : boolean +>a : any +>[b > (c)] : boolean[] +>b > (c) : boolean +>b : any +>(c) : any +>c : any + +f(); +>f() : any +>f : (...args: any[]) => any + +f<[T, U]>(); +>f<[T, U]>() : any +>f : (...args: any[]) => any + +f<{ x: T; m(x: T): U }>(); +>f<{ x: T; m(x: T): U }>() : any +>f : (...args: any[]) => any +>x : any +>m : (x: T) => U +>x : any + +f<{ [K in keyof T]: T[K] }>(); +>f<{ [K in keyof T]: T[K] }>() : any +>f : (...args: any[]) => any + +f U>(); +>f U>() : any +>f : (...args: any[]) => any +>x : any + +f(); +>f() : any +>f : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any +>type : error + +f<`prefix${T}`>(); +>f<`prefix${T}`>() : any +>f : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any + +f(); +>f() : any +>f : (...args: any[]) => any + +f<{ /** @type {(T} @see x */ x: T }>(); +>f<{ /** @type {(T} @see x */ x: T }>() : any +>f : (...args: any[]) => any +>x : any + +f<() => T>`text`; +>f<() => T>`text` : any +>f : (...args: any[]) => any +>`text` : "text" + +f<() => T>`text${1}`; +>f<() => T>`text${1}` : any +>f : (...args: any[]) => any +>`text${1}` : string +>1 : 1 + +f<() => T>; +>f<() => T> : (...args: any[]) => any +>f : (...args: any[]) => any + diff --git a/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRecovery.ts b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRecovery.ts new file mode 100644 index 0000000000000..5fcf0e31b0d6f --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRecovery.ts @@ -0,0 +1,117 @@ +// @strict: true +// @noCheck: true +// @target: esnext +// @module: esnext +// @jsx: preserve + +// @filename: recovery.ts +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +type T = any; +type U = string; +type X = number; +type Y = string; +declare function f(...args: any[]): any; +declare function g(...args: any[]): any; + +// Recovery and rollback preserve diagnostics and the following call. +f(); +g<(T)>(); + +f; +g<(T)>(); + +f<"\xZ">(); +g<(T)>(); + +f<010>(); +g<(T)>(); + +f<("\xZ")>(); +g<(T)>(); + +f<(010)>(); +g<(T)>(); + +f<((x: T) => "\xZ")>(); +g<(T)>(); + +f(); +g<(T)>(); + +f<("\xZ" > (x)); +g<(T)>(); + +f(); +g<(T)>(); + +f(); +g<(T)>(); + +f U>(); +g<(T)>(); + +f<() => >(); +g<(T)>(); + +f(); +g<(T)>(); + +f<{ [(() => { type Bad = (T; return key; })()]: U }>(); +g<(T)>(); + +// @filename: recovery.tsx +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +type T = any; +type U = string; +type X = number; +type Y = string; +declare function f(...args: any[]): any; +declare function g(...args: any[]): any; + +// Recovery and rollback preserve diagnostics and the following call. +f(); +g<(T)>(); + +f; +g<(T)>(); + +f<"\xZ">(); +g<(T)>(); + +f<010>(); +g<(T)>(); + +f<("\xZ")>(); +g<(T)>(); + +f<(010)>(); +g<(T)>(); + +f<((x: T) => "\xZ")>(); +g<(T)>(); + +f(); +g<(T)>(); + +f<("\xZ" > (x)); +g<(T)>(); + +f(); +g<(T)>(); + +f(); +g<(T)>(); + +f U>(); +g<(T)>(); + +f<() => >(); +g<(T)>(); + +f(); +g<(T)>(); + +f<{ [(() => { type Bad = (T; return key; })()]: U }>(); +g<(T)>(); diff --git a/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts new file mode 100644 index 0000000000000..aa3eba1e76031 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts @@ -0,0 +1,121 @@ +// @strict: true +// @noCheck: true +// @target: esnext +// @module: esnext +// @jsx: preserve + +// @filename: expressions.ts +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +type T = any; +type U = string; +type X = number; +type Y = string; +declare function f(...args: any[]): any; +declare function g(...args: any[]): any; + +// Typed, empty, and async arrows remain expressions. +a < ((x: T) => c > (d)); +a < ((x: T) => c > d); +a < (() => c > (d)); +a < (() => c > d); +a < (async (x: T) => c > (d)); +a < (async (x: T) => c > d); + +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +a < [b > `c`]; +a < b[c > (d)]; +a < c[d > (e) ? 0 : 1]; +a < {b: c > (d)}; +a < new B > (c); +a < keyof [b > (c)]; +a < import("m", options) > (c); + +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +console.log(a < b, (((c > (d & e))))); +f(a < b, [c > (d)]); +f(a < b, {c: d > (e)}); +f(a < b, [g(c > (d))]); + +// Completed type arguments still take precedence over relational expressions. +f(1); +f<(x: T) => T>(1); +f<() => T>(1); +f<((x: T) => T)>(1); +f<(x: T) => (T)>(x); +f<{ [a < ((x: T) => c > (d))]: T }>(); +f<{ [a < [b > (c)]]: T }>(); +f(); +f<[T, U]>(); +f<{ x: T; m(x: T): U }>(); +f<{ [K in keyof T]: T[K] }>(); +f U>(); +f(); +f(); +f<`prefix${T}`>(); +f(); +f(); +f<{ /** @type {(T} @see x */ x: T }>(); +f<() => T>`text`; +f<() => T>`text${1}`; +f<() => T>; + +// @filename: expressions.tsx +export {}; +declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; +type T = any; +type U = string; +type X = number; +type Y = string; +declare function f(...args: any[]): any; +declare function g(...args: any[]): any; + +// Typed, empty, and async arrows remain expressions. +a < ((x: T) => c > (d)); +a < ((x: T) => c > d); +a < (() => c > (d)); +a < (() => c > d); +a < (async (x: T) => c > (d)); +a < (async (x: T) => c > d); + +// Expression containers must be structurally complete before accepting type arguments. +a < [b > (c)]; +a < [b > `c`]; +a < b[c > (d)]; +a < c[d > (e) ? 0 : 1]; +a < {b: c > (d)}; +a < new B > (c); +a < keyof [b > (c)]; +a < import("m", options) > (c); + +// Relational expressions must preserve the outer argument list (#60874). +console.log(a < b, (c > (d & e))); +console.log(a < b, (((c > (d & e))))); +f(a < b, [c > (d)]); +f(a < b, {c: d > (e)}); +f(a < b, [g(c > (d))]); + +// Completed type arguments still take precedence over relational expressions. +f(1); +f<(x: T) => T>(1); +f<() => T>(1); +f<((x: T) => T)>(1); +f<(x: T) => (T)>(x); +f<{ [a < ((x: T) => c > (d))]: T }>(); +f<{ [a < [b > (c)]]: T }>(); +f(); +f<[T, U]>(); +f<{ x: T; m(x: T): U }>(); +f<{ [K in keyof T]: T[K] }>(); +f U>(); +f(); +f(); +f<`prefix${T}`>(); +f(); +f(); +f<{ /** @type {(T} @see x */ x: T }>(); +f<() => T>`text`; +f<() => T>`text${1}`; +f<() => T>; From 91ae59f3f009776d11504ef2917d64682456f28f Mon Sep 17 00:00:00 2001 From: magic-akari Date: Sun, 15 Nov 2026 20:45:52 +0800 Subject: [PATCH 2/4] Add regressions for related type argument speculation issues --- .../typeArgumentSpeculationRelatedIssues.js | 103 ++++++++++ ...peArgumentSpeculationRelatedIssues.symbols | 133 +++++++++++++ ...typeArgumentSpeculationRelatedIssues.types | 178 ++++++++++++++++++ .../typeArgumentSpeculationRelatedIssues.ts | 60 ++++++ 4 files changed, 474 insertions(+) create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.js create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.symbols create mode 100644 tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.types create mode 100644 tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelatedIssues.ts diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.js b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.js new file mode 100644 index 0000000000000..bc24e8748057c --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.js @@ -0,0 +1,103 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRelatedIssues.ts] //// + +//// [issue37760.ts] +// https://github.com/microsoft/TypeScript/issues/37760 +export {}; +function alignof(): number { + return 1; +} + +// A right shift already parsed correctly. +function foo(): number { + return 1 >> alignof(); +} + +// A left shift must not become two type-argument openers. +function bar(): number { + return 1 << alignof(); +} + +function baz(): number { + // @ts-ignore + return 1 << alignof(); +} + +//// [issue43720.ts] +// https://github.com/microsoft/TypeScript/issues/43720 +export {}; +declare const res: any; +for (let i = 0; i < ((res).Data).length; i++) { } + +// The original report's extracted-condition workaround remains equivalent. +let ln = ((res).Data).length; +for (let i = 0; i < ln; i++) { } + +//// [issue61975.ts] +// https://github.com/microsoft/TypeScript/issues/61975 +export {}; +class Pantries { + constructor(precise: A) { + this.precise = precise; + } + precise: A; +} + +function sparrow(): boolean { + const sobbed: boolean = true; + return "abc" < (sobbed ? new Pantries("a") : new Pantries("b")).precise; +} + +function sparrow1(): string { + const sobbed: boolean = true; + return (sobbed ? new Pantries("a") : new Pantries("b")).precise; +} + +function sparrow2(): boolean { + const sobbed: boolean = true; + return "abc" < (sobbed ? (new Pantries("a")) : new Pantries("b")).precise; +} + + +//// [issue37760.js] +function alignof() { + return 1; +} +// A right shift already parsed correctly. +function foo() { + return 1 >> alignof(); +} +// A left shift must not become two type-argument openers. +function bar() { + return 1 << alignof(); +} +function baz() { + // @ts-ignore + return 1 << alignof(); +} +export {}; +//// [issue43720.js] +for (let i = 0; i < res.Data.length; i++) { } +// The original report's extracted-condition workaround remains equivalent. +let ln = res.Data.length; +for (let i = 0; i < ln; i++) { } +export {}; +//// [issue61975.js] +class Pantries { + constructor(precise) { + this.precise = precise; + } + precise; +} +function sparrow() { + const sobbed = true; + return "abc" < (sobbed ? new Pantries("a") : new Pantries("b")).precise; +} +function sparrow1() { + const sobbed = true; + return (sobbed ? new Pantries("a") : new Pantries("b")).precise; +} +function sparrow2() { + const sobbed = true; + return "abc" < (sobbed ? (new Pantries("a")) : new Pantries("b")).precise; +} +export {}; diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.symbols b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.symbols new file mode 100644 index 0000000000000..3e963f9cbc231 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.symbols @@ -0,0 +1,133 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRelatedIssues.ts] //// + +=== issue37760.ts === +// https://github.com/microsoft/TypeScript/issues/37760 +export {}; +function alignof(): number { +>alignof : Symbol(alignof, Decl(issue37760.ts, 1, 10)) +>T : Symbol(T, Decl(issue37760.ts, 2, 17)) + + return 1; +} + +// A right shift already parsed correctly. +function foo(): number { +>foo : Symbol(foo, Decl(issue37760.ts, 4, 1)) +>T : Symbol(T, Decl(issue37760.ts, 7, 13)) + + return 1 >> alignof(); +>alignof : Symbol(alignof, Decl(issue37760.ts, 1, 10)) +>T : Symbol(T, Decl(issue37760.ts, 7, 13)) +} + +// A left shift must not become two type-argument openers. +function bar(): number { +>bar : Symbol(bar, Decl(issue37760.ts, 9, 1)) +>T : Symbol(T, Decl(issue37760.ts, 12, 13)) + + return 1 << alignof(); +>alignof : Symbol(alignof, Decl(issue37760.ts, 1, 10)) +>T : Symbol(T, Decl(issue37760.ts, 12, 13)) +} + +function baz(): number { +>baz : Symbol(baz, Decl(issue37760.ts, 14, 1)) +>T : Symbol(T, Decl(issue37760.ts, 16, 13)) + + // @ts-ignore + return 1 << alignof(); +>alignof : Symbol(alignof, Decl(issue37760.ts, 1, 10)) +>T : Symbol(T, Decl(issue37760.ts, 16, 13)) +} + +=== issue43720.ts === +// https://github.com/microsoft/TypeScript/issues/43720 +export {}; +declare const res: any; +>res : Symbol(res, Decl(issue43720.ts, 2, 13)) + +for (let i = 0; i < ((res).Data).length; i++) { } +>i : Symbol(i, Decl(issue43720.ts, 3, 8)) +>i : Symbol(i, Decl(issue43720.ts, 3, 8)) +>((res).Data).length : Symbol(Array.length, Decl(lib.es5.d.ts, --, --)) +>res : Symbol(res, Decl(issue43720.ts, 2, 13)) +>length : Symbol(Array.length, Decl(lib.es5.d.ts, --, --)) +>i : Symbol(i, Decl(issue43720.ts, 3, 8)) + +// The original report's extracted-condition workaround remains equivalent. +let ln = ((res).Data).length; +>ln : Symbol(ln, Decl(issue43720.ts, 6, 3)) +>((res).Data).length : Symbol(Array.length, Decl(lib.es5.d.ts, --, --)) +>res : Symbol(res, Decl(issue43720.ts, 2, 13)) +>length : Symbol(Array.length, Decl(lib.es5.d.ts, --, --)) + +for (let i = 0; i < ln; i++) { } +>i : Symbol(i, Decl(issue43720.ts, 7, 8)) +>i : Symbol(i, Decl(issue43720.ts, 7, 8)) +>ln : Symbol(ln, Decl(issue43720.ts, 6, 3)) +>i : Symbol(i, Decl(issue43720.ts, 7, 8)) + +=== issue61975.ts === +// https://github.com/microsoft/TypeScript/issues/61975 +export {}; +class Pantries { +>Pantries : Symbol(Pantries, Decl(issue61975.ts, 1, 10)) +>A : Symbol(A, Decl(issue61975.ts, 2, 15)) + + constructor(precise: A) { +>precise : Symbol(precise, Decl(issue61975.ts, 3, 16)) +>A : Symbol(A, Decl(issue61975.ts, 2, 15)) + + this.precise = precise; +>this.precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +>this : Symbol(Pantries, Decl(issue61975.ts, 1, 10)) +>precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +>precise : Symbol(precise, Decl(issue61975.ts, 3, 16)) + } + precise: A; +>precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +>A : Symbol(A, Decl(issue61975.ts, 2, 15)) +} + +function sparrow(): boolean { +>sparrow : Symbol(sparrow, Decl(issue61975.ts, 7, 1)) + + const sobbed: boolean = true; +>sobbed : Symbol(sobbed, Decl(issue61975.ts, 10, 9)) + + return "abc" < (sobbed ? new Pantries("a") : new Pantries("b")).precise; +>(sobbed ? new Pantries("a") : new Pantries("b")).precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +>sobbed : Symbol(sobbed, Decl(issue61975.ts, 10, 9)) +>Pantries : Symbol(Pantries, Decl(issue61975.ts, 1, 10)) +>Pantries : Symbol(Pantries, Decl(issue61975.ts, 1, 10)) +>precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +} + +function sparrow1(): string { +>sparrow1 : Symbol(sparrow1, Decl(issue61975.ts, 12, 1)) + + const sobbed: boolean = true; +>sobbed : Symbol(sobbed, Decl(issue61975.ts, 15, 9)) + + return (sobbed ? new Pantries("a") : new Pantries("b")).precise; +>(sobbed ? new Pantries("a") : new Pantries("b")).precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +>sobbed : Symbol(sobbed, Decl(issue61975.ts, 15, 9)) +>Pantries : Symbol(Pantries, Decl(issue61975.ts, 1, 10)) +>Pantries : Symbol(Pantries, Decl(issue61975.ts, 1, 10)) +>precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +} + +function sparrow2(): boolean { +>sparrow2 : Symbol(sparrow2, Decl(issue61975.ts, 17, 1)) + + const sobbed: boolean = true; +>sobbed : Symbol(sobbed, Decl(issue61975.ts, 20, 9)) + + return "abc" < (sobbed ? (new Pantries("a")) : new Pantries("b")).precise; +>(sobbed ? (new Pantries("a")) : new Pantries("b")).precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +>sobbed : Symbol(sobbed, Decl(issue61975.ts, 20, 9)) +>Pantries : Symbol(Pantries, Decl(issue61975.ts, 1, 10)) +>Pantries : Symbol(Pantries, Decl(issue61975.ts, 1, 10)) +>precise : Symbol(Pantries.precise, Decl(issue61975.ts, 5, 5)) +} + diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.types b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.types new file mode 100644 index 0000000000000..de298f13cf61e --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelatedIssues.types @@ -0,0 +1,178 @@ +//// [tests/cases/compiler/typeArgumentSpeculationRelatedIssues.ts] //// + +=== issue37760.ts === +// https://github.com/microsoft/TypeScript/issues/37760 +export {}; +function alignof(): number { +>alignof : () => number + + return 1; +>1 : 1 +} + +// A right shift already parsed correctly. +function foo(): number { +>foo : () => number + + return 1 >> alignof(); +>1 >> alignof() : number +>1 : 1 +>alignof() : number +>alignof : () => number +} + +// A left shift must not become two type-argument openers. +function bar(): number { +>bar : () => number + + return 1 << alignof(); +>1 << alignof() : number +>1 : 1 +>alignof() : number +>alignof : () => number +} + +function baz(): number { +>baz : () => number + + // @ts-ignore + return 1 << alignof(); +>1 << alignof() : number +>1 : 1 +>alignof() : number +>alignof : () => number +} + +=== issue43720.ts === +// https://github.com/microsoft/TypeScript/issues/43720 +export {}; +declare const res: any; +>res : any + +for (let i = 0; i < ((res).Data).length; i++) { } +>i : number +>0 : 0 +>i < ((res).Data).length : boolean +>i : number +>((res).Data).length : number +>((res).Data) : any[] +>(res).Data : any[] +>(res).Data : any +>(res) : any +>res : any +>res : any +>Data : any +>length : number +>i++ : number +>i : number + +// The original report's extracted-condition workaround remains equivalent. +let ln = ((res).Data).length; +>ln : number +>((res).Data).length : number +>((res).Data) : any[] +>(res).Data : any[] +>(res).Data : any +>(res) : any +>res : any +>res : any +>Data : any +>length : number + +for (let i = 0; i < ln; i++) { } +>i : number +>0 : 0 +>i < ln : boolean +>i : number +>ln : number +>i++ : number +>i : number + +=== issue61975.ts === +// https://github.com/microsoft/TypeScript/issues/61975 +export {}; +class Pantries { +>Pantries : Pantries + + constructor(precise: A) { +>precise : A + + this.precise = precise; +>this.precise = precise : A +>this.precise : A +>this : this +>precise : A +>precise : A + } + precise: A; +>precise : A +} + +function sparrow(): boolean { +>sparrow : () => boolean + + const sobbed: boolean = true; +>sobbed : boolean +>true : true + + return "abc" < (sobbed ? new Pantries("a") : new Pantries("b")).precise; +>"abc" < (sobbed ? new Pantries("a") : new Pantries("b")).precise : boolean +>"abc" : "abc" +>(sobbed ? new Pantries("a") : new Pantries("b")).precise : string +>(sobbed ? new Pantries("a") : new Pantries("b")) : Pantries +>sobbed ? new Pantries("a") : new Pantries("b") : Pantries +>sobbed : true +>new Pantries("a") : Pantries +>Pantries : typeof Pantries +>"a" : "a" +>new Pantries("b") : Pantries +>Pantries : typeof Pantries +>"b" : "b" +>precise : string +} + +function sparrow1(): string { +>sparrow1 : () => string + + const sobbed: boolean = true; +>sobbed : boolean +>true : true + + return (sobbed ? new Pantries("a") : new Pantries("b")).precise; +>(sobbed ? new Pantries("a") : new Pantries("b")).precise : string +>(sobbed ? new Pantries("a") : new Pantries("b")) : Pantries +>sobbed ? new Pantries("a") : new Pantries("b") : Pantries +>sobbed : true +>new Pantries("a") : Pantries +>Pantries : typeof Pantries +>"a" : "a" +>new Pantries("b") : Pantries +>Pantries : typeof Pantries +>"b" : "b" +>precise : string +} + +function sparrow2(): boolean { +>sparrow2 : () => boolean + + const sobbed: boolean = true; +>sobbed : boolean +>true : true + + return "abc" < (sobbed ? (new Pantries("a")) : new Pantries("b")).precise; +>"abc" < (sobbed ? (new Pantries("a")) : new Pantries("b")).precise : boolean +>"abc" : "abc" +>(sobbed ? (new Pantries("a")) : new Pantries("b")).precise : string +>(sobbed ? (new Pantries("a")) : new Pantries("b")) : Pantries +>sobbed ? (new Pantries("a")) : new Pantries("b") : Pantries +>sobbed : true +>(new Pantries("a")) : Pantries +>new Pantries("a") : Pantries +>Pantries : typeof Pantries +>"a" : "a" +>new Pantries("b") : Pantries +>Pantries : typeof Pantries +>"b" : "b" +>precise : string +} + diff --git a/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelatedIssues.ts b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelatedIssues.ts new file mode 100644 index 0000000000000..aec111dc898ec --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelatedIssues.ts @@ -0,0 +1,60 @@ +// @strict: true +// @target: esnext +// @module: esnext + +// @filename: issue37760.ts +// https://github.com/microsoft/TypeScript/issues/37760 +export {}; +function alignof(): number { + return 1; +} + +// A right shift already parsed correctly. +function foo(): number { + return 1 >> alignof(); +} + +// A left shift must not become two type-argument openers. +function bar(): number { + return 1 << alignof(); +} + +function baz(): number { + // @ts-ignore + return 1 << alignof(); +} + +// @filename: issue43720.ts +// https://github.com/microsoft/TypeScript/issues/43720 +export {}; +declare const res: any; +for (let i = 0; i < ((res).Data).length; i++) { } + +// The original report's extracted-condition workaround remains equivalent. +let ln = ((res).Data).length; +for (let i = 0; i < ln; i++) { } + +// @filename: issue61975.ts +// https://github.com/microsoft/TypeScript/issues/61975 +export {}; +class Pantries { + constructor(precise: A) { + this.precise = precise; + } + precise: A; +} + +function sparrow(): boolean { + const sobbed: boolean = true; + return "abc" < (sobbed ? new Pantries("a") : new Pantries("b")).precise; +} + +function sparrow1(): string { + const sobbed: boolean = true; + return (sobbed ? new Pantries("a") : new Pantries("b")).precise; +} + +function sparrow2(): boolean { + const sobbed: boolean = true; + return "abc" < (sobbed ? (new Pantries("a")) : new Pantries("b")).precise; +} From c88af1448d45d73ed859410caa3611eb2aec8719 Mon Sep 17 00:00:00 2001 From: magic-akari Date: Sun, 15 Nov 2026 23:12:12 +0800 Subject: [PATCH 3/4] perf(parser): avoid repeated speculative parsing Give member and call suffixes a shared entry point so a failed type-argument interpretation is not retried by an initial member-expression pass. Share angle-closure facts across nested probes to avoid rescanning the same suffix. Remember structural failures in their parsing context so later attempts skip type and type-argument candidates already known to fail. Reuse diagnostic-free value-expression boundaries during disposable arrow and type-argument probes instead of repeatedly building subtrees that will be discarded. Rebuild opaque values before committing a successful outer probe, preserving binding recovery, lexical diagnostics, and comment directives. Restore queued JSDoc declarations and diagnostics when discarding a probe so rebuilding its AST does not insert them twice. Exclude values already carrying diagnostics or producing JSDoc side effects from boundary reuse, avoiding redundant arrow reconstruction during recovery. --- tsc/internal/parser/parser.go | 183 +++++++++++------- tsc/internal/parser/speculative_expression.go | 139 +++++++++++++ .../parser/type_argument_lookahead.go | 136 +++++++++++++ tsc/internal/parser/type_parser_test.go | 92 +++++++++ tsc/internal/scanner/scanner.go | 9 + .../arrowFunctionSpeculationJSDoc.symbols | 57 ++++++ .../arrowFunctionSpeculationJSDoc.types | 75 +++++++ ...typeArgumentSpeculationRecovery.errors.txt | 46 ++++- .../typeArgumentSpeculationRecovery.js | 14 ++ .../typeArgumentSpeculationRecovery.symbols | 16 ++ .../typeArgumentSpeculationRecovery.types | 34 ++++ ...ArgumentSpeculationRelationalExpression.js | 10 + ...entSpeculationRelationalExpression.symbols | 28 +++ ...umentSpeculationRelationalExpression.types | 26 +++ .../compiler/arrowFunctionSpeculationJSDoc.ts | 29 +++ .../typeArgumentSpeculationRecovery.ts | 6 + ...ArgumentSpeculationRelationalExpression.ts | 6 + 17 files changed, 830 insertions(+), 76 deletions(-) create mode 100644 tsc/internal/parser/speculative_expression.go create mode 100644 tsc/internal/parser/type_argument_lookahead.go create mode 100644 tsc/testdata/baselines/reference/compiler/arrowFunctionSpeculationJSDoc.symbols create mode 100644 tsc/testdata/baselines/reference/compiler/arrowFunctionSpeculationJSDoc.types create mode 100644 tsc/testdata/tests/cases/compiler/arrowFunctionSpeculationJSDoc.ts diff --git a/tsc/internal/parser/parser.go b/tsc/internal/parser/parser.go index 11bf53a262561..4cb1de9493b51 100644 --- a/tsc/internal/parser/parser.go +++ b/tsc/internal/parser/parser.go @@ -66,6 +66,14 @@ type Parser struct { // Grammar policies stay immutable during a parse, including nested speculation. recoveringTypes typeParser speculativeTypes typeParser + // Prediction facts survive speculation; no AST handles are retained. + typeArgumentClosures map[int]bool + inExpressionProbe bool + // Opaque values taint the whole probe, including lookaheads that rewind. + hasOpaqueExpression bool + failedTypeArguments collections.Set[speculationKey] + failedSpeculativeTypes collections.Set[speculationKey] + probeExpressions map[probeExpressionKey]probeExpressionBoundary scanner *scanner.Scanner factory ast.NodeFactory @@ -351,12 +359,15 @@ type ParserState struct { contextFlags ast.NodeFlags diagnosticsLen int jsDiagnosticsLen int + jsdocDiagnosticsLen int jsdocInfosLen int reparsedClonesLen int + reparseList []*ast.Node statementHasAwaitIdentifier bool hasParseError bool commonJSModuleIndicator *ast.Node jsdocHasCommonJSConstruct bool + inExpressionProbe bool } func (p *Parser) mark() ParserState { @@ -365,12 +376,15 @@ func (p *Parser) mark() ParserState { contextFlags: p.contextFlags, diagnosticsLen: len(p.diagnostics), jsDiagnosticsLen: len(p.jsDiagnostics), + jsdocDiagnosticsLen: len(p.jsdocDiagnostics), jsdocInfosLen: len(p.jsdocInfos), reparsedClonesLen: len(p.reparsedClones), + reparseList: p.reparseList, statementHasAwaitIdentifier: p.statementHasAwaitIdentifier, hasParseError: p.hasParseError, commonJSModuleIndicator: p.commonJSModuleIndicator, jsdocHasCommonJSConstruct: p.jsdocHasCommonJSConstruct, + inExpressionProbe: p.inExpressionProbe, } } @@ -380,12 +394,15 @@ func (p *Parser) rewind(state ParserState) { p.contextFlags = state.contextFlags p.diagnostics = p.diagnostics[0:state.diagnosticsLen] p.jsDiagnostics = p.jsDiagnostics[0:state.jsDiagnosticsLen] + p.jsdocDiagnostics = p.jsdocDiagnostics[:state.jsdocDiagnosticsLen] p.jsdocInfos = p.jsdocInfos[0:state.jsdocInfosLen] p.reparsedClones = p.reparsedClones[0:state.reparsedClonesLen] + p.reparseList = state.reparseList p.statementHasAwaitIdentifier = state.statementHasAwaitIdentifier p.hasParseError = state.hasParseError p.commonJSModuleIndicator = state.commonJSModuleIndicator p.jsdocHasCommonJSConstruct = state.jsdocHasCommonJSConstruct + p.inExpressionProbe = state.inExpressionProbe } func (p *Parser) lookAhead(callback func(p *Parser) bool) bool { @@ -649,8 +666,10 @@ func (p *Parser) reparseTopLevelAwait(sourceFile *ast.SourceFile) *ast.Node { } } - // Keep diagnostics from the reparse + // Keep diagnostics and pending declarations from the committed reparse. state.diagnosticsLen = len(p.diagnostics) + state.jsdocDiagnosticsLen = len(p.jsdocDiagnostics) + state.reparseList = p.reparseList p.rewind(state) } @@ -1809,7 +1828,7 @@ func (p *Parser) parseObjectBindingElement() *ast.Node { func (p *Parser) parseInitializer() *ast.Expression { if p.parseOptional(ast.KindEqualsToken) { - return p.parseAssignmentExpressionOrHigher() + return p.parseValueExpression(true /*allowReturnTypeInArrowFunction*/) } return nil } @@ -2791,7 +2810,21 @@ func (p *Parser) parseExportSpecifier() *ast.Node { func (p *typeParser) parseType() *ast.TypeNode { saveContextFlags := p.contextFlags p.setContextFlags(ast.NodeFlagsTypeExcludesFlags, false) + speculative := !p.allowAmbiguity && p.contextFlags&ast.NodeFlagsJSDoc == 0 + var key speculationKey + if speculative { + key = p.speculationKey() + if p.failedSpeculativeTypes.Has(key) { + p.contextFlags = saveContextFlags + return nil + } + } result := p.parseTypeWorker() + // Remember structural failure, including a nested failure. Diagnostics on a + // recognized type remain recoverable and do not reject the production. + if speculative && result == nil { + p.failedSpeculativeTypes.Add(key) + } p.contextFlags = saveContextFlags return result } @@ -3847,7 +3880,7 @@ func (p *typeParser) parseComputedPropertyName() *ast.Node { // We parse any expression (including a comma expression). But the grammar // says that only an assignment expression is allowed, so the grammar checker // will error if it sees a comma expression. - expression := p.parseExpressionAllowIn() + expression := p.parseComputedPropertyExpression() if !p.parseExpected(ast.KindCloseBracketToken) && !p.allowAmbiguity { return nil } @@ -4305,9 +4338,14 @@ func (p *Parser) skipParameterStart() bool { return true } if p.token == ast.KindOpenBracketToken || p.token == ast.KindOpenBraceToken { - // Return true if we can parse an array or object binding pattern with no errors + // Binding lookahead requires the complete pattern to be diagnostic-free. + // Its AST is discarded, so computed names and defaults can reuse values + // recognized by earlier probes without repeating their recursive work. previousErrorCount := len(p.diagnostics) + saveProbe := p.inExpressionProbe + p.inExpressionProbe = true p.parseIdentifierOrPattern() + p.inExpressionProbe = saveProbe return previousErrorCount == len(p.diagnostics) } return false @@ -4371,8 +4409,7 @@ func (p *Parser) parseDecoratorExpression() *ast.Expression { pos := p.nodePos() awaitExpression := p.parseIdentifierWithDiagnostic(diagnostics.Expression_expected, nil) p.nextToken() - memberExpression := p.parseMemberExpressionRest(pos, awaitExpression /*allowOptionalChain*/, true) - return p.parseCallExpressionRest(pos, memberExpression) + return p.parseCallExpressionRest(pos, awaitExpression) } return p.parseLeftHandSideExpressionOrHigher() } @@ -4602,7 +4639,7 @@ func (p *Parser) parseAssignmentExpressionOrHigherWorker(allowReturnTypeInArrowF // Note: we call reScanGreaterToken so that we get an appropriately merged token // for cases like `> > =` becoming `>>=` if ast.IsLeftHandSideExpression(expr) && ast.IsAssignmentOperator(p.reScanGreaterThanToken()) { - return p.makeBinaryExpression(expr, p.parseTokenNode(), p.parseAssignmentExpressionOrHigherWorker(allowReturnTypeInArrowFunction), pos) + return p.makeBinaryExpression(expr, p.parseTokenNode(), p.parseValueExpression(allowReturnTypeInArrowFunction), pos) } // It wasn't an assignment or a lambda. This is a conditional expression: return p.parseConditionalExpressionRest(expr, pos, allowReturnTypeInArrowFunction) @@ -4792,10 +4829,24 @@ func (p *Parser) tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInA return p.parseParenthesizedArrowFunctionExpression(true /*allowAmbiguity*/, true /*allowReturnTypeInArrowFunction*/) } state := p.mark() + if !p.inExpressionProbe { + p.hasOpaqueExpression = false + } + p.inExpressionProbe = true result := p.parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) if result == nil { p.rewind(state) + return nil + } + if !state.inExpressionProbe && p.hasOpaqueExpression { + p.rewind(state) + result = p.parseParenthesizedArrowFunctionExpression(false /*allowAmbiguity*/, allowReturnTypeInArrowFunction) + if result == nil { + p.rewind(state) + return nil + } } + p.inExpressionProbe = state.inExpressionProbe return result } @@ -5020,12 +5071,12 @@ func (p *Parser) parseConditionalExpressionRest(leftOperand *ast.Expression, pos // we do not that for the 'whenFalse' part. saveContextFlags := p.contextFlags p.setContextFlags(ast.NodeFlagsDisallowInContext, false) - trueExpression := p.parseAssignmentExpressionOrHigherWorker(false /*allowReturnTypeInArrowFunction*/) + trueExpression := p.parseValueExpression(false /*allowReturnTypeInArrowFunction*/) p.contextFlags = saveContextFlags colonToken := p.parseExpectedToken(ast.KindColonToken) var falseExpression *ast.Expression if ast.NodeIsPresent(colonToken) { - falseExpression = p.parseAssignmentExpressionOrHigherWorker(allowReturnTypeInArrowFunction) + falseExpression = p.parseValueExpression(allowReturnTypeInArrowFunction) } else { falseExpression = p.createMissingIdentifier() } @@ -5645,8 +5696,9 @@ func (p *Parser) parseLeftHandSideExpressionOrHigher() *ast.Expression { // MemberExpression // CallExpression // - // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with - // MemberExpression to make our lives easier. + // PrimaryExpression includes function and object creation expressions. Each new + // expression consumes its associated argument list; additional argument lists + // call the constructed value. // // to best understand the below code, it's important to see how CallExpression expands // out into its own productions: @@ -5663,8 +5715,8 @@ func (p *Parser) parseLeftHandSideExpressionOrHigher() *ast.Expression { // Because of the recursion in these calls, we need to bottom out first. There are three // bottom out states we can run into: 1) We see 'super' which must start either of // the last two CallExpression productions. 2) We see 'import' which must start import call. - // 3)we have a MemberExpression which either completes the LeftHandSideExpression, - // or starts the beginning of the first four CallExpression productions. + // 3) We have a PrimaryExpression, which the common postfix loop extends into + // a MemberExpression or one of the first four CallExpression productions. pos := p.nodePos() var expression *ast.Expression if p.token == ast.KindImportKeyword { @@ -5689,16 +5741,17 @@ func (p *Parser) parseLeftHandSideExpressionOrHigher() *ast.Expression { p.sourceFlags |= ast.NodeFlagsPossiblyContainsImportMeta } } else { - expression = p.parseMemberExpressionOrHigher() + expression = p.parsePrimaryExpression() } } else if p.token == ast.KindSuperKeyword { expression = p.parseSuperExpression() } else { - expression = p.parseMemberExpressionOrHigher() + expression = p.parsePrimaryExpression() } // Now, we *may* be complete. However, we might have consumed the start of a // CallExpression or OptionalExpression. As such, we need to consume the rest - // of it here to be complete. + // of it here to be complete. Member suffixes share this entry so a failed + // type-argument interpretation is not retried by an initial member pass. return p.parseCallExpressionRest(pos, expression) } @@ -5744,14 +5797,50 @@ func (p *Parser) isTemplateStartOfTaggedTemplate() bool { } func (p *Parser) tryParseTypeArgumentsInExpression() *ast.NodeList { - // TypeArguments must not be parsed in JavaScript files to avoid ambiguity with binary operators. - // Check the cheap preconditions before saving the parser state: unless the current token is `<` - // (or `<<`, which reScanLessThanToken would split), there is nothing to speculatively parse and - // the mark/rewind would be a no-op. if p.contextFlags&ast.NodeFlagsJavaScriptFile != 0 || (p.token != ast.KindLessThanToken && p.token != ast.KindLessThanLessThanToken) { return nil } + if !p.typeArgumentsMayClose() { + return nil + } state := p.mark() + if p.contextFlags&ast.NodeFlagsJSDoc != 0 { + result := p.parseTypeArgumentsInExpressionWorker() + if result == nil { + p.rewind(state) + } + return result + } + key := p.speculationKey() + if p.failedTypeArguments.Has(key) { + return nil + } + if !p.inExpressionProbe { + p.hasOpaqueExpression = false + } + p.inExpressionProbe = true + result := p.parseTypeArgumentsInExpressionWorker() + if result == nil { + p.rewind(state) + p.failedTypeArguments.Add(key) + return nil + } + if !state.inExpressionProbe && p.hasOpaqueExpression { + // Recognition may use opaque values, but no such AST can escape. + // Rebuild the recognized candidate with the ordinary expression parser. + p.rewind(state) + result = p.parseTypeArgumentsInExpressionWorker() + if result == nil { + p.rewind(state) + p.failedTypeArguments.Add(key) + return nil + } + } + p.inExpressionProbe = state.inExpressionProbe + return result +} + +func (p *Parser) parseTypeArgumentsInExpressionWorker() *ast.NodeList { if p.reScanLessThanToken() == ast.KindLessThanToken { p.nextToken() typeArguments := p.speculativeTypes.parseDelimitedList(PCTypeArguments, (*typeParser).parseType) @@ -5768,7 +5857,6 @@ func (p *Parser) tryParseTypeArgumentsInExpression() *ast.NodeList { } } } - p.rewind(state) return nil } @@ -5791,59 +5879,6 @@ func (p *Parser) canFollowTypeArgumentsInExpression() bool { return p.hasPrecedingLineBreak() || p.isBinaryOperator() || !p.isStartOfExpression() } -func (p *Parser) parseMemberExpressionOrHigher() *ast.Node { - // Note: to make our lives simpler, we decompose the NewExpression productions and - // place ObjectCreationExpression and FunctionExpression into PrimaryExpression. - // like so: - // - // PrimaryExpression : See 11.1 - // this - // Identifier - // Literal - // ArrayLiteral - // ObjectLiteral - // (Expression) - // FunctionExpression - // new MemberExpression Arguments? - // - // MemberExpression : See 11.2 - // PrimaryExpression - // MemberExpression[Expression] - // MemberExpression.IdentifierName - // - // CallExpression : See 11.2 - // MemberExpression - // CallExpression Arguments - // CallExpression[Expression] - // CallExpression.IdentifierName - // - // Technically this is ambiguous. i.e. CallExpression defines: - // - // CallExpression: - // CallExpression Arguments - // - // If you see: "new Foo()" - // - // Then that could be treated as a single ObjectCreationExpression, or it could be - // treated as the invocation of "new Foo". We disambiguate that in code (to match - // the original grammar) by making sure that if we see an ObjectCreationExpression - // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation. Another way to think - // about this is that for every "new" that we see, we will consume an argument list if - // it is there as part of the *associated* object creation node. Any additional - // argument lists we see, will become invocation expressions. - // - // Because there are no other places in the grammar now that refer to FunctionExpression - // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression - // production. - // - // Because CallExpression and MemberExpression are left recursive, we need to bottom out - // of the recursion immediately. So we parse out a primary expression to start with. - pos := p.nodePos() - expression := p.parsePrimaryExpression() - return p.parseMemberExpressionRest(pos, expression, true /*allowOptionalChain*/) -} - func (p *Parser) parseMemberExpressionRest(pos int, expression *ast.Expression, allowOptionalChain bool) *ast.Expression { for { var questionDotToken *ast.Node diff --git a/tsc/internal/parser/speculative_expression.go b/tsc/internal/parser/speculative_expression.go new file mode 100644 index 0000000000000..5cb4b74479408 --- /dev/null +++ b/tsc/internal/parser/speculative_expression.go @@ -0,0 +1,139 @@ +package parser + +import ( + "github.com/microsoft/TypeScript/tsc/internal/ast" + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/debug" + "github.com/microsoft/TypeScript/tsc/internal/scanner" +) + +type speculationKey struct { + position int + tokenEnd int + lastDiagnosticPosition int + contextFlags ast.NodeFlags + parsingContexts ParsingContexts + token ast.Kind + tokenFlags ast.TokenFlags + hasParseError bool + statementHasAwaitIdentifier bool +} + +type probeExpressionKind uint8 + +const ( + probeExpression probeExpressionKind = iota + probeAssignment + probeAssignmentWithoutArrowReturn +) + +type probeExpressionKey struct { + speculationKey + kind probeExpressionKind +} + +// Boundaries only describe diagnostic-free, disposable recognition passes. +// They retain no AST handles and never construct committed expressions. +type probeExpressionBoundary struct { + scannerState scanner.ScannerState + loc core.TextRange + flags ast.NodeFlags + hasParseError bool +} + +func (p *Parser) speculationKey() speculationKey { + position := p.nodePos() + lastDiagnosticPosition := -1 + if len(p.diagnostics) != 0 { + lastPosition := p.diagnostics[len(p.diagnostics)-1].Pos() + // Earlier diagnostics cannot be deduplicated with errors in this value. + if lastPosition >= position { + lastDiagnosticPosition = lastPosition + } + } + return speculationKey{ + position: position, + tokenEnd: p.scanner.TokenEnd(), + lastDiagnosticPosition: lastDiagnosticPosition, + contextFlags: p.contextFlags, + parsingContexts: p.parsingContexts, + token: p.token, + tokenFlags: p.scanner.TokenFlags(), + hasParseError: p.hasParseError, + statementHasAwaitIdentifier: p.statementHasAwaitIdentifier, + } +} + +// These entry points are used where the grammar needs a value and its end, +// rather than inspecting the value as an assignment target or binding cover. +// During a probe, callers must not inspect the returned expression's kind or +// children to choose a grammar production. A successful outer probe rebuilds +// any opaque values before committing its AST. +func (p *Parser) parseValueExpression(allowReturnTypeInArrowFunction bool) *ast.Expression { + if !p.inExpressionProbe || p.contextFlags&ast.NodeFlagsJSDoc != 0 { + return p.parseAssignmentExpressionOrHigherWorker(allowReturnTypeInArrowFunction) + } + kind := probeAssignment + if !allowReturnTypeInArrowFunction { + kind = probeAssignmentWithoutArrowReturn + } + return p.parseProbeExpression(kind) +} + +func (p *Parser) parseComputedPropertyExpression() *ast.Expression { + if !p.inExpressionProbe || p.contextFlags&ast.NodeFlagsJSDoc != 0 { + return p.parseExpressionAllowIn() + } + saveContextFlags := p.contextFlags + p.setContextFlags(ast.NodeFlagsDisallowInContext, false) + result := p.parseProbeExpression(probeExpression) + p.contextFlags = saveContextFlags + return result +} + +func (p *Parser) parseProbeExpression(kind probeExpressionKind) *ast.Expression { + debug.Assert(p.inExpressionProbe && p.contextFlags&ast.NodeFlagsJSDoc == 0, "Expression boundaries are only reusable in disposable probes") + key := probeExpressionKey{speculationKey: p.speculationKey(), kind: kind} + if boundary, known := p.probeExpressions[key]; known { + p.scanner.RewindPosition(boundary.scannerState) + p.token = p.scanner.Token() + p.hasParseError = boundary.hasParseError + // A nested lookahead may rewind its AST after observing this value. + // Keep the taint until the enclosing speculative parse is discarded. + p.hasOpaqueExpression = true + result := p.factory.NewIdentifier("") + result.Loc = boundary.loc + result.Flags = boundary.flags + p.identifierCount++ + return result + } + state := p.mark() + var result *ast.Expression + switch kind { + case probeExpression: + result = p.parseExpression() + case probeAssignment: + result = p.parseAssignmentExpressionOrHigherWorker(true /*allowReturnTypeInArrowFunction*/) + case probeAssignmentWithoutArrowReturn: + result = p.parseAssignmentExpressionOrHigherWorker(false /*allowReturnTypeInArrowFunction*/) + } + // A preceding operator can consume hasParseError after scanning the first + // token of this value. Its existing diagnostics still prevent boundary reuse. + if result != nil && !state.hasParseError && key.lastDiagnosticPosition < 0 && + len(p.diagnostics) == state.diagnosticsLen && len(p.jsDiagnostics) == state.jsDiagnosticsLen && + len(p.jsdocDiagnostics) == state.jsdocDiagnosticsLen && len(p.reparseList) == len(state.reparseList) && + p.commonJSModuleIndicator == state.commonJSModuleIndicator && p.jsdocHasCommonJSConstruct == state.jsdocHasCommonJSConstruct && + p.statementHasAwaitIdentifier == state.statementHasAwaitIdentifier { + boundary := probeExpressionBoundary{ + scannerState: p.scanner.Mark(), + loc: result.Loc, + flags: result.Flags, + hasParseError: p.hasParseError, + } + if p.probeExpressions == nil { + p.probeExpressions = make(map[probeExpressionKey]probeExpressionBoundary) + } + p.probeExpressions[key] = boundary + } + return result +} diff --git a/tsc/internal/parser/type_argument_lookahead.go b/tsc/internal/parser/type_argument_lookahead.go new file mode 100644 index 0000000000000..6a6898dda81b8 --- /dev/null +++ b/tsc/internal/parser/type_argument_lookahead.go @@ -0,0 +1,136 @@ +package parser + +import ( + "github.com/microsoft/TypeScript/tsc/internal/ast" + "github.com/microsoft/TypeScript/tsc/internal/core" +) + +type typeArgumentDelimiter struct { + kind ast.Kind + angleStart int +} + +// typeArgumentsMayClose only rejects lists whose closing angle cannot belong +// to the opening token. Parentheses, brackets, and braces fence off inner +// angles, so a comparison inside a group cannot close an outer type list. +// All openings encountered by a scan share its closure facts; nested attempts +// do not repeatedly scan the same suffix. A lexical ambiguity leaves the +// decision to the type grammar, including its diagnostics and recovery. +// A negative proof uses only group fences, semicolons, and EOF in the normal +// lexical goal. Unknown lexical goals and mismatched groups are inconclusive; +// new lexical goals must also defer to grammar instead of rejecting a list. +func (p *Parser) typeArgumentsMayClose() bool { + start := p.scanner.TokenStart() + if mayClose, known := p.typeArgumentClosures[start]; known { + return mayClose + } + if p.hasParseError || p.contextFlags&ast.NodeFlagsJSDoc != 0 { + return true + } + state := p.mark() + defer p.rewind(state) + angles := make([]int, 1, 8) + angles[0] = start + hasNestedSyntax := p.token == ast.KindLessThanLessThanToken + if hasNestedSyntax { + angles = append(angles, start+1) + } + var groups []typeArgumentDelimiter + for { + p.nextToken() + if p.hasParseError { + p.recordTypeArgumentClosures(angles, true) + return true + } + switch p.token { + case ast.KindSlashToken, ast.KindSlashEqualsToken, ast.KindTemplateHead: + // Selecting the regular-expression/template lexical goal needs grammar. + p.recordTypeArgumentClosures(angles, true) + return true + case ast.KindLessThanToken, ast.KindLessThanLessThanToken: + angles = append(angles, p.scanner.TokenStart()) + if p.token == ast.KindLessThanLessThanToken { + angles = append(angles, p.scanner.TokenStart()+1) + } + // Nested starts may require the JSX lexical goal. + if p.languageVariant == core.LanguageVariantJSX && len(groups) != 0 { + p.recordTypeArgumentClosures(angles, true) + return true + } + hasNestedSyntax = true + case ast.KindOpenParenToken, ast.KindOpenBracketToken, ast.KindOpenBraceToken: + groups = append(groups, typeArgumentDelimiter{kind: p.token, angleStart: len(angles)}) + hasNestedSyntax = true + case ast.KindCloseParenToken, ast.KindCloseBracketToken, ast.KindCloseBraceToken: + if len(groups) == 0 { + p.recordTypeArgumentClosures(angles, false) + return false + } + group := groups[len(groups)-1] + groups = groups[:len(groups)-1] + if !matchingTypeArgumentDelimiter(group.kind, p.token) { + p.recordTypeArgumentClosures(angles, true) + return true + } + p.recordTypeArgumentClosures(angles[group.angleStart:], false) + angles = angles[:group.angleStart] + case ast.KindEndOfFile: + p.recordTypeArgumentClosures(angles, false) + return false + case ast.KindSemicolonToken: + angleStart := 0 + if len(groups) != 0 { + angleStart = groups[len(groups)-1].angleStart + } + p.recordTypeArgumentClosures(angles[angleStart:], false) + angles = angles[:angleStart] + if len(groups) == 0 { + return false + } + case ast.KindGreaterThanToken: + // Scan returns one '>' at a time; this lookahead never rescans it. + angleStart := 0 + if len(groups) != 0 { + angleStart = groups[len(groups)-1].angleStart + } + remaining := max(angleStart, len(angles)-1) + // Simple lists need no index allocation: the grammar consumes them + // immediately, and their lookahead contains no recursive work. + if hasNestedSyntax { + p.recordTypeArgumentClosures(angles[remaining:], true) + } + angles = angles[:remaining] + if remaining == 0 { + return true + } + } + } +} + +func (p *Parser) recordTypeArgumentClosures(angles []int, mayClose bool) { + if len(angles) == 0 { + return + } + if p.typeArgumentClosures == nil { + p.typeArgumentClosures = make(map[int]bool) + } + for _, position := range angles { + // A proof of non-closure takes precedence over an inconclusive scan. + if previous, known := p.typeArgumentClosures[position]; !known || previous { + p.typeArgumentClosures[position] = mayClose + } + } +} + +func matchingTypeArgumentDelimiter(opening ast.Kind, closing ast.Kind) bool { + switch opening { + case ast.KindOpenParenToken: + return closing == ast.KindCloseParenToken + case ast.KindOpenBracketToken: + return closing == ast.KindCloseBracketToken + case ast.KindOpenBraceToken: + return closing == ast.KindCloseBraceToken + default: + panic("Unexpected type-argument delimiter") + } +} diff --git a/tsc/internal/parser/type_parser_test.go b/tsc/internal/parser/type_parser_test.go index 254c91cfc3b0a..bb877696c79be 100644 --- a/tsc/internal/parser/type_parser_test.go +++ b/tsc/internal/parser/type_parser_test.go @@ -6,6 +6,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/diagnostics" "gotest.tools/v3/assert" ) @@ -47,3 +48,94 @@ func TestInferConstraintSpeculationFailure(t *testing.T) { assert.Assert(t, !ok) assert.Assert(t, reflect.DeepEqual(p.mark(), state)) } + +func TestTypeArgumentClosureLookaheadRollback(t *testing.T) { + t.Parallel() + p := newParser() + p.initializeState(ast.SourceFileParseOptions{FileName: "/index.ts", PathKey: "/index.ts"}, "< // @ts-ignore\n\"\\xZ\">();", core.ScriptKindTS) + p.nextToken() + state := p.mark() + assert.Assert(t, p.typeArgumentsMayClose()) + assert.Assert(t, reflect.DeepEqual(p.mark(), state)) + // The real scan must still observe the directive and its lexical diagnostic. + p.nextToken() + assert.Equal(t, len(p.scanner.CommentDirectives()), 1) + assert.Equal(t, len(p.diagnostics), 1) + assert.Equal(t, p.diagnostics[0].Code(), diagnostics.Hexadecimal_digit_expected.Code()) +} + +func TestProbeExpressionBoundaryRollback(t *testing.T) { + t.Parallel() + p := newParser() + p.initializeState(ast.SourceFileParseOptions{FileName: "/index.ts", PathKey: "/index.ts"}, "x + y // @ts-ignore\n;", core.ScriptKindTS) + p.nextToken() + p.inExpressionProbe = true + state := p.mark() + first := p.parseValueExpression(true) + assert.Equal(t, first.Kind, ast.KindBinaryExpression) + assert.Equal(t, len(p.probeExpressions), 1) + p.rewind(state) + assert.Assert(t, p.lookAhead(func(p *Parser) bool { + // A cache hit is opaque and belongs only to this disposable lookahead. + return p.parseValueExpression(true).Kind == ast.KindIdentifier + })) + assert.Assert(t, reflect.DeepEqual(p.mark(), state)) + assert.Assert(t, p.hasOpaqueExpression) + assert.Equal(t, len(p.scanner.CommentDirectives()), 0) + p.inExpressionProbe = false + committed := p.parseValueExpression(true) + assert.Equal(t, committed.Kind, ast.KindBinaryExpression) + assert.Equal(t, len(p.scanner.CommentDirectives()), 1) +} + +func TestJSDocSpeculationRollback(t *testing.T) { + t.Parallel() + p := newParser() + p.initializeState(ast.SourceFileParseOptions{FileName: "/index.js", PathKey: "/index.js"}, `/** @typedef {number} Local */ +const local = 0; +/** @returns { */ +function broken() {}`, core.ScriptKindJS) + p.nextToken() + retainedDeclaration := p.factory.NewIdentifier("retained") + retainedDiagnostic := ast.NewDiagnostic(nil, core.NewTextRange(0, 0), diagnostics.Type_expected) + p.reparseList = []*ast.Node{retainedDeclaration} + p.jsdocDiagnostics = []*ast.Diagnostic{retainedDiagnostic} + state := p.mark() + assert.Assert(t, p.lookAhead(func(p *Parser) bool { + assert.Equal(t, p.parseStatement().Kind, ast.KindVariableStatement) + assert.Equal(t, p.parseStatement().Kind, ast.KindFunctionDeclaration) + assert.Assert(t, len(p.reparseList) > 1) + assert.Assert(t, len(p.jsdocDiagnostics) > 1) + return true + })) + assert.Equal(t, len(p.reparseList), 1) + assert.Assert(t, p.reparseList[0] == retainedDeclaration) + assert.Equal(t, len(p.jsdocDiagnostics), 1) + assert.Assert(t, p.jsdocDiagnostics[0] == retainedDiagnostic) + assert.Assert(t, reflect.DeepEqual(p.mark(), state)) +} + +func TestProbeExpressionBoundaryWithScanError(t *testing.T) { + t.Parallel() + for _, source := range []string{`"\xZ";`, `= "\xZ";`} { + t.Run(source, func(t *testing.T) { + t.Parallel() + p := newParser() + p.initializeState(ast.SourceFileParseOptions{FileName: "/index.ts", PathKey: "/index.ts"}, source, core.ScriptKindTS) + p.nextToken() + if p.token == ast.KindEqualsToken { + // The operator node consumes the error flag on the following token. + p.parseTokenNode() + } + p.inExpressionProbe = true + state := p.mark() + assert.Equal(t, len(p.diagnostics), 1) + assert.Equal(t, p.parseValueExpression(true).Kind, ast.KindStringLiteral) + p.rewind(state) + assert.Equal(t, p.parseValueExpression(true).Kind, ast.KindStringLiteral) + assert.Assert(t, !p.hasOpaqueExpression) + assert.Equal(t, len(p.diagnostics), 1) + assert.Equal(t, p.diagnostics[0].Code(), diagnostics.Hexadecimal_digit_expected.Code()) + }) + } +} diff --git a/tsc/internal/scanner/scanner.go b/tsc/internal/scanner/scanner.go index 7dc5199678d93..64034767f5c07 100644 --- a/tsc/internal/scanner/scanner.go +++ b/tsc/internal/scanner/scanner.go @@ -343,6 +343,15 @@ func (s *Scanner) Rewind(state ScannerState) { s.ScannerState = state } +// RewindPosition restores lexical state without replacing the caller's +// collected directives. Disposable grammar probes do not replay collection +// effects when they reuse an expression boundary. +func (s *Scanner) RewindPosition(state ScannerState) { + directives := s.commentDirectives + s.ScannerState = state + s.commentDirectives = directives +} + func (s *Scanner) ResetPos(pos int) { if pos < 0 { panic("Cannot reset token state to negative position") diff --git a/tsc/testdata/baselines/reference/compiler/arrowFunctionSpeculationJSDoc.symbols b/tsc/testdata/baselines/reference/compiler/arrowFunctionSpeculationJSDoc.symbols new file mode 100644 index 0000000000000..2106f99c4674a --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/arrowFunctionSpeculationJSDoc.symbols @@ -0,0 +1,57 @@ +//// [tests/cases/compiler/arrowFunctionSpeculationJSDoc.ts] //// + +=== types.d.ts === +export interface Key {} +>Key : Symbol(Key, Decl(types.d.ts, 0, 0)) + +=== index.js === +export {}; +const key = "k"; +>key : Symbol(key, Decl(index.js, 1, 5)) + +const result = (a) => ({ +>result : Symbol(result, Decl(index.js, 2, 5)) +>a : Symbol(a, Decl(index.js, 2, 16)) + + [String((b) => ({ +>[String((b) => ({ [String((c) => ({ [String(key)]: 0 }))]: 0 }))] : Symbol([String((b) => ({ + [String((c) => ({ [String(key)]: 0 }))]: 0 + }))], Decl(index.js, 2, 24)) +>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 7 more) +>b : Symbol(b, Decl(index.js, 3, 13)) + + [String((c) => ({ [String(key)]: 0 }))]: 0 +>[String((c) => ({ [String(key)]: 0 }))] : Symbol([String((c) => ({ [String(key)]: 0 }))], Decl(index.js, 3, 21)) +>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 7 more) +>c : Symbol(c, Decl(index.js, 4, 17)) +>[String(key)] : Symbol([String(key)], Decl(index.js, 4, 25)) +>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 7 more) +>key : Symbol(key, Decl(index.js, 1, 5)) + + }))]: 0, + /** @typedef {number} Local */ + typedef() {}, +>typedef : Symbol(typedef, Decl(index.js, 5, 12)) + + /** @callback Callback */ + callback() {}, +>callback : Symbol(callback, Decl(index.js, 7, 17)) + + /** @import {Key} from "./types" */ + imported() {} +>imported : Symbol(imported, Decl(index.js, 9, 18)) + +}); + +/** @type {Local} */ +const local = 1; +>local : Symbol(local, Decl(index.js, 15, 5)) + +/** @type {Callback} */ +const callback = () => {}; +>callback : Symbol(callback, Decl(index.js, 17, 5)) + +/** @type {Key} */ +const imported = {}; +>imported : Symbol(imported, Decl(index.js, 19, 5)) + diff --git a/tsc/testdata/baselines/reference/compiler/arrowFunctionSpeculationJSDoc.types b/tsc/testdata/baselines/reference/compiler/arrowFunctionSpeculationJSDoc.types new file mode 100644 index 0000000000000..3712a9614d93b --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/arrowFunctionSpeculationJSDoc.types @@ -0,0 +1,75 @@ +//// [tests/cases/compiler/arrowFunctionSpeculationJSDoc.ts] //// + +=== types.d.ts === + +export interface Key {} + +=== index.js === +export {}; +const key = "k"; +>key : "k" +>"k" : "k" + +const result = (a) => ({ +>result : (a: any) => { [x: string]: number | (() => void); typedef(): void; callback(): void; imported(): void; } +>(a) => ({ [String((b) => ({ [String((c) => ({ [String(key)]: 0 }))]: 0 }))]: 0, /** @typedef {number} Local */ typedef() {}, /** @callback Callback */ callback() {}, /** @import {Key} from "./types" */ imported() {}}) : (a: any) => { [x: string]: number | (() => void); typedef(): void; callback(): void; imported(): void; } +>a : any +>({ [String((b) => ({ [String((c) => ({ [String(key)]: 0 }))]: 0 }))]: 0, /** @typedef {number} Local */ typedef() {}, /** @callback Callback */ callback() {}, /** @import {Key} from "./types" */ imported() {}}) : { [x: string]: number | (() => void); typedef(): void; callback(): void; imported(): void; } +>{ [String((b) => ({ [String((c) => ({ [String(key)]: 0 }))]: 0 }))]: 0, /** @typedef {number} Local */ typedef() {}, /** @callback Callback */ callback() {}, /** @import {Key} from "./types" */ imported() {}} : { [x: string]: number | (() => void); typedef(): void; callback(): void; imported(): void; } + + [String((b) => ({ +>[String((b) => ({ [String((c) => ({ [String(key)]: 0 }))]: 0 }))] : number +>String((b) => ({ [String((c) => ({ [String(key)]: 0 }))]: 0 })) : string +>String : StringConstructor +>(b) => ({ [String((c) => ({ [String(key)]: 0 }))]: 0 }) : (b: any) => { [x: string]: number; } +>b : any +>({ [String((c) => ({ [String(key)]: 0 }))]: 0 }) : { [x: string]: number; } +>{ [String((c) => ({ [String(key)]: 0 }))]: 0 } : { [x: string]: number; } + + [String((c) => ({ [String(key)]: 0 }))]: 0 +>[String((c) => ({ [String(key)]: 0 }))] : number +>String((c) => ({ [String(key)]: 0 })) : string +>String : StringConstructor +>(c) => ({ [String(key)]: 0 }) : (c: any) => { [x: string]: number; } +>c : any +>({ [String(key)]: 0 }) : { [x: string]: number; } +>{ [String(key)]: 0 } : { [x: string]: number; } +>[String(key)] : number +>String(key) : string +>String : StringConstructor +>key : "k" +>0 : 0 +>0 : 0 + + }))]: 0, +>0 : 0 + + /** @typedef {number} Local */ + typedef() {}, +>typedef : () => void + + /** @callback Callback */ + callback() {}, +>callback : () => void + + /** @import {Key} from "./types" */ + imported() {} +>imported : () => void + +}); + +/** @type {Local} */ +const local = 1; +>local : number +>1 : 1 + +/** @type {Callback} */ +const callback = () => {}; +>callback : Callback +>() => {} : () => void + +/** @type {Key} */ +const imported = {}; +>imported : Key +>{} : {} + diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.errors.txt b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.errors.txt index 1096ccb5f7138..bab777c34d4ab 100644 --- a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.errors.txt +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.errors.txt @@ -13,6 +13,12 @@ recovery.ts(44,6): error TS1385: Function type notation must be parenthesized wh recovery.ts(47,9): error TS1110: Type expected. recovery.ts(50,5): error TS1003: Identifier expected. recovery.ts(53,28): error TS1005: ')' expected. +recovery.ts(56,13): error TS1125: Hexadecimal digit expected. +recovery.ts(56,17): error TS1005: ')' expected. +recovery.ts(56,19): error TS1434: Unexpected keyword or identifier. +recovery.ts(56,20): error TS1128: Declaration or statement expected. +recovery.ts(56,22): error TS1128: Declaration or statement expected. +recovery.ts(56,28): error TS1109: Expression expected. recovery.tsx(11,5): error TS1110: Type expected. recovery.tsx(14,4): error TS1110: Type expected. recovery.tsx(17,6): error TS1125: Hexadecimal digit expected. @@ -28,9 +34,15 @@ recovery.tsx(44,6): error TS1385: Function type notation must be parenthesized w recovery.tsx(47,9): error TS1110: Type expected. recovery.tsx(50,5): error TS1003: Identifier expected. recovery.tsx(53,28): error TS1005: ')' expected. +recovery.tsx(56,13): error TS1125: Hexadecimal digit expected. +recovery.tsx(56,17): error TS1005: ')' expected. +recovery.tsx(56,19): error TS1434: Unexpected keyword or identifier. +recovery.tsx(56,20): error TS1128: Declaration or statement expected. +recovery.tsx(56,22): error TS1128: Declaration or statement expected. +recovery.tsx(56,28): error TS1109: Expression expected. -==== recovery.ts (15 errors) ==== +==== recovery.ts (21 errors) ==== export {}; declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; type T = any; @@ -116,7 +128,22 @@ recovery.tsx(53,28): error TS1005: ')' expected. !!! error TS1005: ')' expected. g<(T)>(); -==== recovery.tsx (15 errors) ==== + f<({ p = "\xZ" }: T) => U>(); + +!!! error TS1125: Hexadecimal digit expected. + ~ +!!! error TS1005: ')' expected. + ~ +!!! error TS1434: Unexpected keyword or identifier. + ~ +!!! error TS1128: Declaration or statement expected. + ~~ +!!! error TS1128: Declaration or statement expected. + ~ +!!! error TS1109: Expression expected. + g<(T)>(); + +==== recovery.tsx (21 errors) ==== export {}; declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; type T = any; @@ -201,4 +228,19 @@ recovery.tsx(53,28): error TS1005: ')' expected. ~ !!! error TS1005: ')' expected. g<(T)>(); + + f<({ p = "\xZ" }: T) => U>(); + +!!! error TS1125: Hexadecimal digit expected. + ~ +!!! error TS1005: ')' expected. + ~ +!!! error TS1434: Unexpected keyword or identifier. + ~ +!!! error TS1128: Declaration or statement expected. + ~~ +!!! error TS1128: Declaration or statement expected. + ~ +!!! error TS1109: Expression expected. + g<(T)>(); \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.js b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.js index f97b17865b97a..9d567e8434cfa 100644 --- a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.js +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.js @@ -55,6 +55,9 @@ g<(T)>(); f<{ [(() => { type Bad = (T; return key; })()]: U }>(); g<(T)>(); + +f<({ p = "\xZ" }: T) => U>(); +g<(T)>(); //// [recovery.tsx] export {}; @@ -111,6 +114,9 @@ g<(T)>(); f<{ [(() => { type Bad = (T; return key; })()]: U }>(); g<(T)>(); + +f<({ p = "\xZ" }: T) => U>(); +g<(T)>(); //// [recovery.js] @@ -145,6 +151,10 @@ f(); g(); f(); g(); +f < ({ p = "\xZ" }); +T; +U > (); +g(); export {}; //// [recovery.jsx] // Recovery and rollback preserve diagnostics and the following call. @@ -178,4 +188,8 @@ f(); g(); f(); g(); +f < ({ p = "\xZ" }); +T; +U > (); +g(); export {}; diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.symbols b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.symbols index e75ed46bd7e57..4aa699fac01d6 100644 --- a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.symbols +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.symbols @@ -165,6 +165,14 @@ g<(T)>(); >g : Symbol(g, Decl(recovery.ts, 6, 66)) >T : Symbol(T, Decl(recovery.ts, 1, 83)) +f<({ p = "\xZ" }: T) => U>(); +>f : Symbol(f, Decl(recovery.ts, 5, 16)) +>p : Symbol(p, Decl(recovery.ts, 55, 4)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.ts, 6, 66)) +>T : Symbol(T, Decl(recovery.ts, 1, 83)) + === recovery.tsx === export {}; declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; @@ -330,3 +338,11 @@ g<(T)>(); >g : Symbol(g, Decl(recovery.tsx, 6, 66)) >T : Symbol(T, Decl(recovery.tsx, 1, 83)) +f<({ p = "\xZ" }: T) => U>(); +>f : Symbol(f, Decl(recovery.tsx, 5, 16)) +>p : Symbol(p, Decl(recovery.tsx, 55, 4)) + +g<(T)>(); +>g : Symbol(g, Decl(recovery.tsx, 6, 66)) +>T : Symbol(T, Decl(recovery.tsx, 1, 83)) + diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.types b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.types index 6df7cc8504452..f8ac59f0ff72c 100644 --- a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.types +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRecovery.types @@ -167,6 +167,23 @@ g<(T)>(); >g<(T)>() : any >g : (...args: any[]) => any +f<({ p = "\xZ" }: T) => U>(); +>f<({ p = "\xZ" } : boolean +>f : (...args: any[]) => any +>({ p = "\xZ" } : { p: string; } +>{ p = "\xZ" } : { p: string; } +>p : any +>"\xZ" : "\\xZ" +>T : any +>U>() : boolean +>U : any +>() : any +> : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + === recovery.tsx === export {}; declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; @@ -334,3 +351,20 @@ g<(T)>(); >g<(T)>() : any >g : (...args: any[]) => any +f<({ p = "\xZ" }: T) => U>(); +>f<({ p = "\xZ" } : boolean +>f : (...args: any[]) => any +>({ p = "\xZ" } : { p: string; } +>{ p = "\xZ" } : { p: string; } +>p : any +>"\xZ" : "\\xZ" +>T : any +>U>() : boolean +>U : any +>() : any +> : any + +g<(T)>(); +>g<(T)>() : any +>g : (...args: any[]) => any + diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.js b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.js index 1b8350969202f..24731c4bf452a 100644 --- a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.js +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.js @@ -57,6 +57,9 @@ f<{ /** @type {(T} @see x */ x: T }>(); f<() => T>`text`; f<() => T>`text${1}`; f<() => T>; + +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z; //// [expressions.tsx] export {}; @@ -115,6 +118,9 @@ f<{ /** @type {(T} @see x */ x: T }>(); f<() => T>`text`; f<() => T>`text${1}`; f<() => T>; + +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z; //// [expressions.js] @@ -162,6 +168,8 @@ f(); f `text`; f `text${1}`; f; +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g()]: z = g() }) => z; export {}; //// [expressions.jsx] // Typed, empty, and async arrows remain expressions. @@ -208,4 +216,6 @@ f(); f `text`; f `text${1}`; f; +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g()]: z = g() }) => z; export {}; diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.symbols b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.symbols index 0697ba99aa2ad..b10f435185e17 100644 --- a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.symbols +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.symbols @@ -284,6 +284,20 @@ f<() => T>; >f : Symbol(f, Decl(expressions.ts, 5, 16)) >T : Symbol(T, Decl(expressions.ts, 1, 83)) +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z; +>probe : Symbol(probe, Decl(expressions.ts, 58, 5)) +>g : Symbol(g, Decl(expressions.ts, 6, 66)) +>x : Symbol(x, Decl(expressions.ts, 1, 75)) +>y : Symbol(y, Decl(expressions.ts, 58, 22)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>U : Symbol(U, Decl(expressions.ts, 2, 13)) +>z : Symbol(z, Decl(expressions.ts, 58, 16)) +>g : Symbol(g, Decl(expressions.ts, 6, 66)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>T : Symbol(T, Decl(expressions.ts, 1, 83)) +>z : Symbol(z, Decl(expressions.ts, 58, 16)) + === expressions.tsx === export {}; declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; @@ -568,3 +582,17 @@ f<() => T>; >f : Symbol(f, Decl(expressions.tsx, 5, 16)) >T : Symbol(T, Decl(expressions.tsx, 1, 83)) +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z; +>probe : Symbol(probe, Decl(expressions.tsx, 58, 5)) +>g : Symbol(g, Decl(expressions.tsx, 6, 66)) +>x : Symbol(x, Decl(expressions.tsx, 1, 75)) +>y : Symbol(y, Decl(expressions.tsx, 58, 22)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>U : Symbol(U, Decl(expressions.tsx, 2, 13)) +>z : Symbol(z, Decl(expressions.tsx, 58, 16)) +>g : Symbol(g, Decl(expressions.tsx, 6, 66)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>T : Symbol(T, Decl(expressions.tsx, 1, 83)) +>z : Symbol(z, Decl(expressions.tsx, 58, 16)) + diff --git a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.types b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.types index 8178806f47282..f840eb70552b8 100644 --- a/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.types +++ b/tsc/testdata/baselines/reference/compiler/typeArgumentSpeculationRelationalExpression.types @@ -368,6 +368,19 @@ f<() => T>; >f<() => T> : (...args: any[]) => any >f : (...args: any[]) => any +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z; +>probe : ({ [g<({ [x]: y }: T) => U>()]: z }: T) => any +>({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z : ({ [g<({ [x]: y }: T) => U>()]: z }: T) => any +>g<({ [x]: y }: T) => U>() : any +>g : (...args: any[]) => any +>x : any +>y : any +>z : any +>g() : any +>g : (...args: any[]) => any +>z : any + === expressions.tsx === export {}; declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; @@ -736,3 +749,16 @@ f<() => T>; >f<() => T> : (...args: any[]) => any >f : (...args: any[]) => any +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z; +>probe : ({ [g<({ [x]: y }: T) => U>()]: z }: T) => any +>({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z : ({ [g<({ [x]: y }: T) => U>()]: z }: T) => any +>g<({ [x]: y }: T) => U>() : any +>g : (...args: any[]) => any +>x : any +>y : any +>z : any +>g() : any +>g : (...args: any[]) => any +>z : any + diff --git a/tsc/testdata/tests/cases/compiler/arrowFunctionSpeculationJSDoc.ts b/tsc/testdata/tests/cases/compiler/arrowFunctionSpeculationJSDoc.ts new file mode 100644 index 0000000000000..091191c01b890 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/arrowFunctionSpeculationJSDoc.ts @@ -0,0 +1,29 @@ +// @allowJs: true +// @checkJs: true +// @noImplicitAny: false +// @noEmit: true + +// @filename: types.d.ts +export interface Key {} + +// @filename: index.js +export {}; +const key = "k"; +const result = (a) => ({ + [String((b) => ({ + [String((c) => ({ [String(key)]: 0 }))]: 0 + }))]: 0, + /** @typedef {number} Local */ + typedef() {}, + /** @callback Callback */ + callback() {}, + /** @import {Key} from "./types" */ + imported() {} +}); + +/** @type {Local} */ +const local = 1; +/** @type {Callback} */ +const callback = () => {}; +/** @type {Key} */ +const imported = {}; diff --git a/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRecovery.ts b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRecovery.ts index 5fcf0e31b0d6f..2f38c3cbcbdad 100644 --- a/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRecovery.ts +++ b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRecovery.ts @@ -60,6 +60,9 @@ g<(T)>(); f<{ [(() => { type Bad = (T; return key; })()]: U }>(); g<(T)>(); +f<({ p = "\xZ" }: T) => U>(); +g<(T)>(); + // @filename: recovery.tsx export {}; declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; @@ -115,3 +118,6 @@ g<(T)>(); f<{ [(() => { type Bad = (T; return key; })()]: U }>(); g<(T)>(); + +f<({ p = "\xZ" }: T) => U>(); +g<(T)>(); diff --git a/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts index aa3eba1e76031..fe4e149065537 100644 --- a/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts +++ b/tsc/testdata/tests/cases/compiler/typeArgumentSpeculationRelationalExpression.ts @@ -62,6 +62,9 @@ f<() => T>`text`; f<() => T>`text${1}`; f<() => T>; +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z; + // @filename: expressions.tsx export {}; declare const a: any, b: any, c: any, d: any, e: any, B: any, options: any, x: any; @@ -119,3 +122,6 @@ f<{ /** @type {(T} @see x */ x: T }>(); f<() => T>`text`; f<() => T>`text${1}`; f<() => T>; + +// Arrow and type-argument probes must rebuild computed names and defaults. +const probe = ({ [g<({ [x]: y }: T) => U>()]: z = g() }: T) => z; From 1a577ed56743b74a8dee3836991fb12e92c20d7e Mon Sep 17 00:00:00 2001 From: magic-akari Date: Wed, 18 Nov 2026 01:21:08 +0800 Subject: [PATCH 4/4] Clarify parser speculation contracts Replace vague terminology and repeated implementation details with comments about parsing failures, placeholder nodes, and rollback guarantees. Rename the expression-cache marker to usedExpressionCache and explain why cache hits require rebuilding a complete AST after successful speculation. --- tsc/internal/parser/parser.go | 40 ++++++------------- tsc/internal/parser/speculative_expression.go | 22 ++++------ .../parser/type_argument_lookahead.go | 21 +++------- tsc/internal/parser/type_parser.go | 7 ++-- tsc/internal/parser/type_parser_test.go | 6 +-- tsc/internal/scanner/scanner.go | 4 +- 6 files changed, 33 insertions(+), 67 deletions(-) diff --git a/tsc/internal/parser/parser.go b/tsc/internal/parser/parser.go index 4cb1de9493b51..10c637b77b95e 100644 --- a/tsc/internal/parser/parser.go +++ b/tsc/internal/parser/parser.go @@ -63,14 +63,13 @@ const ( ) type Parser struct { - // Grammar policies stay immutable during a parse, including nested speculation. - recoveringTypes typeParser - speculativeTypes typeParser - // Prediction facts survive speculation; no AST handles are retained. + recoveringTypes typeParser + speculativeTypes typeParser typeArgumentClosures map[int]bool inExpressionProbe bool - // Opaque values taint the whole probe, including lookaheads that rewind. - hasOpaqueExpression bool + // Cache hits return placeholders, so a successful outer probe must be reparsed + // if it used the expression cache. + usedExpressionCache bool failedTypeArguments collections.Set[speculationKey] failedSpeculativeTypes collections.Set[speculationKey] probeExpressions map[probeExpressionKey]probeExpressionBoundary @@ -666,7 +665,7 @@ func (p *Parser) reparseTopLevelAwait(sourceFile *ast.SourceFile) *ast.Node { } } - // Keep diagnostics and pending declarations from the committed reparse. + // Rewinding must preserve diagnostics and declarations from this reparse. state.diagnosticsLen = len(p.diagnostics) state.jsdocDiagnosticsLen = len(p.jsdocDiagnostics) state.reparseList = p.reparseList @@ -2820,8 +2819,6 @@ func (p *typeParser) parseType() *ast.TypeNode { } } result := p.parseTypeWorker() - // Remember structural failure, including a nested failure. Diagnostics on a - // recognized type remain recoverable and do not reject the production. if speculative && result == nil { p.failedSpeculativeTypes.Add(key) } @@ -2845,8 +2842,7 @@ func (p *typeParser) parseTypeWorker() *ast.TypeNode { if extendsType == nil { return nil } - // `extends` determines the conditional-type production. Keep its - // branches when only a separator is missing. + // Missing '?' or ':' is recoverable within a conditional type. p.parseExpected(ast.KindQuestionToken) trueType := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, false, (*typeParser).parseType) if trueType == nil { @@ -2959,8 +2955,7 @@ func (p *typeParser) tryParseConstraintOfInferType() (*ast.Node, bool) { if p.parseOptional(ast.KindExtendsKeyword) { constraint := p.doInContext(ast.NodeFlagsDisallowConditionalTypesContext, true, (*typeParser).parseType) if constraint == nil { - // A failed constraint cannot become the same extends type of a conditional. - // Propagate failure instead of reparsing it at every enclosing infer type. + // A conditional type would require the same failed type after 'extends'. p.rewind(state) return nil, false } @@ -3805,7 +3800,6 @@ func (p *typeParser) parseTypeOrTypePredicate() *ast.TypeNode { } func (p *typeParser) parseTypeMemberSemicolon() bool { - // A comma or an explicit/implicit semicolon separates type members. if p.parseOptional(ast.KindCommaToken) { return true } @@ -4338,9 +4332,6 @@ func (p *Parser) skipParameterStart() bool { return true } if p.token == ast.KindOpenBracketToken || p.token == ast.KindOpenBraceToken { - // Binding lookahead requires the complete pattern to be diagnostic-free. - // Its AST is discarded, so computed names and defaults can reuse values - // recognized by earlier probes without repeating their recursive work. previousErrorCount := len(p.diagnostics) saveProbe := p.inExpressionProbe p.inExpressionProbe = true @@ -4830,7 +4821,7 @@ func (p *Parser) tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInA } state := p.mark() if !p.inExpressionProbe { - p.hasOpaqueExpression = false + p.usedExpressionCache = false } p.inExpressionProbe = true result := p.parsePossibleParenthesizedArrowFunctionExpression(allowReturnTypeInArrowFunction) @@ -4838,7 +4829,7 @@ func (p *Parser) tryParseParenthesizedArrowFunctionExpression(allowReturnTypeInA p.rewind(state) return nil } - if !state.inExpressionProbe && p.hasOpaqueExpression { + if !state.inExpressionProbe && p.usedExpressionCache { p.rewind(state) result = p.parseParenthesizedArrowFunctionExpression(false /*allowAmbiguity*/, allowReturnTypeInArrowFunction) if result == nil { @@ -5750,8 +5741,7 @@ func (p *Parser) parseLeftHandSideExpressionOrHigher() *ast.Expression { } // Now, we *may* be complete. However, we might have consumed the start of a // CallExpression or OptionalExpression. As such, we need to consume the rest - // of it here to be complete. Member suffixes share this entry so a failed - // type-argument interpretation is not retried by an initial member pass. + // of it here to be complete. return p.parseCallExpressionRest(pos, expression) } @@ -5816,7 +5806,7 @@ func (p *Parser) tryParseTypeArgumentsInExpression() *ast.NodeList { return nil } if !p.inExpressionProbe { - p.hasOpaqueExpression = false + p.usedExpressionCache = false } p.inExpressionProbe = true result := p.parseTypeArgumentsInExpressionWorker() @@ -5825,9 +5815,7 @@ func (p *Parser) tryParseTypeArgumentsInExpression() *ast.NodeList { p.failedTypeArguments.Add(key) return nil } - if !state.inExpressionProbe && p.hasOpaqueExpression { - // Recognition may use opaque values, but no such AST can escape. - // Rebuild the recognized candidate with the ordinary expression parser. + if !state.inExpressionProbe && p.usedExpressionCache { p.rewind(state) result = p.parseTypeArgumentsInExpressionWorker() if result == nil { @@ -5844,8 +5832,6 @@ func (p *Parser) parseTypeArgumentsInExpressionWorker() *ast.NodeList { if p.reScanLessThanToken() == ast.KindLessThanToken { p.nextToken() typeArguments := p.speculativeTypes.parseDelimitedList(PCTypeArguments, (*typeParser).parseType) - // Only a completed type production can establish the type argument interpretation. - // Diagnostics from a recoverable type do not make speculation fail. if typeArguments != nil && p.reScanGreaterThanToken() == ast.KindGreaterThanToken { p.nextToken() // We successfully parsed a type argument list. The next token determines whether we want to diff --git a/tsc/internal/parser/speculative_expression.go b/tsc/internal/parser/speculative_expression.go index 5cb4b74479408..f47cb539107ed 100644 --- a/tsc/internal/parser/speculative_expression.go +++ b/tsc/internal/parser/speculative_expression.go @@ -32,8 +32,6 @@ type probeExpressionKey struct { kind probeExpressionKind } -// Boundaries only describe diagnostic-free, disposable recognition passes. -// They retain no AST handles and never construct committed expressions. type probeExpressionBoundary struct { scannerState scanner.ScannerState loc core.TextRange @@ -46,7 +44,7 @@ func (p *Parser) speculationKey() speculationKey { lastDiagnosticPosition := -1 if len(p.diagnostics) != 0 { lastPosition := p.diagnostics[len(p.diagnostics)-1].Pos() - // Earlier diagnostics cannot be deduplicated with errors in this value. + // Earlier diagnostics cannot suppress errors within this expression. if lastPosition >= position { lastDiagnosticPosition = lastPosition } @@ -64,11 +62,9 @@ func (p *Parser) speculationKey() speculationKey { } } -// These entry points are used where the grammar needs a value and its end, -// rather than inspecting the value as an assignment target or binding cover. -// During a probe, callers must not inspect the returned expression's kind or -// children to choose a grammar production. A successful outer probe rebuilds -// any opaque values before committing its AST. +// parseValueExpression and parseComputedPropertyExpression may return a +// placeholder during speculation. Only its range and flags are meaningful; +// callers must not inspect its kind or children to choose a grammar production. func (p *Parser) parseValueExpression(allowReturnTypeInArrowFunction bool) *ast.Expression { if !p.inExpressionProbe || p.contextFlags&ast.NodeFlagsJSDoc != 0 { return p.parseAssignmentExpressionOrHigherWorker(allowReturnTypeInArrowFunction) @@ -92,15 +88,13 @@ func (p *Parser) parseComputedPropertyExpression() *ast.Expression { } func (p *Parser) parseProbeExpression(kind probeExpressionKind) *ast.Expression { - debug.Assert(p.inExpressionProbe && p.contextFlags&ast.NodeFlagsJSDoc == 0, "Expression boundaries are only reusable in disposable probes") + debug.Assert(p.inExpressionProbe && p.contextFlags&ast.NodeFlagsJSDoc == 0, "Expression caching requires speculation outside JSDoc") key := probeExpressionKey{speculationKey: p.speculationKey(), kind: kind} if boundary, known := p.probeExpressions[key]; known { p.scanner.RewindPosition(boundary.scannerState) p.token = p.scanner.Token() p.hasParseError = boundary.hasParseError - // A nested lookahead may rewind its AST after observing this value. - // Keep the taint until the enclosing speculative parse is discarded. - p.hasOpaqueExpression = true + p.usedExpressionCache = true result := p.factory.NewIdentifier("") result.Loc = boundary.loc result.Flags = boundary.flags @@ -117,8 +111,8 @@ func (p *Parser) parseProbeExpression(kind probeExpressionKind) *ast.Expression case probeAssignmentWithoutArrowReturn: result = p.parseAssignmentExpressionOrHigherWorker(false /*allowReturnTypeInArrowFunction*/) } - // A preceding operator can consume hasParseError after scanning the first - // token of this value. Its existing diagnostics still prevent boundary reuse. + // Existing lexical diagnostics forbid reuse even if a preceding operator + // has already cleared hasParseError. if result != nil && !state.hasParseError && key.lastDiagnosticPosition < 0 && len(p.diagnostics) == state.diagnosticsLen && len(p.jsDiagnostics) == state.jsDiagnosticsLen && len(p.jsdocDiagnostics) == state.jsdocDiagnosticsLen && len(p.reparseList) == len(state.reparseList) && diff --git a/tsc/internal/parser/type_argument_lookahead.go b/tsc/internal/parser/type_argument_lookahead.go index 6a6898dda81b8..5f12cf5087973 100644 --- a/tsc/internal/parser/type_argument_lookahead.go +++ b/tsc/internal/parser/type_argument_lookahead.go @@ -10,15 +10,10 @@ type typeArgumentDelimiter struct { angleStart int } -// typeArgumentsMayClose only rejects lists whose closing angle cannot belong -// to the opening token. Parentheses, brackets, and braces fence off inner -// angles, so a comparison inside a group cannot close an outer type list. -// All openings encountered by a scan share its closure facts; nested attempts -// do not repeatedly scan the same suffix. A lexical ambiguity leaves the -// decision to the type grammar, including its diagnostics and recovery. -// A negative proof uses only group fences, semicolons, and EOF in the normal -// lexical goal. Unknown lexical goals and mismatched groups are inconclusive; -// new lexical goals must also defer to grammar instead of rejecting a list. +// typeArgumentsMayClose returns false only when no '>' can close the current +// type argument list. A true result does not establish that the list is valid. +// Ambiguous tokenization must be left to the parser. Cached results remain +// valid after parser rewind. func (p *Parser) typeArgumentsMayClose() bool { start := p.scanner.TokenStart() if mayClose, known := p.typeArgumentClosures[start]; known { @@ -44,7 +39,6 @@ func (p *Parser) typeArgumentsMayClose() bool { } switch p.token { case ast.KindSlashToken, ast.KindSlashEqualsToken, ast.KindTemplateHead: - // Selecting the regular-expression/template lexical goal needs grammar. p.recordTypeArgumentClosures(angles, true) return true case ast.KindLessThanToken, ast.KindLessThanLessThanToken: @@ -52,7 +46,6 @@ func (p *Parser) typeArgumentsMayClose() bool { if p.token == ast.KindLessThanLessThanToken { angles = append(angles, p.scanner.TokenStart()+1) } - // Nested starts may require the JSX lexical goal. if p.languageVariant == core.LanguageVariantJSX && len(groups) != 0 { p.recordTypeArgumentClosures(angles, true) return true @@ -88,14 +81,12 @@ func (p *Parser) typeArgumentsMayClose() bool { return false } case ast.KindGreaterThanToken: - // Scan returns one '>' at a time; this lookahead never rescans it. + // Scan returns one '>' at a time. angleStart := 0 if len(groups) != 0 { angleStart = groups[len(groups)-1].angleStart } remaining := max(angleStart, len(angles)-1) - // Simple lists need no index allocation: the grammar consumes them - // immediately, and their lookahead contains no recursive work. if hasNestedSyntax { p.recordTypeArgumentClosures(angles[remaining:], true) } @@ -115,7 +106,7 @@ func (p *Parser) recordTypeArgumentClosures(angles []int, mayClose bool) { p.typeArgumentClosures = make(map[int]bool) } for _, position := range angles { - // A proof of non-closure takes precedence over an inconclusive scan. + // An inconclusive result must not overwrite a known failure to close. if previous, known := p.typeArgumentClosures[position]; !known || previous { p.typeArgumentClosures[position] = mayClose } diff --git a/tsc/internal/parser/type_parser.go b/tsc/internal/parser/type_parser.go index d062f65509c0c..b21d8154de322 100644 --- a/tsc/internal/parser/type_parser.go +++ b/tsc/internal/parser/type_parser.go @@ -2,10 +2,9 @@ package parser import "github.com/microsoft/TypeScript/tsc/internal/ast" -// typeParser is an immutable grammar context shared by type productions without changing -// the recovering parser used by nested expressions or JSDoc. A speculative type -// production returns nil when its structure cannot be established. Diagnostics -// on a recognized type, such as an invalid literal, do not imply failure. +// typeParser returns nil for structurally incomplete types when allowAmbiguity +// is false. Recoverable diagnostics do not imply failure. Nested expressions +// and JSDoc retain their usual error recovery. // Optional productions return (nil, true) when absent and (nil, false) on failure. type typeParser struct { *Parser diff --git a/tsc/internal/parser/type_parser_test.go b/tsc/internal/parser/type_parser_test.go index bb877696c79be..28c5a2fbaefd7 100644 --- a/tsc/internal/parser/type_parser_test.go +++ b/tsc/internal/parser/type_parser_test.go @@ -57,7 +57,6 @@ func TestTypeArgumentClosureLookaheadRollback(t *testing.T) { state := p.mark() assert.Assert(t, p.typeArgumentsMayClose()) assert.Assert(t, reflect.DeepEqual(p.mark(), state)) - // The real scan must still observe the directive and its lexical diagnostic. p.nextToken() assert.Equal(t, len(p.scanner.CommentDirectives()), 1) assert.Equal(t, len(p.diagnostics), 1) @@ -76,11 +75,10 @@ func TestProbeExpressionBoundaryRollback(t *testing.T) { assert.Equal(t, len(p.probeExpressions), 1) p.rewind(state) assert.Assert(t, p.lookAhead(func(p *Parser) bool { - // A cache hit is opaque and belongs only to this disposable lookahead. return p.parseValueExpression(true).Kind == ast.KindIdentifier })) assert.Assert(t, reflect.DeepEqual(p.mark(), state)) - assert.Assert(t, p.hasOpaqueExpression) + assert.Assert(t, p.usedExpressionCache) assert.Equal(t, len(p.scanner.CommentDirectives()), 0) p.inExpressionProbe = false committed := p.parseValueExpression(true) @@ -133,7 +131,7 @@ func TestProbeExpressionBoundaryWithScanError(t *testing.T) { assert.Equal(t, p.parseValueExpression(true).Kind, ast.KindStringLiteral) p.rewind(state) assert.Equal(t, p.parseValueExpression(true).Kind, ast.KindStringLiteral) - assert.Assert(t, !p.hasOpaqueExpression) + assert.Assert(t, !p.usedExpressionCache) assert.Equal(t, len(p.diagnostics), 1) assert.Equal(t, p.diagnostics[0].Code(), diagnostics.Hexadecimal_digit_expected.Code()) }) diff --git a/tsc/internal/scanner/scanner.go b/tsc/internal/scanner/scanner.go index 64034767f5c07..b7830a3876005 100644 --- a/tsc/internal/scanner/scanner.go +++ b/tsc/internal/scanner/scanner.go @@ -343,9 +343,7 @@ func (s *Scanner) Rewind(state ScannerState) { s.ScannerState = state } -// RewindPosition restores lexical state without replacing the caller's -// collected directives. Disposable grammar probes do not replay collection -// effects when they reuse an expression boundary. +// RewindPosition restores lexical state while preserving collected comment directives. func (s *Scanner) RewindPosition(state ScannerState) { directives := s.commentDirectives s.ScannerState = state