Quick start
This page defines a small grammar for a date like 2026-11, then validates with its regex and reads it with its parser.
1. Install
2. Define a grammar
grammar() starts a builder. Each .define(name, builder) adds a rule, and the builder function receives the rules defined before it, by name. .compose() finishes the grammar:
import { , , , } from "@ghostry/aster";
export const = ()
.("digit", () => ("0", "9"))
.("year", ({ }) => ([, , , ]))
.("month", ({ }) => ([, ]))
.("date", ({ , }) => ([, ("-"), ]))
.();range("0", "9")matches one character from0to9.sequence([…])matches each part in turn.literal("-")matches exactly that text.digit,year, andmonthare references to the rules of those names. A builder only sees rules defined before it, so the order of.define()calls matters.
3. Validate with the regex
initialize() returns the functions that read a grammar. toPattern gives the pattern source, and toRegExp compiles it:
import { } from "@ghostry/aster";
import { } from "./date";
const { , } = ();
(, "date"); // "^[0-9][0-9][0-9][0-9]-[0-9][0-9]$"
(, "date").("2026-11"); // true
(, "date").("2026-1"); // falseThe pattern is anchored, so it matches whole strings only. Drop it into a JSON Schema as it is:
{ "type": "string", "pattern": "^[0-9][0-9][0-9][0-9]-[0-9][0-9]$" }4. Read it with the parser
toParser compiles a rule once and returns a function. A match gives you the rule's node, and each named rule inside it is a node too:
import { } from "@ghostry/aster";
import { } from "./date";
const { } = ();
const = (, "date");
const = ("2026-11");
if (.) {
const [year, , ] = ..;
.; // "2026"
; // "-"
..; // 5
}An input that doesn't match is a result too, never an exception:
const failed = parse("2026-x1");
if (!failed.ok) {
failed.message; // 'Expected month at 1:6, found "x".'
}Next steps
- Mental model: how the grammar, the regex, and the parser relate.
- Defining grammars: every combinator, and what each adds to the AST.
- Safe by default: why
toPatterncan refuse a grammar, and what to do then.
