How to transform a simple grammar into something which works in PEG.js (expected "a" but "a" found)
Asked Answered
H

2

1

I've just started playing with PEG.js and have a problem with a grammar (vastly simplified for debugging):

start
  = presingle single
  / preplural plural

presingle
  = "a"
  / "b"

preplural
  = "b"
  / "c"

single
  = "d"
  / "e"

plural
  = "dd"
  / "ee"

I'm using https://pegjs.org/online

This grammar fails to parse bdd.

Line 1, column 3: Expected "a" but "d" found.

Is this something which PEGs cannot do, or can I transform my grammar into something which will parse this?

P.S. If I try to parse the (erroneously advised?) bda I get the nonsensical error:

Line 1, column 3: Expected "a" but "a" found.
Hydrazine answered 31/10, 2012 at 14:32 Comment(0)
J
1

This grammar changes only the order of the clauses in start and works for bdd

start = 
   preplural plural /
    presingle single

presingle
  = "a"
  / "b"

preplural
  = "b"
  / "c"

single
  = "d"
  / "e"

plural
  = "dd"
  / "ee"

and for bda shows error Line 1, column 3: Expected "dd" or "ee" but "a" found.

Jussive answered 31/10, 2012 at 15:10 Comment(3)
hi i have a similar problem, and i don't get why this solution works i thought that ' / ' was the OR operator meaning that one of them should work regardless of the order am i missing something ?Greenlee
I do not recall my thinking at the time. I suspect I tried the inversion and found it to work. From the next answer it would seem that this was a bug which has since been fixed.Jussive
PEG's ' / ' not the same as BNF/EBNF/ABNF's option/or '|', but first match.Incantatory
T
1

The good news is that modern versions of pegjs give the error message: “Line 1, column 3: Expected end of input but "d" found.” when given the input bdd.

This is what you would expect, since it matches the single match first, and since the "b" and the "d" match, it assumes that it is good to go. Inverting the order, as suggested by @HBP forces it to match the plurals first, and only if they don't exist, does it try the single, which gives the result that you expect.

Truncation answered 18/9, 2015 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.