moonpsecguide
github
nine steps, one grammar

From a character
to a document.

Every step is code that compiles and runs. Outputs are the real ones; nothing here is illustrative.

01

Add the package

One module, no dependencies. It builds on all four backends.

// moon.mod
import {
  "moonbitstack/moonpsec@0.1.0",
}
02

One parser, one value

A parser reads characters and produces a value. take_while1 reads a run that may not be empty; run hands the text to it and asks for all of it.

let letters = @moonpsec.take_while1(ch => ch.is_ascii_alphabetic())
let answer = @moonpsec.run(letters, "moonbit")
answer = Ok("moonbit")
03

Compose

then runs two parsers in order and keeps the second value; skip keeps the first. Together they read the parts of a sentence a grammar does not want in its result.

let keyword = @moonpsec.string("let")
let binding = keyword.then(@moonpsec.space1.then(letters)).skip(@moonpsec.char(';'))
let bound = @moonpsec.run(binding, "let answer;")
bound = Ok("answer")
04

Repeat, with separators

sep_by reads a list; sep_end_by is the one that also reads a separator after the last item. A separator with nothing after it is a refusal, because the list had already committed to another item the moment the separator was read.

let item = @moonpsec.take_while1(ch => ch != ',')
let list = item.sep_by(@moonpsec.char(','))
let items = @moonpsec.run(list, "a,b,c")
items = Ok(["a", "b", "c"])
05

Read the refusal

A refusal carries the position, the thing that was found, everything that would have been accepted, and any note the grammar attached. to_string is one line for a log; pretty is the form a person needs.

let refusal = @moonpsec.run(@moonpsec.string("let"), "lex").unwrap_err()
let place = refusal.position.to_string()
let said = refusal.to_string()
let drawn = refusal.pretty("lex")
place = "1:3" said = 1:3: unexpected 'x'; expecting "let" drawn = 1:3: | 1 | lex | ^ unexpected 'x' expecting "let"
06

Name what was wanted, then get past it

label puts a reader's word where a character class would go. recover_with runs a second parser at the place of the refusal and keeps the refusal beside the value, so a caller can collect several problems and read on.

let integer = @moonpsec.take_while1(ch => ch.is_ascii_digit()).label("integer")
let forgiving = integer.recover_with(_ => @moonpsec.pure("0"))
let repaired = @moonpsec.run(forgiving, "").unwrap()
repaired.value = "0" repaired.refusal = Some(1:1: unexpected end of input; expecting integer)
07

Know when a branch has committed

A choice tries its other branch only while nothing has been read. attempt puts the text back and lets both be tried — at the cost of retrying work the first branch had already done.

let straight = @moonpsec.string("ab").or(@moonpsec.string("ac"))
let either = @moonpsec.string("ab").attempt().or(@moonpsec.string("ac"))
let first = @moonpsec.run(straight, "ac")
let second = @moonpsec.run(either, "ac")
first = Err(1:2: unexpected 'c'; expecting "ab") second = Ok("ac")
08

Take precedence from a table

make_expr_parser turns a term parser and a table of operators into an expression parser. The table runs from the tightest binding to the loosest; mixed associativity at one level is allowed.

let digit = @moonpsec.char('4').map(_ => 4)
let times = @moonpsec.char('*').map(_ => (a : Int, b : Int) => a * b)
let plus = @moonpsec.char('+').map(_ => (a : Int, b : Int) => a + b)
let levels : Array[Array[@moonpsec.Operator[Int]]] = [
  [@moonpsec.Operator::InfixL(times)],
  [@moonpsec.Operator::InfixL(plus)],
]
let sums = @moonpsec.make_expr_parser(digit, levels)
let worked = @moonpsec.run(sums, "4+4*4")
worked = Ok(20)
09

Feed text that is still arriving

A Feeder takes the text a chunk at a time and answers Needs while the text ends in the middle of something. A grammar without eof answers as soon as it has a value, and the rest of the chunk comes back with it.

let hello = @moonpsec.feeder(@moonpsec.string("hello").eof())
let first_chunk = hello.feed("he")
let second_chunk = hello.feed("llo")
let value = hello.finish()
first_chunk = Needs(1) second_chunk = Needs(1) value = Ok("hello")
—

Where next

The reference lists every name with its signature. The play page runs the reader on whatever you type, and draws the tree the operator table builds.

Two grammars in the repository are worth reading end to end: a JSON reader for RFC 8259 (src/examples/01-json) and a calculator whose precedence is a table (src/examples/02-calc).