What is a Parser?
AParser<T> is the fundamental building block of Parserator. It represents a function that:
- Takes an input string and a parser state
- Either succeeds with a value of type
T, or - Fails with detailed error information
The Parser Type
T represents the type of value this parser produces when successful.
Core Types
ParserState
Represents the current parsing position and context:ParserOutput
Contains both the updated state and the parsing result:result field uses an Either type:
Either.right(value)for successEither.left(errorBundle)for failure
Running Parsers
parse()
Runs the parser and returns the fullParserOutput:
parseOrError()
Returns either the parsed value or aParseErrorBundle:
parseOrThrow()
Returns the parsed value or throws aParseErrorBundle:
Transforming Parsers
map()
Transforms the parsed value using a function:flatMap()
Chains parsers where the next parser depends on the previous result:Sequencing Parsers
zip()
Combines two parsers and returns both results as a tuple:then()
Runs two parsers in sequence, keeping only the second result:zipRight()
thenDiscard()
Runs two parsers in sequence, keeping only the first result:zipLeft()
Trimming Whitespace
Parsers have built-in methods for handling surrounding content:Creating Parsers
Parser.lift()
Creates a parser that always succeeds with the given value:Parser.pure()
Parser.lazy()
Creates a parser that is evaluated lazily, useful for recursive parsers:Parser.fatal()
Creates a parser that always fails with a fatal error:Position Tracking
Parsers automatically track position information for error reporting. Thespanned() method captures both the value and its span:
Debugging
Thetap() method allows you to observe parsing without affecting the result: