moonpsecreference
github

moonpsec

moonbitstack/moonpsec

Everything a grammar can name: the parsers that read a character or a run of them, the combinators that build bigger parsers out of smaller ones, the four ways to run one, and what comes back when the text is refused.

types

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 : Int32
  • line : Int32
  • column : 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 : Position
  • got : 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 : T
  • refusal : 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 : StringView
  • at : Int32
  • line : Int32
  • column : Int32
  • complete : Bool
  • tab : Int32

values

letalpha_num

pub let alpha_num : Parser[Char]

Reads an ASCII letter or a decimal digit.

letany_char

pub let any_char : Parser[Char]

Reads the next character without any expectation attached, so that a failure of it says only what was found.

letascii

pub let ascii : Parser[Char]

Reads an ASCII character, refusing anything above U+007F.

letat_end

pub let at_end : Parser[Bool]

Whether the text has ended, without requiring it: an if in a grammar wants to ask rather than to insist.

letblank

pub let blank : Parser[Char]

Reads an ASCII space or tab, the two characters that separate tokens without ending a line.

letcontrol

pub let control : Parser[Char]

Reads a control character.

letcrlf

pub let crlf : Parser[Unit]

Reads a carriage return followed by a line feed, the line ending of HTTP and of every text file that came through Windows.

letdigit

pub let digit : Parser[Char]

Reads a decimal digit. Only the ten ASCII digits count: every number notation a grammar is likely to describe spells its digits this way, and a script's own digits are a different question from what the number means.

leteof

pub let eof : Parser[Unit]

Succeeds only at the end of the text, and reads nothing.

test {
assert_eq(@moonpsec.run(@moonpsec.eof, ""), Ok(()))
}

lethex_digit

pub let hex_digit : Parser[Char]

Reads a hexadecimal digit, either case.

letletter

pub let letter : Parser[Char]

Reads an ASCII letter.

letlower

pub let lower : Parser[Char]

Reads a lowercase ASCII letter.

letnewline

pub let newline : Parser[Char]

Reads a line feed.

letoct_digit

pub let oct_digit : Parser[Char]

Reads an octal digit.

letposition

pub let position : Parser[Position]

The position the parser has reached, without reading anything.

letprintable

pub let printable : Parser[Char]

Reads a character that a terminal draws, which is what a lexer wants when the text may be pasted from anywhere.

letpunctuation

pub let punctuation : Parser[Char]

Reads an ASCII punctuation character.

letspace

pub let space : Parser[Char]

Reads one whitespace character, of any script's spaces.

letspace1

pub let space1 : Parser[Unit]

Reads whitespace until it runs out, and reads nothing if there is none.

letstart

pub let start : Position

The position at the start of any text: offset zero, line one, column one.

lettab

pub let tab : Parser[Char]

Reads a horizontal tab.

lettake_rest

pub let take_rest : Parser[String]

Reads everything that is left. Over a text that is still arriving this waits for the end rather than handing back half of it.

letupper

pub let upper : Parser[Char]

Reads an uppercase ASCII letter.

functions

fnbetween

pub fn[T, O, C] between(Parser[O], Parser[C], Parser[T]) -> Parser[T]

Runs a parser between an opening and a closing parser, keeping its value.

fnchar

pub fn char(Char) -> Parser[Char]

Reads exactly ch.

test {
assert_eq(@moonpsec.run(@moonpsec.char('a'), "a"), Ok('a'))
}

fnchar_ci

pub fn char_ci(Char) -> Parser[Char]

Reads ch in either case, which is how a grammar accepts NULL and null without listing both. The comparison folds the two ASCII cases only; letters outside ASCII have case pairs that need a Unicode table, so they have to be listed.

fnchoice

pub fn[T] choice(Array[Parser[T]]) -> Parser[T]

Tries the parsers in order and produces the first value that one of them can parse.

fnfail

pub fn[T] fail(String) -> Parser[T]

A parser that always refuses, saying why. Nothing is read, so a choice still tries its other branch.

fnfeeder

pub fn[T] feeder(Parser[T], tab? : Int32) -> Feeder[T]

Starts a parser on text that has not arrived yet.

test {
let feeder = @moonpsec.feeder(@moonpsec.string("ab").eof())
assert_eq(feeder.feed("a") is @moonpsec.Progress::Needs(_), true)
assert_eq(feeder.feed("b") is @moonpsec.Progress::Needs(_), true)
assert_eq(feeder.finish().unwrap(), "ab")
}

fnmake_expr_parser

pub fn[T] make_expr_parser(Parser[T], Array[Array[Operator[T]]]) -> Parser[T]

