ohmjs / ohm

A library and language for building parsers, interpreters, compilers, etc.
MIT License
5.01k stars 217 forks source link

export grammar as module string #300

Closed aleclofabbro closed 3 years ago

aleclofabbro commented 3 years ago

when defining grammar that uses escaped characters as a js string e.g.:

const grString = `
Grammar {
// ...more grammar here

lineTerminator = "\n" | "\r" | "\u2028" | "\u2029"

// ...more grammar here
}
`

ohm.grammar(grString)

with

/node_modules/ohm-js/src/main.js:283
    throw errors.grammarSyntaxError(m);
    ^

Error: Line 68, col 20:
> 68 |  lineTerminator = "
                          ^
" | "
" | "
"
Expected "\"", not "\n", or an escape sequence

Although it works as expected when :

note that lineTerminator is taken from ohm's javascript grammar example

pdubroy commented 3 years ago

You have to be careful when writing Ohm grammars inside of a JavaScript string literal. The \n here is an escape sequence that is replaced with a literal newline character before Ohm sees the string.

It's especially since Ohm supports many of the same escape sequences as JavaScript, so you have to be mindful of which level is interpreting your escape!

There are two solutions: