decoder : DecoderProps(state, item, problem) -> Decoder(state, item, problem)
Configure a custom incremental reader using named state, step and recovery props.
Parser(input, a, p) :: # (opaque)
Generic parser combinators for transforming input into structured values.
A Parser(input, a, p) is a value that describes how to read an a from the
front of an input. Combine small parsers with keep, skip, map,
one_of, many and sep_by to build larger ones, then run the result with
parser.parse_str(source) for text or parser.parse(input) for generic input.
This parser turns "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green"
into { id: 1, requirements: [[Blue(3), Red(4)], [Red(1), Green(2), Blue(6)], [Green(2)]] }
using the shared UTF-8 primitives:
Requirement : [Green(U64), Red(U64), Blue(U64)]
RequirementSet : List(Requirement)
Game : { id : U64, requirements : List(RequirementSet) }
parse_game : Str -> Try(Game, [ParsingError])
parse_game = |s| {
green = Parser.const(|x| Green(x)).keep(Parser.Utf8.digits({})).skip(Parser.Utf8.string(" green"))
red = Parser.const(|x| Red(x)).keep(Parser.Utf8.digits({})).skip(Parser.Utf8.string(" red"))
blue = Parser.const(|x| Blue(x)).keep(Parser.Utf8.digits({})).skip(Parser.Utf8.string(" blue"))
requirement_set : Parser(_, RequirementSet, _)
requirement_set = Parser.one_of([green, red, blue]).sep_by(Parser.Utf8.string(", "))
requirements : Parser(_, List(RequirementSet), _)
requirements = requirement_set.sep_by(Parser.Utf8.string("; "))
game : Parser(_, Game, _)
game =
Parser.const(|id| |r| { id, requirements: r })
.skip(Parser.Utf8.string("Game "))
.keep(Parser.Utf8.digits({}))
.skip(Parser.Utf8.string(": "))
.keep(requirements)
match game.parse_str(s) {
Ok(g) => Ok(g)
Err(ParseError(_)) => Err(ParsingError)
}
}
Alternatives backtrack: when one alternative of alt or one_of fails, the
next one is tried on the original input, however much the failed one read.
Failures report the furthest position any parser reached. When a
repetition such as many stops at a bad element, or an alternative fails
after reading further than the one that succeeded, that failure is kept
and reported if the whole parse later fails at or before it.
The representation is internal and may change to improve efficiency or error problems.
decoder : DecoderProps(state, item, problem) -> Decoder(state, item, problem)
Configure a custom incremental reader using named state, step and recovery props.
encoder : EncoderProps(state, item, problem) -> Encoder(state, item, problem)
Configure a custom incremental writer using named state and callbacks.
Parse an entire UTF-8 source, keeping original text coordinates on failure.
run_str : Parser(List(U8), a, p), Str -> Try({ value : a, rest : Str }, [ParseError(Diagnostic(Problem(p)))])
Parse a UTF-8 prefix. A split scalar is a typed boundary failure.
custom : (input -> Try({ value : a, rest : input }, [ParseError(Diagnostic([..p]))])) -> Parser(input, a, p) where [input.len : input -> U64]
Write a custom parser without using the provided combinators.
The function receives the remaining input and returns either the parsed
value with the rest it did not consume, or
Err(ParseError({ problem, location, path })). Use InputOffset(offset)
for positions relative to this input, or preserve a native location and path.
Run a parser on the start of an input, returning the parsed value and the input it did not consume.
Most parsers consume part of input when they succeed. This allows you to string parsers
together that run one after the other. The part of the input that the first
parser did not consume, is used by the next parser.
On failure, the error is the furthest failure seen, with its offset
counted from the start of input. This is mostly useful when creating
your own parsing building blocks.
parse : Parser(input, a, p), input -> Try(a, [ParseError(Diagnostic(Problem(p)))]) where [input.len : input -> U64]
Run a parser on the given input, expecting it to consume all of it.
The input type only needs a len method, which is used both to detect
leftover input and to locate generic failures with InputOffset counted
from the start of input. Leftover input is a failure too: if some
parser failed at or beyond the leftover, its problem is reported;
otherwise the problem is UnexpectedInput. For text use
parser.parse_str(source); byte lists use parser.parse(bytes).
Parser that can never succeed, regardless of the given input. It will always fail with the given error problem.
This is mostly useful as a 'base case' if all other parsers
in a one_of or alt have failed, to provide some more descriptive error problem.
const : a -> Parser(_, a, p)
Parser that will always produce the given a, without looking at the actual input.
This is the usual start of a pipeline: const supplies a (curried)
constructor function and each keep feeds it one parsed value.
parse_u32 : Parser(Parser.Utf8.Bytes, U32, _)
parse_u32 = Parser.const(U64.to_u32_wrap).keep(Parser.Utf8.digits({}))
expect parse_u32.parse_str("123") == Ok(123.U32)
alt : Parser(input, a, p), Parser(input, a, p) -> Parser(input, a, p)
Try the first parser and (only) if it fails, try the second parser as fallback.
The second parser starts from the same input as first (backtracking).
If both fail, the failure that reached further is reported; when both
stopped at the same place, the second one is.
Try a list of parsers in turn, until one of them succeeds.
Each parser starts from the same input. An empty list always fails.
For UTF-8 input, Parser.one_of behaves the same way.
color : Parser(Parser.Utf8.Bytes, [Red, Green, Blue], _)
color =
Parser.one_of([
Parser.const(Red).skip(Parser.Utf8.string("red")),
Parser.const(Green).skip(Parser.Utf8.string("green")),
Parser.const(Blue).skip(Parser.Utf8.string("blue")),
])
expect color.parse_str("green") == Ok(Green)
map_problem : Parser(input, a, p), (Problem(p) -> Problem(q)) -> Parser(input, a, q)
Translate structured problems while preserving the furthest failure. Wrap a closed native union in a domain tag when combining formats.
map : Parser(input, a, p), (a -> b) -> Parser(input, b, p)
Transforms the result of parsing into something else, using the given transformation function.
map2 : Parser(input, a, p), Parser(input, b, p), (a, b -> c) -> Parser(input, c, p)
Transforms the result of parsing into something else, using the given two-parameter transformation function.
map3 : Parser(input, a, p), Parser(input, b, p), Parser(input, c, p), (a, b, c -> d) -> Parser(input, d, p)
Transforms the result of parsing into something else, using the given three-parameter transformation function.
If you need transformations with more inputs,
take a look at keep.
flatten : Parser(input, Try(a, Problem(p)), p) -> Parser(input, a, p) where [input.len : input -> U64]
Removes a layer of Try from running the parser.
Use this to map functions that return a Try over the parser:
an Err(msg) value becomes a failure with that problem, reported where
the inner parser started.
even : Parser(Parser.Utf8.Bytes, U64, _)
even =
Parser.Utf8.digits({})
.map(|n| if n % 2 == 0 { Ok(n) } else { Err(OddNumber) })
.flatten()
expect even.parse_str("42") == Ok(42)
expect even.parse_str("7") == Err(ParseError(Parser.Diagnostic.{ problem: OddNumber, location: Text({ offset: 0, line: 1, column: 1 }), path: [] }))
and_then : Parser(input, a, p), (a -> Parser(input, b, p)) -> Parser(input, b, p)
Run first, then build the next parser from its value and run that.
Use this when what comes next depends on what was read, such as a
length prefix. When the next parser is fixed, prefer keep, skip
and map, which are simpler and let the parser be built once.
sized : Parser(Parser.Utf8.Bytes, List(U8), _)
sized = Parser.Utf8.digit({}).and_then(|n| Parser.Utf8.any_codeunit({}).many().map(|bytes| bytes.take_first(n)))
lazy : ({} -> Parser(input, a, p)) -> Parser(input, a, p)
Runs a parser lazily.
This is (only) useful when dealing with a recursive structure.
For instance, consider a type Comment : { message : Str, responses : List(Comment) }.
Without lazy, you would ask the compiler to build an infinitely deep parser.
(Resulting in a compiler error.)
A top-level parser that refers to itself has to be a function, called
inside lazy: tree = |{}| ... with Parser.lazy(|_| tree({})). Top-level
parsers that refer to each other need one lazy somewhere in the cycle,
so that each value can be built before the other is used.
Make a parser optional.
Returns Ok(value) when the given parser succeeds, and Err(Missing)
without consuming input when it fails, so the result never fails.
A parser which runs the element parser zero or more times on the input, returning a list containing all the parsed elements.
Repetition stops at the first element that fails, or that succeeds
without consuming any input; that element's value is not included.
(Without this rule, a parser such as chomp_while or maybe(p) that can
succeed on empty input would repeat forever.) The failure of the element
that stopped the repetition is kept, so if the parse later fails there,
that failure is what gets reported.
one_or_more : Parser(input, a, p) -> Parser(input, List(a), p) where [input.len : input -> U64]
A parser which runs the element parser one or more times on the input, returning a list containing all the parsed elements.
Fails when the first element fails. Also see Parser.many.
between : Parser(input, a, p), Parser(input, open, p), Parser(input, close, p) -> Parser(input, a, p)
Runs a parser for an 'opening' delimiter, then your main parser, then the 'closing' delimiter, and only returns the result of your main parser.
Useful to recognize structures surrounded by delimiters (like braces, parentheses, quotes, etc.)
between_brackets = |parser| parser.between(Parser.Utf8.codeunit('['), Parser.Utf8.codeunit(']'))
sep_by_one_or_more : Parser(input, a, p), Parser(input, sep, p) -> Parser(input, List(a), p) where [input.len : input -> U64]
Parse one or more values separated by separator.
The separators are consumed and omitted from the result.
A trailing separator that is not followed by a value is left unconsumed.
sep_by : Parser(input, a, p), Parser(input, sep, p) -> Parser(input, List(a), p) where [input.len : input -> U64]
Parse zero or more values separated by separator.
The separators are consumed and omitted from the result.
parse_numbers : Parser(Parser.Utf8.Bytes, List(U64), _)
parse_numbers = Parser.Utf8.digits({}).sep_by(Parser.Utf8.codeunit(','))
expect parse_numbers.parse_str("1,2,3") == Ok([1, 2, 3])
ignore : Parser(input, a, p) -> Parser(input, {}, p)
Discard a parser's value while preserving how much input it consumes.
Useful with many to skip a repeated token without collecting values.
keep : Parser(input, a -> b, p), Parser(input, a, p) -> Parser(input, b, p)
Run a parser producing a function, then a parser producing its argument, and return the function result.
Start with const(|a| |b| ...) and add one keep per argument, as in
the module example. The function must be curried (|a| |b| ..., not
|a, b| ...), because its arguments are applied one at a time.
skip : Parser(input, a, p), Parser(input, _, p) -> Parser(input, a, p)
Run two parsers in sequence, discarding the second parser's value.
Both parsers must succeed, and the input read by the second is consumed.
at_sign : Parser(Parser.Utf8.Bytes, [AtSign], _)
at_sign = Parser.const(AtSign).skip(Parser.Utf8.codeunit('@'))
expect at_sign.parse_str("@") == Ok(AtSign)
chomp_until : a -> Parser(List(a), List(a), p) where [a.is_eq : a, a -> Bool]
Match zero or more codeunits until it reaches the given codeunit. The given codeunit is not included in the match and is not consumed. Fails if the codeunit never appears in the remaining input.
This can be used with Parser.skip to ignore text.
ignore_text : Parser(Parser.Utf8.Bytes, U64, _)
ignore_text =
Parser.const(|d| d)
.skip(Parser.chomp_until(':'))
.skip(Parser.Utf8.codeunit(':'))
.keep(Parser.Utf8.digits({}))
expect ignore_text.parse_str("ignore preceding text:123") == Ok(123)
This can be used with Parser.keep to capture a list of U8 codeunits.
capture_text : Parser(Parser.Utf8.Bytes, List(U8), _)
capture_text =
Parser.const(|codeunits| codeunits)
.keep(Parser.chomp_until(':'))
.skip(Parser.Utf8.codeunit(':'))
expect capture_text.parse_str("Roc:") == Ok(['R', 'o', 'c'])
Use Str.from_utf8_lossy to turn the results into a Str.
Also see Parser.chomp_while.
chomp_while : (a -> Bool) -> Parser(List(a), List(a), p)
Match zero or more codeunits until the check returns false.
The codeunit that returned false is not included in the match.
Note: a chomp_while parser always succeeds, possibly consuming nothing.
This can be used with Parser.skip to ignore text.
This is useful for chomping whitespace or variable names.
ignore_numbers : Parser(Parser.Utf8.Bytes, Str, _)
ignore_numbers =
Parser.const(|str| str)
.skip(Parser.chomp_while(|b| b >= '0' and b <= '9'))
.keep(Parser.Utf8.string("TEXT"))
expect ignore_numbers.parse_str("0123456789876543210TEXT") == Ok("TEXT")
This can be used with Parser.keep to capture a list of U8 codeunits.
capture_numbers : Parser(Parser.Utf8.Bytes, List(U8), _)
capture_numbers =
Parser.const(|codeunits| codeunits)
.keep(Parser.chomp_while(|b| b >= '0' and b <= '9'))
.skip(Parser.Utf8.string("TEXT"))
expect capture_numbers.parse_str("123TEXT") == Ok(['1', '2', '3'])
Use Str.from_utf8_lossy to turn the results into a Str.
Also see Parser.chomp_until.
Run a parser and return the input it consumed, instead of its value.
The result is a slice of the input, not a copy, so recognising a token with small parsers and keeping its text costs no allocation.
identifier = Parser.span(Parser.Utf8.codeunit('$').skip(Parser.chomp_while(|b| b >= 'a' and b <= 'z')))
expect identifier.parse_str("$abc") == Ok("$abc".to_utf8())
Parser.Utf8 :: # (opaque)
UTF-8 parser constructors and byte primitives.
codeunit_satisfies : (U8 -> Bool) -> Parser(Bytes, U8, Problem(p))
Match one UTF-8 code unit when it satisfies the given predicate.
Fails on empty input or when the predicate returns False.
is_digit : U8 -> Bool
is_digit = |b| b >= '0' and b <= '9'
expect (Parser.Utf8.codeunit_satisfies(is_digit)).parse_str("0") == Ok('0')
expect (Parser.Utf8.codeunit_satisfies(is_digit)).parse_str("*").is_err()
Match one exact UTF-8 code unit.
For a character outside ASCII, which is several code units, use string.
at_sign : Parser(Parser.Utf8.Bytes, [AtSign], _)
at_sign = Parser.const(AtSign).skip(Parser.Utf8.codeunit('@'))
expect at_sign.parse_str("@") == Ok(AtSign)
expect (at_sign).run_str("$").is_err()
Match an exact sequence of UTF-8 bytes and return them.
Match the given Str exactly (case-sensitive) and return it.
expect (Parser.Utf8.string("Foo")).parse_str("Foo") == Ok("Foo")
expect (Parser.Utf8.string("Foo")).parse_str("Bar").is_err()
any_codeunit : {} -> Parser(Bytes, U8, Problem(p))
Match any single U8 code unit; fails only on empty input.
expect (Parser.Utf8.any_codeunit({})).parse_str("a") == Ok('a')
expect (Parser.Utf8.any_codeunit({})).parse_str("$") == Ok('$')
rest : {} -> Parser(Bytes, Bytes, Problem(p))
Consume the rest of the input and return it as bytes; never fails.
expect {
bytes = "consumes all the input".to_utf8()
Parser.Utf8.rest({}).parse(bytes) == Ok(bytes)
}
Consume the rest of the input as a Str, failing if the bytes are not valid UTF-8.
Parse one ASCII decimal digit into a U64 from 0 through 9.
expect (Parser.Utf8.digit({})).parse_str("0") == Ok(0)
expect (Parser.Utf8.digit({})).parse_str("not a digit").is_err()
Parse one or more ASCII decimal digits into a U64, accepting leading zeroes.
Fails when the input does not start with a digit or the value does not fit
in a U64. Signs and decimal points are not accepted.
expect (Parser.Utf8.digits({})).parse_str("0123") == Ok(123)
expect (Parser.Utf8.digits({})).parse_str("not a digit").is_err()
The index of the first byte at or after pos that is in class, or
the length of bytes if there is none. Scans 16 bytes at a time.
markup = Parser.Utf8.ByteClass.from_bytes(['<', '&'])
expect Parser.Utf8.find_any("a&b<c".to_utf8(), 0, markup) == 1
expect Parser.Utf8.find_any("abc".to_utf8(), 0, markup) == 3
skip_class : Bytes, U64, ByteClass -> U64
The index of the first byte at or after pos that is not in class,
or the length of bytes if every remaining byte is. Use it to skip a
run of name characters, digits or whitespace.
digits = Parser.Utf8.ByteClass.from_predicate(|b| b >= '0' and b <= '9')
expect Parser.Utf8.skip_class("123abc".to_utf8(), 0, digits) == 3
find_line_end : Bytes, U64 -> U64
The index of the next \n or \r at or after pos, or the length of
bytes if there is none. Scans 16 bytes at a time.
expect Parser.Utf8.find_line_end("ab\r\ncd".to_utf8(), 0) == 2
span_class : ByteClass -> Parser(Bytes, Bytes, Problem(p))
Consume the longest run of bytes in class, possibly empty, and return
it as a slice of the input. It scans 16 bytes at a time, so prefer it to
Parser.chomp_while for runs longer than a few bytes.
name_char = Parser.Utf8.ByteClass.from_predicate(|b| (b >= 'a' and b <= 'z') or b == '-')
expect (Parser.Utf8.span_class(name_char)).run_str("foo-bar=1").map_ok(|r| r.rest) == Ok("=1")
UTF-8 input represented as a list of bytes.
Problem : [UnexpectedEnd, ExpectedPredicate, ExpectedByte(U8), ExpectedBytes(List(U8)), InvalidUtf8, ExpectedDigit, IntegerOverflow(U64), ..p]
Byte-parser failures extended by the surrounding grammar's own tags.
Parser.Utf8.ByteClass :: # (opaque)
A set of byte values, for finding or skipping runs of bytes 16 at a time.
Build a class once, outside any loop, and reuse it: construction derives the lookup tables the vector scan uses. Any set of bytes works. A set whose high-nibble rows have at most eight distinct shapes (every ASCII class, and most practical ones) is scanned with two table lookups per 16 bytes; other sets fall back to a byte loop.
spaces = Parser.Utf8.ByteClass.from_bytes([' ', '\t'])
expect spaces.contains('\t')
expect !spaces.contains('x')
from_bytes : List(U8) -> ByteClass
The class holding exactly these bytes.
from_predicate : (U8 -> Bool) -> ByteClass
The class holding every byte b for which check(b) is true.
complement : ByteClass -> ByteClass
The class holding every byte that is not in this one.
Whether the byte is in the class.
Parser.Quotation :: # (opaque)
Compile-time quotation diagnostics and checked constant conversion.
Unwrap a checked conversion, or fail with its explanation. A demanded top-level call runs during compilation.
Build a simple compiler quotation error without inventing coordinates.
Convert a UTF-8 byte offset to a one-based line and byte column. CRLF, CR, and LF each end one line; offsets past the end are clamped.
Parse all text and convert its furthest error into a quotation error.
Use this inside a custom nominal type's from_quote method.
:= {
name : Str ?? "<literal>",
format : Str,
message : Str,
line : U64 ?? 0,
column : U64 ?? 0,
}
The available location and explanation of a checked conversion failure. Zero line or column means that coordinate is unavailable.
:= {
parser : Parser(List(U8), a, p),
source : Str,
name : Str ?? "<literal>",
}
Props for adapting a complete text parser to from_quote.
:= {
problem : problem,
location : Location,
path : List(PathSegment),
}
Structured failures shared by every format.
is_eq : _
Compare and hash diagnostics structurally when their problems support it.
to_hash : _
line_column : Location -> Try({ line : U64, column : U64 }, [NoTextPosition])
Text coordinates when known; binary and generated values have none.
byte_offset : Location -> Try(U64, [NoByteOffset])
Original byte offsets, distinct from generic parser input indexes.
Location : [InputOffset(U64), ByteOffset(U64), Text({ offset : U64, line : U64, column : U64 }), LineColumn({ line : U64, column : U64 }), Unavailable(UnavailableReason)]
Offsets count original bytes, except InputOffset which counts input elements. Lines, columns, records and fields are one-based; indexes are zero-based.
UnavailableReason : [NotRetained, GeneratedValue, NotApplicable]
Logical context retained independently of physical source coordinates.
Counts can stop at the first violation without scanning additional input.
Excerpt : Excerpt
A bounded copy of offending source bytes and its original size.
Location : Location
PathSegment : PathSegment
UnavailableReason : UnavailableReason
Observed : Observed
:= { bytes : List(U8), total_bytes : U64 }
Owned, bounded original bytes for diagnostics. No source allocation is retained.
:= { policy : ErrorPolicy ?? FailFast, max_errors : U64 ?? 1000 }
Error handling. A recovery budget allows exactly max_errors rejects.
InputEnd : InputEnd
Step : Step(state, item, problem)
Parser.Decoder(state, item, problem) :: # (opaque)
A configured incremental decoder; use it with either shared reader.
read_iter : Decoder(state, item, problem), Iter(Bytes) -> Iter(Try(ReadEvent(item, problem), ReadError(problem)))
Lazily consume pure chunks, validating EOF when the source ends.
read_stream : Decoder(state, item, problem), Stream(Try(Bytes, source_error)) -> Stream(Try(ReadEvent(item, problem), [SourceErr(source_error), RecoveryLimitExceeded(Diagnostic(RecoveryProblem(problem))), DecoderProtocol(Diagnostic(ProtocolProblem)), ..problem]))
Consume an effectful source without converting source failure into EOF.
collect : Decoder(state, item, problem), Iter(Bytes) -> Try(List(item), [MissingFinished, SkippedRecords(Report), RecoveryLimitExceeded(Diagnostic(RecoveryProblem(problem))), DecoderProtocol(Diagnostic(ProtocolProblem)), ..problem])
Collect the complete document, rejecting skipped or reported failures.
collect_report : Decoder(state, item, problem), Iter(Bytes) -> Try({ values : List(item), errors : List([..problem]), report : Report }, [MissingFinished, RecoveryLimitExceeded(Diagnostic(RecoveryProblem(problem))), DecoderProtocol(Diagnostic(ProtocolProblem)), ..problem])
Collect both values and the bounded rejected-record diagnostics.
values_stream : Decoder(state, item, problem), Stream(Try(Bytes, source_error)) -> Stream(Try(item, [SourceErr(source_error), MissingFinished, SkippedRecords(Report), RecoveryLimitExceeded(Diagnostic(RecoveryProblem(problem))), DecoderProtocol(Diagnostic(ProtocolProblem)), ..problem]))
Extract fail-fast values from an effectful byte source.
metadata : Decoder(state, item, problem) -> metadata where [state.metadata : state -> metadata]
Inspect only the metadata deliberately provided by this format's state.
step : Decoder(state, item, problem), { bytes : Bytes, end : InputEnd } -> Step(Decoder(state, item, problem), item, [..problem])
Advance manually and retain the returned descriptor.
Parser.Encoder(state, item, problem) :: # (opaque)
A configured record encoder with state and an EOF suffix.
write_iter : Encoder(state, item, problem), Iter(item) -> Iter(Try(Bytes, [InvalidChunkSize(Diagnostic(ChunkSizeProblem)), ..problem]))
Encode records lazily with a bounded final suffix.
write_stream : Encoder(state, item, problem), Stream(Try(item, source_error)) -> Stream(Try(Bytes, [SourceErr(source_error), InvalidChunkSize(Diagnostic(ChunkSizeProblem)), ..problem]))
Encode an effectful source without collecting it.
ReadEvent : ReadEvent(item, problem)
ReadError : ReadError(problem)
ProtocolProblem : ProtocolProblem
RecoveryProblem : RecoveryProblem(problem)
ChunkSizeProblem : ChunkSizeProblem
Report : Report
TextEncoding : TextEncoding
EncodingError : EncodingError
:= { initial_state : state, step : state, Bytes, InputEnd -> Step(state, item, [..problem]), errors : RecoveryProps ?? {} }
Configure a pure state machine without reading input.
:= { initial_state : state, encode : state, item -> Try({ state : state, bytes : Bytes }, [..problem]), finish : state -> Try(Bytes, [..problem]), chunk_bytes : U64 ?? 65_536 }
Configure record encoding and completion without pulling input.
Problem : [UnexpectedInput, NoAlternatives, CharacterNotFound, Utf8Boundary, ..p]
Built-in combinator failures and the caller's domain-specific tags.
ParseResult : Try({ value : a, rest : input }, [ParseError(Diagnostic(Problem(p)))])
The result of running a parser on part of an input: the parsed value
and the rest of the input, or a ParseError diagnostic. Generic
input positions use InputOffset; text runners supply Text coordinates.