简体   繁体   中英

Parser combinators and left-recursion

So it is well known that the top-down parsing paradigm can not deal with left-recursion. The grammar must either be refactored to get rid of left-recursion or some other paradigm must be used. I've been working on a parser combinator library and since I'm doing this in a language that allows for global side-effects it struck me that I can use some global store for tracking which rules have fired and which ones have not. This scheme of guarding on certain conditions lets me deal with very simple cases of left-recursion at the cost of some extra annotation on the combinators. Here's an example grammar in TypeScript

var expression = Parser.delay(_ => TestGrammar.expression);
var in_plus = false;

class TestGrammar {

  static terminal = Parser.m(x => 'a' === x);

  static op = Parser.m(x => '+' === x);

  static plus = expression.on_success(_ => {
    in_plus = false; 
  }).then(TestGrammar.op).then(expression).on_enter(_ => {
    in_plus = true; 
  }).guard(_ => !in_plus);

  static expression = TestGrammar.plus.or(TestGrammar.terminal);

}

console.log(TestGrammar.expression.parse_input('a+a+a+a'));

The idea is pretty simple. In cases where we might get stuck in a loop the rules are amended with guards like in the case of plus in the above example. The rule fails if we hit a looping condition and the guard is lifted as soon as we make progress.

What I'd like to know is if this idea has been explored and analysed. I'd rather not go down this rabbit hole and try to figure stuff out if this is a dead end.

Have a look at GLL algorithms (eg https://github.com/djspiewak/gll-combinators ). They can handle ambiguous and left-recursive grammars efficiently.

They do not directly call the parser function of the sub-parser, but keep a 'todo'-list of (Parser,Position) tupels (called the Trampoline). This way the endless loop (recursing into self) is avoided (no tupel is added twice).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM