A MoonBit port of PEG.js: parser generator for MoonBit
Dependencies
| What | Cases | Result |
|---|---|---|
| Grammar parser: ASTs (locations, comments) and syntax errors | 595 | identical |
| Compiler passes run directly (checks, transforms, bytecode) | 214 | identical |
| generate() + parse, over cache/trace/optimize variants | 1108 grammars, 1656 parses | identical |
| Bytecode of examples/{arithmetics,json,css,javascript}.pegjs and of PEG.js' own grammar | 5 | identical |
| Generated MoonBit parsers (speed/size × cache × trace) | 753 parsers, 1248 parses | identical |
| Parser generated from PEG.js' grammar rewritten with MoonBit code blocks | 595 | identical |
///|
test "runtime parser with actions" {
let grammar =
#|start = head:number tail:("+" @number)* { sum }
#|number = [0-9]+ { toNumber }
let parser : @peg.Parser[Unit] = @peg.generate(
grammar,
options=@peg.Options::new(actions={
"toNumber": ctx => {
let mut n = 0.0
for c in ctx.text() {
n = n * 10.0 + (c.to_int() - '0'.to_int()).to_double()
}
Num(n)
},
"sum": ctx => {
let mut total = ctx.label("head")
for x in ctx.label("tail").as_arr().unwrap() {
guard (total, x) is (Num(a), Num(b)) else { fail("not numbers") }
total = Num(a + b)
}
total
},
}),
)
debug_inspect(parser.parse("1+20+300"), content="Num(321)")
}///|
test "default values and errors" {
let parser : @peg.Parser[Unit] = @peg.generate("start = 'a' [0-9]? $('b'+)")
debug_inspect(
parser.parse("abbb"),
content=(
#|Arr([Str("a"), Null, Str("bbb")])
),
)
let message = try parser.parse("ac") catch {
@runtime.SyntaxError(message~, ..) => message
_ => "other error"
} noraise {
_ => "parsed"
}
inspect(
message,
content=(
#|Expected "b" or [0-9] but "c" found.
),
)
}{
// The initializer runs once per parse; its definitions are visible to all
// code blocks.
fn num(v : PegValue) -> Double {
match v {
Num(n) => n
_ => 0.0
}
}
}
Sum
= head:Integer tail:(_ "+" _ @Integer)* {
let mut total = num(head)
for x in tail.as_arr().unwrap() {
total = total + num(x)
}
Num(total)
}
Integer "integer"
= [0-9]+ &{ ctx.text().length() < 10 } { Num(@string.parse_double(ctx.text())) }
_ = " "*moon run --target native cmd/pegmbt -- sum.pegjs # writes sum.mbt| Package | Contents |
|---|---|
| bobzhang/peg | generate, generate_source, new_session, re-exports |
| bobzhang/peg/runtime | Value, locations, expectations, errors, parse state, JS string semantics |
| bobzhang/peg/bytecode | opcodes and compiled Programs |
| bobzhang/peg/ast | grammar AST (JSON-compatible with PEG.js') |
| bobzhang/peg/parser | the grammar parser (frozen bytecode of src/parser.pegjs) |
| bobzhang/peg/compiler | session, options and all compiler passes |
| bobzhang/peg/vm | the bytecode interpreter |
| bobzhang/peg/codegen | MoonBit source generation |
| bobzhang/peg/cli, cmd/pegmbt | the command-line tool (native) |
moon test --target allInstall
Download zipA MoonBit port of PEG.js: parser generator for MoonBit
Dependencies