foo123 / editor-grammar

invariant codebase of editor-grammar (codemirror-grammar, ace-grammar,prism-grammar,syntaxhighlighter-grammar, highlightjs-grammar,..)
https://foo123.github.io/
19 stars 7 forks source link

syntax rule not working #5

Closed totalamd closed 6 years ago

totalamd commented 6 years ago

I wanna change syntax rule to allow trailing comma in JSON arrays, so I change "literal_array" : "'[' (literal_value (',' literal_value)*)? ']'" to "literal_array" : "'[' (literal_value (',' literal_value)* (',')? )? ']'" But seems it not works. What I do wrong? Error:

error: Token "atom": true|false|null Expected | Token "string" Expected | Token "number" Expected | Token "[" Expected | Token "{" Expected

foo123 commented 6 years ago

What you 've done is not going to work as you think since the (',' literal_value)* rule part is first and tries to match a comma (even a trailing comma) but then tries to match a literal_value. You can make the literal_value optional like this:

"literal_array" : "'[' (literal_value (',' literal_value?)*)? ']'"

But this will allow many trailing commas. Else you can take a try using lookahead tokens and refine the rule to match only a single trailing comma, assuming no literal_value is matched.

The issue here is that like PEGs * quantifier is greedy, It will try to match as much as it can. Thus the last comma in your rule is never reached.