Search code examples
rascal

How to solve ambiguity in an expression like new Date().getTime()?


We are working on a new version of a JavaScript grammar using Rascal. Based on the language specification (version 6) and existing JavaScript grammars, the following are valid productions for expressions:

syntax Expression = ... 
                  | new: "new" Expression
                  | call: Expression Args

syntax Args = ... 

However, when we try to parse an expression like "new Date().getTime()" we get an Ambiguity error. We tried to fix it using a combination of the "left" and ">" operators, something like

| left "new" Expression
> Expression Args

but we were not able to fix the problem. I believe that this might be simple to solve, but after spending a couple of hours, we could not figure out a solution.


Solution

  • I've tried to complete your example here, and this works without throwing an Ambiguity() exception.

    module Test
    
    import IO;
    import ParseTree;
    
    lexical Ident = [A-Za-z]+ !>> [a-zA-Z];
    layout Whitespace = [\t\n\r\ ]*;
    
    syntax Expression 
      = Ident
      | "new" Expression
      > Expression "(" {Expression ","}* ")"
      > right Expression "." Expression
      ;
    
    void main() {
      Expression ex = parse(#Expression, "a().b()");
      println(ex);
    
      Expression ex2 = parse(#Expression, "new a().b()");
      println(ex2);
    }