-
Notifications
You must be signed in to change notification settings - Fork 30
Writing a Parser
- Create a Parser class, extending
hxparse.Parser
. - Add a constructor which calls
super(stream)
, wherestream
is an object (typically derived fromLexer
) compatible with theTokenSource
structure. - Define a set of parsing functions.
Anywhere within a parser, the expression switch stream
is recognized as a stream matching. Its cases accept two kinds of expressions:
- Match a list of lexer tokens:
case [Token1, Token2]:
- 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.
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.
- A small parser for printf placeholders: https://github.com/Simn/hxparse/blob/master/test/PrintfParser.hx
- A small JSON parser: https://github.com/Simn/hxparse/blob/master/test/JSONParser.hx
- A parser for the haxe language: https://github.com/Simn/haxeparser/blob/master/src/haxeparser/HaxeParser.hx