title: How to parse JavaScript function expression calls with ANTLR?
body: <p>I am building a JavaScript instrumentor with ANTLR, using the <a href="http://research.xebic.com/es3/" rel="nofollow">Patrick Hulsmeijer EcmaScript 3 grammar</a>. </p>
  
  <p>I'm having a problem parsing this line of code: </p>
  
  <pre><code>function(){}();
  </code></pre>
  
  <p>that is a direct call of a function expression. 
  The parser recognizes the statement as a function declaration and then fails when it finds the parentheses after the function body. The reason is that function declarations are recognized with most precedence to avoid the ambiguity with function expressions.</p>
  
  <p>This is how the grammar recognizes function declarations: </p>
  
  <pre><code>sourceElement
  options
  {
      k = 1 ;
  }
      : { input.LA(1) == FUNCTION }? functionDeclaration
      | statement
      ;
  </code></pre>
  
  <p><em>I am not even sure that it is a valid EcmaScript statement. Is it?</em><br>
  I think it should be more correct to write: </p>
  
  <pre><code>(function(){})();
  </code></pre>
  
  <p>which is actually well handled by the parser.<br>
  By the way this is not the core of the question, because I have no control over the code to instrument. </p>
  
  <p>I tried to eliminate <code>functionDeclaration</code> from the <code>sourceElement</code> production and to put it in the <strike><code>statement</code></strike><code>statementTail</code> production: </p>
  
  <pre><code>statementTail
      : variableStatement
      | emptyStatement
      | expressionStatement
      | functionDeclaration
      | ifStatement
      | ...
      ;
  </code></pre>
  
  <p>But a build error arises: </p>
  
  <blockquote>
    <p>[fatal] rule <code>statementTail</code> has
    non-LL(*) decision due to recursive
    rule invocations reachable from alts
    3,4.  Resolve by left-factoring or
    using syntactic predicates or using
    <code>backtrack=true</code> option.<br>
    |---> : variableStatement</p>
  </blockquote>
  
  <p>because the <code>variableStatement</code> production contains <code>functionExpression</code> as a descendant, which leads to an ambiguity. The parser cannot choose among <code>functionDeclaration</code> and <code>functionExpression</code> because they are almost equal:</p>
  
  <pre><code>functionDeclaration
      : FUNCTION name=Identifier formalParameterList functionBody
      -&gt; ^( FUNCTIONDECL $name formalParameterList functionBody )
      ;
  
  functionExpression
      : FUNCTION name=Identifier? formalParameterList functionBody
      -&gt; ^( FUNCTIONEXPR $name? formalParameterList functionBody )
      ;
  </code></pre>
  
  <p>Note: I modified the original rewrite rules using different tree nodes (FUNCTIONDECL and FUNCTIONEXPR) because I need it while walking the AST. </p>
  
  <p><strong>How can I solve this ambiguity?</strong></p>