How to parse JavaScript function expression calls using ANTLR?

I am creating a JavaScript tool with ANTLR using Patrick Halsmeier's EcmaScript 3 grammar .

I had a problem parsing this line of code:

function(){}();

which is a direct call to a function expression. The parser recognizes the instruction as a function declaration and then fails when it finds the brackets after the function body. The reason is that function declarations are recognized with the highest priority in order to avoid ambiguity with the expression of functions.

Here's how grammar recognizes function declarations:

sourceElement
options
{
    k = 1 ;
}
    : { input.LA(1) == FUNCTION }? functionDeclaration
    | statement
    ;

I'm not even sure if this is a valid EcmaScript statement. It? I think it would be more correct to write:

(function(){})();

.
, ​​, .

functionDeclaration sourceElement statement statementTail production:

statementTail
    : variableStatement
    | emptyStatement
    | expressionStatement
    | functionDeclaration
    | ifStatement
    | ...
    ;

:

[] statementTail -LL (*) - 3,4. backtrack=true.
| --- > : variableStatement

variableStatement functionExpression , . functionDeclaration functionExpression, :

functionDeclaration
    : FUNCTION name=Identifier formalParameterList functionBody
    -> ^( FUNCTIONDECL $name formalParameterList functionBody )
    ;

functionExpression
    : FUNCTION name=Identifier? formalParameterList functionBody
    -> ^( FUNCTIONEXPR $name? formalParameterList functionBody )
    ;

. , (FUNCTIONDECL FUNCTIONEXPR), , AST.

?

+1
1

Declaration, sourceElement 'function'. ECMAScript Language Specification:

ExpressionStatement , FunctionDeclaration.

, , , : , .

function f(){}(42)

ECMAScript Declaration, Statement.

. , , ANTLR-backtracking. , Declaration, functionDeclaration . , , ,

function f(){}()

Declaration , .

+2

All Articles