Mental model
Aster has three parts: a grammar, which is plain data; the functions initialize returns, which read a grammar; and the two outputs they make from it, a regex and a parser.
A grammar is a list of rules
const date = grammar()
.define("digit", () => range("0", "9"))
.define("year", ({ digit }) => sequence([digit, digit, digit, digit]))
.compose();A composed grammar is { rules }: each rule's name and body, in the order they were defined. A body is built from combinators, and a reference to another rule is held by name, not copied in.
- Each builder sees only earlier rules. A rule can't refer to itself or to a later rule, so every grammar is regular and has a regex form.
- Builders are immutable.
.define()returns a new builder, so two grammars can branch from a shared prefix. - A composed grammar is frozen, all the way down, and survives a JSON round trip. See Grammars as data.
.define()checks each rule as it's added, and throws an error that names the rule. See Definition checks.
initialize builds the functions that read it
const { toPattern, toRegExp, toParser, analyze } = initialize();Defining a grammar needs no configuration, so grammar() and the combinators are plain imports. What reads a grammar comes from initialize, which takes the configuration for the safety check. Every function takes the grammar and a rule name. The name is checked against the grammar's rules by TypeScript.
Two outputs that agree
From the same rule:
toPatternandtoRegExpwrite a regex. Use it to validate: it's fast, and it runs anywhere ECMA-262 regex does.toParserbuilds a parser. Use it to read the structure, or to read input you don't trust.
They accept exactly the same strings. Where an input can be read more than one way, the parser returns the reading the regex engine would pick: the first alternative of an either that leads to a match, and as many iterations of a loop as can still lead to one.
Matching works like a regex
A string matches a rule when some way of reading it through the rule works. An either doesn't commit to the first alternative that matches. That's what a regex does, and what PEG-based parsers don't. Order in an either, and greediness in a loop, decide which reading the parser returns, never whether the input matches.
What each output promises
- The regex is checked before it's returned.
toPatternthrowsVulnerablePatternErrorrather than return a pattern that a backtracking engine can take superlinear time on. See Safe by default. - The parser runs in time linear in the input for every grammar, including ones whose regex
toPatternrefuses. A failed parse returns where it failed and what could have come next. See Parsing.