Builds an expression parser from a term parser and a table of operators. The table is ordered by precedence, highest first; every operator in one entry has the same precedence. A prefix or postfix operator binds tighter than any infix operator of the same entry, and two unary operators of the same entry are not allowed in a row, so --1 is a refusal rather than a double negation — a grammar that wants the latter wraps the operator in many itself.

test {
let number = @moonpsec.satisfy(ch => ch >= '0' && ch <= '9').map(ch => {
ch.to_int() - '0'.to_int()
})
let plus = @moonpsec.char('+').map(_ => (a : Int32, b : Int32) => a + b)
let times = @moonpsec.char('*').map(_ => (a : Int32, b : Int32) => a * b)
let expr = @moonpsec.make_expr_parser(number, [
[@moonpsec.Operator::InfixL(times)],
[@moonpsec.Operator::InfixL(plus)],
])
assert_eq(@moonpsec.run(expr, "1+2*3"), Ok(7))
}

fnnone_of

pub fn none_of(StringView) -> Parser[Char]

Reads one character that is not in set.

fnone_of

pub fn one_of(StringView) -> Parser[Char]

Reads one character out of set.

fnparse

pub fn[T] parse(Parser[T], StringView, tab? : Int32) -> Result[(T, Position), Refused]

Runs a parser over the whole of text and returns its value with the position it ended at, which is what a test of a line or a column wants.

test {
let word = @moonpsec.satisfy(ch => ch != ' ').many()
let (value, end) = @moonpsec.parse(word, "hi").unwrap()
assert_eq(value.length(), 2)
assert_eq(end.line, 1)
assert_eq(end.column, 3)
}

fnpure

pub fn[T] pure(T) -> Parser[T]

A parser that always produces the same value and reads nothing.

fnrun

pub fn[T] run(Parser[T], StringView, tab? : Int32) -> Result[T, Refused]

Runs a parser over the whole of text and returns its value. Text left over is a refusal, the same as any other: a grammar that describes one value describes the whole of a document, so run adds the end of the text to it.

test {
let digits = @moonpsec.satisfy(ch => ch >= '0' && ch <= '9').many()
assert_eq(@moonpsec.run(digits, "123").unwrap().length(), 3)
}

fnrun_partial

pub fn[T] run_partial(Parser[T], StringView, tab? : Int32) -> Result[(T, StringView), Refused]

Runs a parser over text and returns its value with the text it did not read.

fnrun_position

pub fn[T] run_position(Parser[T], StringView, tab? : Int32) -> Result[(T, Position), Refused]

Runs a parser over text and returns its value with the position it stopped at, whether or not it read everything.

test {
let (_, place) = @moonpsec.run_position(@moonpsec.take(1), "\ta").unwrap()
assert_eq(place.column, 9)
}

fnsatisfy

pub fn satisfy((Char) -> Bool, want? : Item) -> Parser[Char]

Reads the next character if it passes check. want names what the caller was looking for; without it a refusal says only what it found, which is the right thing for a predicate the reader could not have guessed.

fnstream

pub fn[T] stream(Parser[T], Iter[StringView], tab? : Int32) -> Result[T, Refused]

Runs a parser over text that arrives as chunks, and requires it to describe all of it. This is run for a stream: the chunks are fed in order and the text ends after the last one.

test {
let parser = @moonpsec.take_while1(ch => ch.is_ascii_alphabetic())
assert_eq(
@moonpsec.stream(parser, ["ab"[:], "cd"[:]].iter()).unwrap(),
"abcd",
)
}

fnstring

pub fn string(StringView) -> Parser[String]

Reads exactly text and produces it. The whole run is compared, and a mismatch is reported against the whole run rather than the character that broke it, because that is what the grammar was asking for.

test {
assert_eq(@moonpsec.run(@moonpsec.string("let"), "let"), Ok("let"))
}

fnstring_ci

pub fn string_ci(StringView) -> Parser[String]

Reads text in either ASCII case and produces what the grammar wrote, which keeps TRUE from becoming true in the result.

fntake

pub fn take(Int32) -> Parser[String]

Reads exactly times characters and produces them, refusing when the text ends first.

fntake_while

pub fn take_while((Char) -> Bool) -> Parser[String]

Reads characters while check holds and produces them as text. Reads nothing when the first character does not pass. The scan keeps the counters in local variables and builds one state at the end: a combinator that allocates a state per character is a combinator that turns a scan of a document into a scan of the allocator.

test {
let spaces = @moonpsec.take_while(ch => ch == ' ')
assert_eq(@moonpsec.run(spaces, "   "), Ok("   "))
}

fntake_while1

pub fn take_while1((Char) -> Bool) -> Parser[String]

Like [take_while], but requires at least one character.

Two types appear at the end because the interface names them, not because a grammar does: State is where a parser stands and Reply is what it answers with. They are built by the library; a grammar only holds parsers.