0

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

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
  • Maybe this one helps: https://stackoverflow.com/questions/41088400/bison-loop-for-conflict If not, there are dozens of other ones. Search for "dangling else". (I don't know where you got solution 1 from, but it is certainly not correct.) – rici Dec 06 '17 at 01:18
  • "dangling else" -- Hmmm.. that's a term I've not heard. Thank you. – Jeremy J Starcher Dec 06 '17 at 01:27
  • 1
    Thank you for the magic phrase I needed. Several hours of research later took me to this page, which laid out the pieces in the order I need. https://cs.nyu.edu/courses/fall10/G22.2130-001/grammar.html – Jeremy J Starcher Dec 06 '17 at 07:17
  • cool. That's the solution in the SO question/answer I linked; was it not obvious enough in that answer? – rici Dec 06 '17 at 07:30
  • @rici Yes, the same solution but -- I'm still learning how to write grammar. The answer I linked to provided a little bit more context on where to put the pieces. – Jeremy J Starcher Dec 06 '17 at 07:45
  • @jeremt: ok, i'll work on it tomorrow. – rici Dec 06 '17 at 08:02

0 Answers0