Parsing nested `if/else' statements

248 views Asked by At

I am working on a JavaScript implementation of the OpenSCAD language, which -- for this purpose -- is a C-type language.

I've been able to successfully parse all sorts of if and if/else statements:

if(true) t1=200;t2=500;
if(true) t1=200;
if(true)t1=200;
if(true){t1=200;}
if(true) if(false) {t1=200;}
if(true){t1=200;} else {t2=500;}

However, I have come across a particular combo that is leaving me with 'ambiguous grammar' -- Nearley.js's way of saying the parsing may happen in multiple ways:

if(true) if(false) {t1=200;} else {echo("hi");}

Attempted solution 1: Crafted from a handful of different sources

selection_statement
    -> elseIfStatement {% id %}


bareifStatement
    -> "if" _ "(" _ expression _ ")" _ statement  {% d => d %}

elseIfStatement
    -> bareifStatement _ "else" _ statement {% ifstatement %}
    | bareifStatement _ elseIfStatement {% id %}
    | bareifStatement

Attempted Solution #2 Culled from https://github.com/vsl-lang/VSL/blob/develop/src/vsl/parser/parser.ne

IfStatement
   -> "if" _ "(" _ expression _ ")" _ statement (
        _ "else" _ (
            statement {% id %}
        ) {% debug %}
    ):? {% debug %}

Attempted Solution 3: Still can parse two ways

selection_statement
    -> elseIfStatement {% id %}

elseIfStatement
    -> "if" _ "(" _ expression _ ")" _ statement  (_ "else" _ statement):? {% ifstatement %}

Has anyone successfully parsed this kind of grammar in an Earley syntax?

Hints? Suggestions? Heck, I'll even take a solution!

(The entire package is available on github, but it will require a few tweaks before it can run on other machines.) https://github.com/JeremyJStarcher/openscadtojs

0

There are 0 answers