structFeeder
Feeds a parser its text a chunk at a time.
The whole text is kept, and a chunk makes the parser run again from the
start of it, so a document fed in k chunks costs k runs. Chunks of a
kilobyte or more make that cost negligible; feeding a whole file one
character at a time would not, and there is no reason to.
pub struct Feeder[T] {
parser : Parser[T]text : @ref.Ref[String]ended : @ref.Ref[Bool]tab : Int32
pub fn[T] Feeder::feed(Self[T], StringView) -> Progress[T]
Adds a chunk and runs the parser over everything fed so far.
A grammar that describes a prefix of the text reaches Ready as soon as it
has what it needs, and the rest of the chunk comes back with the value. A
grammar that describes the whole document — one that ends in eof, or the
parser given to run — reaches Ready only when the text does.
pub fn[T] Feeder::finish(Self[T]) -> Result[T, Refused]
Ends the text and returns what the parser made of it, refusing anything it
did not read.
pub fn[T] Feeder::text(Self[T]) -> StringView
The text fed so far, which is what a refusal is rendered against.
enumItem
One thing an error talks about: what was found, or what was wanted.
A single character and a run of them are different variants because a
reader expects 'a' for one and "abc" for several, and because the
expected sets of two branches are merged as sets of these.
pub(all) enum Item {
Token(Char)A single character.Tokens(String)A run of characters, whether one long or several.Label(String)A name a parser was given with label — "integer",
"operator" — instead of the characters that would have matched.EndThe end of the text.
Derives Eq, Debug.
pub fn Item::to_string(Self) -> String
Renders a character the way error messages spell it out: a printable
character in single quotes, a control character by name, and a space as
space, because ' ' is invisible in a message.
enumOperator
One operator in a precedence table.
An operator is a parser for the operator itself, not a name to look up: a
grammar that wants + to mean something different in a string context
passes a different parser, and one that wants operators separated from
their operands by space passes a parser that eats the space.
Ternary reads its first separator and produces a parser for its second,
which is what lets a ? b : c be written with the colon only after the
middle operand has been read — the reference shape for a conditional.
pub(all) enum Operator[T] {
InfixL(Parser[(T, T) -> T])InfixR(Parser[(T, T) -> T])InfixN(Parser[(T, T) -> T])Prefix(Parser[(T) -> T])Postfix(Parser[(T) -> T])Ternary(Parser[Parser[(T, T, T) -> T]])
structParser
A parser for values of type T.
A Parser is a description, not a run: it can be run any number of times,
on any text, and combining two of them with [Parser::and_then] or
[Parser::or] builds a third without touching either.
pub struct Parser[T] {
rule : (State) -> Reply[T]
pub fn[T, U] Parser::and_then(Self[T], (T) -> Self[U]) -> Self[U]
Uses the value of one parser to decide what to parse next.
The second parser starts where the first one stopped, so a length prefix
or an opening tag can decide what has to follow it.
pub fn[T] Parser::attempt(Self[T]) -> Self[T]
Runs a parser and then sets aside whether it succeeded.
A refused parser is always safe to run over: the text is left where it was,
which is what makes a sequence of optional clauses possible.
pub fn[T] Parser::chain_left(Self[T], Self[(T, T) -> T]) -> Self[T]
Folds a run of values separated by a left-associative operator.
chain_left(number, plus) reads 1+2+3 as (1+2)+3, which is what the
operator table ends up using for every left-associative operator.
pub fn[T] Parser::chain_right(Self[T], Self[(T, T) -> T]) -> Self[T]
Folds a run of values separated by a right-associative operator, reading
2^3^2 as 2^(3^2).
pub fn[T] Parser::count(Self[T], Int32) -> Self[Array[T]]
Runs a parser a fixed number of times.
pub fn[T] Parser::eof(Self[T]) -> Self[T]
Runs the parser and then requires the text to end.
test {
assert_eq(@moonpsec.run(@moonpsec.any_char, "a"), Ok('a'))
}
pub fn[T] Parser::hidden(Self[T]) -> Self[T]
Drops the expectations of a parser, so that a choice reports only the
branches that were meant to be visible.
pub fn[T] Parser::label(Self[T], String) -> Self[T]
Replaces whatever the parser expected with one name.
Without a label the message of a failed many1(digit) names the character
class; with one it says expecting integer, which is what the reader of
the document needs to know.
pub fn[T] Parser::look_ahead(Self[T]) -> Self[T]
Runs a parser and then puts the position back, keeping its value.
A look_ahead never reads: whatever it matched is still there for the
parser that follows, which is how one parser checks what comes next
without taking it.
pub fn[T] Parser::many(Self[T]) -> Self[Array[T]]
Repeats a parser until it fails, collecting the values.
Stops as soon as a round reads nothing, so a parser that can succeed on
empty text ends the repetition instead of running forever.
pub fn[T] Parser::many1(Self[T]) -> Self[Array[T]]
Repeats a parser until it fails, and requires at least one round.
pub fn[T, S] Parser::many_till(Self[T], Self[S]) -> Self[Array[T]]
Repeats a parser until stop matches, keeping what the parser produced and
discarding the stop.
pub fn[T, U] Parser::map(Self[T], (T) -> U) -> Self[U]
Maps the value of a parser.
test {
let answer = @moonpsec.string("yes").map(s => s.length())
assert_eq(@moonpsec.run(answer, "yes"), Ok(3))
}
pub fn[T] Parser::not_followed_by(Self[T]) -> Self[Unit]
Succeeds, reading nothing, exactly when the parser fails.
The refusal of the inner parser becomes an expectation of nothing at all;
what it matched becomes the surprising thing. not_followed_by(keyword)
is how a grammar says "an identifier, but not a reserved word".
pub fn[T] Parser::optional(Self[T]) -> Self[T?]
Runs a parser if it matches and produces nothing otherwise.
The difference from [Parser::or] with pure(None) is that a parser that
has already read something cannot be skipped: the failure still stands.
pub fn[T] Parser::or(Self[T], Self[T]) -> Self[T]
Tries a second parser when the first one fails without having read
anything.
This is the choice that makes a grammar out of alternatives. The refusals
of both branches are merged, so a reader sees every alternative that was
available at the place where the text stopped making sense.
pub fn[T] Parser::or_else(Self[T], T) -> Self[T]
Runs a parser if it matches and produces fallback otherwise.
pub fn[T] Parser::recover_with(Self[T], (Refused) -> Self[T]) -> Self[Repair[T]]
Runs a parser, and when it refuses, runs recover at the place the refusal
points at, keeping whatever it produces.
The refusal is kept with the value, so a caller that wants to report
several problems can collect them and still walk the rest of the document:
test {
let item = @moonpsec.satisfy(ch => ch == '1').label("a digit")
let forgiving = item.recover_with(_ => @moonpsec.pure('0'))
let repaired = @moonpsec.run(forgiving, "")
assert_eq(repaired.unwrap().value, '0')
}
pub fn[T, S] Parser::sep_by(Self[T], Self[S]) -> Self[Array[T]]
Runs a parser as often as it matches, with separator between the values,
and keeps the values. Zero matches are allowed.
pub fn[T, S] Parser::sep_by1(Self[T], Self[S]) -> Self[Array[T]]
Like [Parser::sep_by], but requires at least one value.
pub fn[T, S] Parser::sep_end_by(Self[T], Self[S]) -> Self[Array[T]]
Runs a parser as often as it matches, with separator after each value,
and keeps the values. Zero matches are allowed.
pub fn[T, S] Parser::sep_end_by1(Self[T], Self[S]) -> Self[Array[T]]
Like [Parser::sep_end_by], but requires at least one value.
pub fn[T, U] Parser::skip(Self[T], Self[U]) -> Self[T]
Runs both parsers in order and keeps the first value.
pub fn[T] Parser::skip_many(Self[T]) -> Self[Unit]
Runs a parser without keeping its values, as often as it matches.
pub fn[T] Parser::skip_many1(Self[T]) -> Self[Unit]
Runs a parser without keeping its values, at least once.
pub fn[T, U] Parser::then(Self[T], Self[U]) -> Self[U]
Runs both parsers in order and keeps the second value, for the punctuation
and keywords a grammar has to read but does not want in its result.
structPosition
A place in the text being parsed.
at is the offset that a [StringView] indexes by, in UTF-16 code units
from the start of the text handed to the parser. line and column start
at one, because that is how an editor counts and a position a reader cannot
find in their file is half a position.
pub(all) struct Position {
at : Int32line : Int32column : Int32
Derives Eq, Debug.
pub fn Position::before(Self, Self) -> Bool
Whether self stands before other in the text.
The offset decides; it is the only one of the three that has to move
forward, and comparing on it keeps two positions taken at the same place
comparable even when one of them came from a recovered error.
pub fn Position::to_string(Self) -> String
Renders the position the way editors and compilers do: line:column.
enumProgress
What a parser makes of the text fed so far.
Needs is the answer that makes a parser incremental: the text ends in the
middle of something, so no verdict is possible until more arrives. Feeding
the next chunk and running again continues from the same place, and a
grammar never has to know that its text arrived in pieces.
pub(all) enum Progress[T] {
Ready(T, StringView)A value, with the text that was left over after it.Needs(Int32)At least this many more code units are needed before anything can be
decided.Failed(Refused)A refusal that more text cannot repair.
pub fn[T] Progress::is_ready(Self[T]) -> Bool
Whether a value has been produced.
pub fn[T] Progress::refusal(Self[T]) -> Refused?
The refusal, when the text has been refused for good.
pub fn[T] Progress::value(Self[T]) -> T?
The value, when there is one.
structRefused
Why a parser refused the text, and where.
got is what the parser was looking at when it gave up, want is
everything that would have been accepted there, and notes holds the
free-form messages fail was given. An error with all
three empty says only that something was refused, which is what a parser
with nothing to say produces.
pub(all) struct Refused {
position : Positiongot : Item?want : Array[Item]notes : Array[String]
Derives Eq, Debug.
pub fn Refused::merge(Self, Self) -> Self
Combines the refusals of two branches of a choice.
The branch that got further is the one whose complaint is worth keeping: it
saw more of the text, so what it expected is what the text was missing. When
both stopped at the same place the two sets of expectations are both right,
and a reader wants to see all of them at once.
pub fn Refused::message(Self) -> String
The refusal as plain lines, the way a compiler prints one: what was found,
then what was wanted, then any message the parser attached.
pub fn Refused::pretty(Self, StringView, tab? : Int32) -> String
The refusal with the line it happened on and a caret under the character,
which is what a person needs to find it.
text is the whole text that was parsed. Lines are shown up to 120
characters around the position; tabs are expanded to eight-column stops so
the caret lands under the right character. Characters wider than one column
— CJK ideographs, most emoji — are counted as two.
pub fn Refused::to_string(Self) -> String
The refusal in one line, prefixed with where it happened: what a log line
or a test assertion wants.
structRepair
A value a recovered parser produced, together with the refusal it got past.
refusal is nothing when the parser matched as written. Keeping it next to
the value is what lets a caller report every problem of a document instead
of stopping at the first one.
pub(all) struct Repair[T] {
value : Trefusal : Refused?
Derives Debug.
enumReply
What a parser says when it is run: it has a value and the state it left,
it refuses the text, or it cannot tell yet because the text it was given
ends where it wanted to look.
The flag on a refusal is whether the parser had already read something.
A choice only falls through to its other branch when nothing was read,
which is the rule that makes a grammar predictable: once a parser has
committed to an interpretation, a later mistake is reported instead of
being quietly retried another way. [Parser::attempt] is how a grammar
says it wants the other branch tried anyway.
pub enum Reply[T] {
Value(T, State)Problem(Refused, Bool)Starved(Int32)
structState
Where a running parser stands: the text, how far into it the parser has
read, the line and column that offset is on, and whether the text is known
to be complete.
A parser is a function from one of these to a reply, so every combinator
gets the rest of the text by way of the state it is handed and gives back
the state it leaves behind. Nothing is ever mutated, which is what makes
backtracking a matter of holding on to an older state.
pub struct State {
text : StringViewat : Int32line : Int32column : Int32complete : Booltab : Int32