@r47onfire/nebula - v0.0.0
    Preparing search index...

    Getting started

    bun add github:@r47onfire/nebula
    # or
    npm install github:@r47onfire/nebula

    A grammar is a plain object mapping rule names to entries, each entry holding the rule's definition combinator (and, for a parameterized rule, its parameter names). Combinators are also plain data -- every constructor below just builds a node of the grammar:

    import {
    defineGrammar,
    lit,
    param,
    parseToCST,
    regex,
    rule,
    seq,
    } from "@r47onfire/nebula";

    const grammar = defineGrammar({
    main: { def: rule("wrap", lit("("), lit(")")) },
    wrap: {
    params: ["open", "close"],
    def: seq(param("open"), rule("word"), param("close")),
    },
    word: { def: regex(/[a-z]+/) },
    });

    Two things to notice:

    • rule("word") refers to another rule by name. A rule that succeeds produces a CST node whose type is the rule name.
    • wrap is a parameterized rule: its entry carries a params list alongside its def. rule("wrap", lit("("), lit(")")) calls it with two combinator arguments, and inside the body param("open") and param("close") stand for them. Different call sites can pass different arguments and get different parses from the same rule body.
    const cst = parseToCST("(abc)", new URL("test"), 0, "main", grammar, "exprs");
    

    The arguments are the text, the filename (as a URL), the index to start at, the start rule, the grammar, and the node type to wrap recovered text in when the parse has to skip over input it cannot match. An optional seventh argument names the error node type (default "BAD"), and an optional eighth passes in a memo table to reuse across parses of an unchanged grammar.

    The result is a CSTNode. Named nodes have a type, every node knows its start/end offsets and the text it matched, and concatenating the text of all the leaves -- including ignored ones -- reproduces the input exactly.

    Parsing does not throw on bad input. A position where nothing matched becomes an error node whose errorExpected field holds the combinator that should have matched there, which is also how a caller can render "expected X" messages. See The CST and compiling it for condensing a CST and formatting errors.