language-javascript icon indicating copy to clipboard operation
language-javascript copied to clipboard

Exception when parsing object literals containing arrow functions

Open gabejohnson opened this issue 5 years ago • 2 comments

I noticed a parse error when parsing an object literal containing an arrow function if any properties are defined after the arrow function.

({ f: x => x }) // no error

({ x: null, f: x => x }) // no error

({ f: (x => x), x: null }) // no error

({ x: true ? 1 : 0, y: null }) // no error

({ f: x => x, x: null }) // ColonToken {tokenSpan = TokenPn 163 9 16, tokenComment = []}

Since the third example parses without error, my suspicion is that the, in the failing example is being parsed as a comma operator and thus the colon after x is unexpected.

The behavior also appears to be restricted to arrow functions as the fourth example contains an expression which doesn't cause a failure.

gabejohnson avatar Jun 19 '20 14:06 gabejohnson

I've also found a strange interplay between arrow functions and template literals:

0;``
// JSAstModule [JSModuleStatementListItem (JSDecimal '0',JSSemicolon),JSModuleStatementListItem (JSTemplateLiteral ((),'``',[]))]

()=>{};''
// JSAstModule [JSModuleStatementListItem (JSArrowExpression (()) => JSStatementBlock []),JSModuleStatementListItem (JSStringLiteral '')]

()=>{}``
// JSAstModule [JSModuleStatementListItem (JSTemplateLiteral ((JSArrowExpression (()) => JSStatementBlock []),'``',[]))]

()=>{};``
// JSAstModule [JSModuleStatementListItem (JSTemplateLiteral ((JSArrowExpression (()) => JSStatementBlock []),'``',[]))]

()=>{}
``
// JSAstModule [JSModuleStatementListItem (JSTemplateLiteral ((JSArrowExpression (()) => JSStatementBlock []),'``',[]))]

Example 1 (no arrow function with a template literal) parses as expected. So does example 2 (arrow function with no template literal).

Example 3 shouldn't parse, but does. The template literal should cause a syntax error.

Example 4 should parse but not as a labeled template literal. The semicolon appears to be ignored.

Example 5 should parse but not in the same way as 3 and 4. ASI doesn't appear to be respected in this case.

gabejohnson avatar Jun 27 '20 20:06 gabejohnson

I have a branch which fixes all of these cases. @erikd would you accept a PR?

gabejohnson avatar Jul 01 '20 16:07 gabejohnson