Skip to content

Parser State

mattbierner edited this page Dec 9, 2014 · 4 revisions

The parser state is an immutable object that tracks the state of a parser while it is executing. The default Bennu parser state, parse.ParserState, keeps track of position, input, and userState.

Interface

At a minimum, any parser state must implement the following interface.

state.input

Returns the remaining input to be parsed as a Nu stream.

state.position

Returns a position object for the current position in the input stream.

state.userState

Returns the user data object for the state.

state.setInput(newInput)

Returns a new parser state with input 'newInput'.

state.setPosition(newPosition)

Returns a new parser state its position set as newPosition

state.setUserState(newUserState)

Returns a new parser state its userState set as newUserState.

state.next(tok)

Called when tok has just been consumed. Returns a new parser the continues with the new state. If you object implements the rest of these interfaces, just inherit from parse.ParserState to get this functionality.

state.eq(other)

Is this state equal to another state? Used for memoization.

Custom Parser States

You probably don't need this. The default parser state supports custom position types and a custom user state object which allows you to attach arbitrary data to parser states.

However, if you for some reason feel that you need a custom parser state, there is nothing stopping you from creating one.

Simply implement the above interface and pass it to the parser. All parser state functions must be side effect free and referentially transparent. State objects must be immutable.