Skip to content
Simon Krajewski edited this page Mar 8, 2014 · 5 revisions

Writing a Parser

Basic steps

  1. Create a Parser class, extending hxparse.Parser.
  2. Add a constructor which calls super(stream), where stream is an object (typically derived from Lexer) compatible with the TokenSource structure.
  3. Define a set of parsing functions.

Parsing functions

Anywhere within a parser, the expression switch stream is recognized as a stream matching. Its cases accept two kinds of expressions:

  1. Match a list of lexer tokens: case [Token1, Token2]:
  2. Match anything: case _:

Within the lexer token list, calls to other parsing functions can be made: case [e = parseExpr(), i = parseIdent()]:. The variables e and i are then available in the case body.

Parsing rules

Upon a switch stream expression, the current token is obtained by calling this.peek(0) and matched against the case list. If no match can be made, a non-critical hxparse.NoMatch exception is thrown: Because no token has been consumed, the stream is still intact matching can continue elsewhere.

As soon as a match can be made, the current token is consumed by calling this.junk(). If matching fails after this point, the stream is in an irrecoverable state and an hxparse.Unexpected exception is thrown.

Examples

Clone this wiki locally