Tail recursive parser explained

In computer science, tail recursive parsers are a derivation from the more common recursive descent parsers. Tail recursive parsers are commonly used to parse left recursive grammars. They use a smaller amount of stack space than regular recursive descent parsers. They are also easy to write. Typical recursive descent parsers make parsing left recursive grammars impossible (because of an infinite loop problem). Tail recursive parsers use a node reparenting technique that makes this allowable.

Example

Given an EBNF Grammar such as the following: E: T T: T | F F: F | I I: A simple tail recursive parser can be written much like a recursive descent parser. The typical algorithm for parsing a grammar like this using an abstract syntax tree is:

  1. Parse the next level of the grammar and get its output tree, designate it the first tree,
  2. While there is terminating token,, that can be put as the parent of this node:
    1. Allocate a new node,
    2. Set 's current operator as the current input token
    3. Advance the input one token
    4. Set 's left subtree as
    5. Parse another level down again and store this as the next tree,
    6. Set 's right subtree as
    7. Set to
  3. Return

A basic example of this kind of parser in C is shown here. Implementation details have been omitted for simplicity.typedef struct _exptree exptree;struct _exptree ;

exptree *parse_e(void)

exptree *parse_t(void)

exptree *parse_f(void)

exptree *parse_i(void)

See also

Further reading