From b66617a071fb7b55a8d12f6efc0307b632074a18 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Tue, 17 Jan 2023 23:59:49 +0800 Subject: [PATCH] fix: analysis `ParenthesizedExpression` or `FunctionExpression` more correctly in parser (#2605) --- src/parser.ts | 50 ++++++++++++++-------- tests/parser/arrow-functions.ts | 2 + tests/parser/arrow-functions.ts.fixture.ts | 2 + 3 files changed, 35 insertions(+), 19 deletions(-) diff --git a/src/parser.ts b/src/parser.ts index 976307a49d..f9d637f7f4 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -514,19 +514,23 @@ export class Parser extends DiagnosticEmitter { if (signature) { if (isInnerParenthesized) { if (!tn.skip(Token.CloseParen)) { - this.error( - DiagnosticCode._0_expected, - tn.range(), ")" - ); + if (!suppressErrors) { + this.error( + DiagnosticCode._0_expected, + tn.range(), ")" + ); + } return null; } } type = signature; } else if (isInnerParenthesized || this.tryParseSignatureIsSignature) { - this.error( - DiagnosticCode.Unexpected_token, - tn.range() - ); + if (!suppressErrors) { + this.error( + DiagnosticCode.Unexpected_token, + tn.range() + ); + } return null; // Type (',' Type)* ')' } else if (acceptParenthesized) { @@ -545,10 +549,12 @@ export class Parser extends DiagnosticEmitter { type.range.start = startPos; type.range.end = tn.pos; } else { - this.error( - DiagnosticCode.Unexpected_token, - tn.range() - ); + if (!suppressErrors) { + this.error( + DiagnosticCode.Unexpected_token, + tn.range() + ); + } return null; } @@ -3780,14 +3786,20 @@ export class Parser extends DiagnosticEmitter { // if we got here, check for arrow case Token.CloseParen: { - if ( - !tn.skip(Token.Colon) && - !tn.skip(Token.Equals_GreaterThan) - ) { - again = false; - break; + // `Identifier):Type =>` is function expression + if (tn.skip(Token.Colon)) { + let type = this.parseType(tn, true, true); + if (type == null) { + again = false; + break; + } } - // fall-through + if (tn.skip(Token.Equals_GreaterThan)) { + tn.reset(state); + return this.parseFunctionExpression(tn); + } + again = false; + break; } // function expression case Token.Colon: { // type annotation diff --git a/tests/parser/arrow-functions.ts b/tests/parser/arrow-functions.ts index d1ae00bdb5..f6d0b4b98b 100644 --- a/tests/parser/arrow-functions.ts +++ b/tests/parser/arrow-functions.ts @@ -9,4 +9,6 @@ x => x; // not an array function (b ? x : y); +b ? (x) : y; +b ? (x):i32=>1 : y; (b ? f : g)(); diff --git a/tests/parser/arrow-functions.ts.fixture.ts b/tests/parser/arrow-functions.ts.fixture.ts index aae3fe4715..2a74453d9c 100644 --- a/tests/parser/arrow-functions.ts.fixture.ts +++ b/tests/parser/arrow-functions.ts.fixture.ts @@ -6,4 +6,6 @@ x => x; () => {}; (b ? x : y); +b ? (x) : y; +b ? (x): i32 => 1 : y; (b ? f : g)();