tillda
tillda

Reputation: 18690

How to write an *interruptible* recursive(?) descent parser

I have a pretty standard recursive descent parser. The algorithm is straightforward: each function reads characters from a stream and either returns FAIL or calls subsequent parse functions (specified by a corresponding grammar rule):

function parseFoo() {
  var ret = parseBar(stream);
  if (ret == FAIL) {
    ret = parseQuax(stream);
    ...
  }
  ...
  return ret;
}

I would like to solve a situation where I don't have the full stream at once - I get its pieces asynchronously. Therefore what I need is a feature of "interruptability" - I must be able to save a state of the parser and later continue from that point on.

Sadly, this is one thing that is impossible to do with nested function calls, because all the state of a parser is "stored" on the call stack (in the order of functions and in their local variables).

So I have to construct the parse* functions differently.

The language I use is JavaScript.

Can someone point me o any ideas how to proceed?

EDITs:

Upvotes: 1

Views: 636

Answers (1)

It depends upon the programming language used.

You basically need some support of continuations (which you could understand as the abstraction of the call stack). In other words, you may want to code in continuation passing style (CPS).

If coding in C, you might be interested by CPC.

If coding in Javascript, you'll probably need to hand-code in CPS. See also this, this, this question, this pages etc....

Upvotes: 1

Related Questions