moon-gbnf

    Pure MoonBit GBNF (GGML BNF) grammar compiler, static validator, JSON Schema to GBNF compiler, and incremental LLM constrained decoding engine.

    gbnf
    llm
    grammar
    constrained-decoding
    json-schema
    parser
    llama-cpp
    Download zip
    Version
    0.1.1
    License
    Apache-2.0
    Last updated
    10 hours ago
    Downloads
    10

    No dependencies

    #moon-gbnf

    纯 MoonBit 实现的 GBNF(GGML BNF)语法编译器、JSON Schema 编译器与 LLM 结构化受限解码引擎 A pure MoonBit 1.0, zero-FFI GBNF grammar compiler, static validator, JSON Schema → GBNF compiler, and incremental constrained decoding engine for LLMs.

    CI mooncakes.io Playground License


    #为什么做 moon-gbnf?

    在本地大模型推理与 AI Agent 开发中,结构化输出(Structured Outputs) 是让 LLM 稳定输出合法 JSON、SQL、函数调用参数或自定义 DSL 的关键技术。由 llama.cpp 提出的 GBNF(GGML BNF) 已成为开源大模型生态中事实上的语法约束标准。

    moon-gbnf 使用纯 MoonBit 1.0 编写、零外部 FFI 依赖,可同时编译至 Native / WebAssembly (WASM / WASM-GC) / JavaScript 后端,为 MoonBit AI 生态补齐语法约束与受限解码核心组件。


    #在线 Playground(GitHub Pages)

    • 在线地址:https://eprogressing.github.io/moon-gbnf/
    • 技术架构:基于零 FFI 的 MoonBit ESM 外设桥接包(playground_bridge/)与纯静态 Web 应用(web/),通过 .github/workflows/pages.yml 自动部署到 GitHub Pages。
    • 双栏实时交互:
      • 左侧面板(Grammar / JSON Schema 编译与静态诊断):支持 GBNF 与 JSON Schema 实时切换、内置正则 pattern / allOf / 整数边界 / additionalProperties / 错误诊断预设,实时展示语法规则与静态分析报错(高亮左递归 LeftRecursion、未定义规则 UndefinedRule 及精确 line:col)。
      • 右侧面板(逐字符受限解码与词表 Token 掩码):支持逐字符推进(Step +1 char)、实时显示合法前缀长度、下一合法字符区间(allowed_ranges)以及词表 Token 掩码(含 <eos> 门控)。
    • 本地构建与预览:
      moon build --target js --release && node web/build.mjs --stage _build/pages node web/verify_playground.mjs


    #核心特性与架构

    JSON Schema ──▶ [JSON Schema + Regex Compiler] ──┐ ▼ GBNF Text ──▶ [Lexer & Parser] ──────────▶ [AST & Static Validator] │ ▼ [Normalized Flat IR] │ ▼ [Incremental Constrained Decoding Engine] ├── accept_codepoint / accept_str (事务式增量校验) ├── allowed_ranges (合法 Unicode 码点区间并集) ├── mask_vocab / allowed_token_ids (128-entry ASCII 位图 + 前缀缓存) └── clone (O(1) 尾递归优化 + Beam Search 快照回溯)

    #已实现模块

    • 支持规则定义 (::=)、选择 (|)、序列、分组 ((...))、量词 (*, +, ?, {m}, {m,}, {m,n})
    • 支持字符串字面量、字符类 [a-z]、否定字符类 [^...]、Unicode 转义 (\xHH, \uHHHH, \UHHHHHHHH) 与 # 注释
    • 精准行列号诊断错误信息
    • 缺失 root、重复定义、未定义引用、不可达规则警告、Grammar::issue_span 行列号定位
    • 不动点 Nullable 分析、直接/间接左递归检测与零消耗空循环检测
    • 区间排序合并、合法 Unicode 标量值补集运算、二分查找
    • 线性可选链与右递归展开,避免指数爆炸与左递归
    • 支持字面量、转义、\d/\D/\w/\W/\s/\S、.、[...]/[^...]、^/$ 锚点、量词 (*/+/?/{m,n})、分组与选择 (|),以及 RFC 8259 JSON 字符串安全转义
    • 对非上下文无关特性(如反向引用 backreferences、环视 lookarounds)返回显式 RegexError::UnsupportedFeature 错误
    • 支持 object / array / string / number / integer / boolean / null / enum / const / required / 全可选属性链
    • 支持递归 $ref(#/$defs/...、内部 JSON Pointer)、allOf 递归合并与冲突检测、整数 minimum / maximum(及 exclusiveMinimum / exclusiveMaximum)、additionalProperties(false / true / schema 对象)、pattern、anyOf / oneOf、联合类型 type: [...]、minLength / maxLength、minItems / maxItems 及内置 format(date、date-time、uuid、email)
    • 紧凑非字符串 StackSet 去重 + 尾调用优化(长序列恒定栈深)、事务式回滚、clone() 状态快照
    • 128 项 ASCII 位图 + VocabStepCache 状态前缀缓存,面向 32k–128k 词表优化 mask_vocab() / allowed_token_ids()(含 EOS 门控)
    • 实用纯 MoonBit 零 FFI CLI 子命令(demo, validate, schema, decode, mask, bench, help)
    • 32k / 64k / 128k 确定性基准测试套件与全套 llama.cpp 标准语法兼容测试(compat_test.mbt)


    #快速开始

    #环境要求

    • MoonBit 工具链(已在 moon 0.1.20261126 / MoonBit 1.0 验证)
    • Node.js 22+(仅用于本地构建预览 Playground 与运行 E2E 检查)

    #运行检查与多后端测试

    moon fmt --check moon check --target all --warn-list "+missing_doc" --deny-warn moon test --target wasm-gc moon test --target native moon test --target js

    #CLI 实用子命令(cmd/)

    因核心与 CLI 均保持零 FFI 跨后端设计(统一支持 wasm-gc / native / js),所有子命令直接接收内联文法/Schema 字符串,或通过 shell 命令替换读取文件(例如 "$(cat grammar.gbnf)"):

    # 1. 默认交互 Demo(与 demo 子命令等价) moon run cmd moon run cmd -- demo # 2. 查看帮助 moon run cmd -- --help # 3. 静态校验并编译 GBNF(含 LeftRecursion / UndefinedRule 行列号诊断) moon run cmd -- validate 'root ::= "ok" ("!" | "?")' moon run cmd -- validate "$(cat grammar.gbnf)" # 4. 将 JSON Schema 编译为原始 GBNF 文本 moon run cmd -- schema '{"type":"object","properties":{"code":{"type":"string","pattern":"^[A-Z]{2}$"},"n":{"type":"integer","minimum":1,"maximum":9}},"required":["code","n"],"additionalProperties":false}' # 5. 增量解码校验(支持以 "-" 开头的输入参数及 --schema 模式) moon run cmd -- decode 'root ::= "-" [0-9]+' "-1" moon run cmd -- decode --schema '{"type":"integer","minimum":1,"maximum":9}' "7" # 6. 词表级 Token 掩码与下一合法字符区间查询 moon run cmd -- mask 'root ::= "ab"' "a" '["<eos>","a","b"]' --eos 0 # 7. 运行纯 MoonBit 32k / 64k / 128k 基准测试 moon run cmd -- bench

    #核心 API 示例

    #1. 解析、校验并增量解码 GBNF

    let gbnf =
    #|root ::= "{\"ok\":" ("true" | "false") "}"

    let compiled = @moon_gbnf.compile(gbnf).unwrap()
    let state = @moon_gbnf.GrammarState::new(compiled)

    let vocab = ["<eos>", "{\"ok\":", "true", "false", "null", "}"]
    let allowed = state.allowed_token_ids(vocab, eos_token_id=0) // [1]

    #2. 直接从 JSON Schema 编译受限解码器

    let schema =
    #|{
    #| "type": "object",
    #| "properties": {
    #| "tool": { "enum": ["search", "calc"] },
    #| "query": { "type": "string", "minLength": 1 }
    #| },
    #| "required": ["tool", "query"]
    #|}

    let cg = @moon_gbnf.compile_json_schema(schema).unwrap()
    assert_eq(cg.matches("{\"tool\": \"search\", \"query\": \"moonbit\"}"), true)
    assert_eq(cg.matches("{\"tool\": \"delete\", \"query\": \"x\"}"), false)


    #Benchmarks

    All benchmarks run in pure MoonBit (zero FFI) with deterministic BPE-style vocabularies (32,768, 65,536, and 128,000 tokens covering ASCII single bytes, JSON punctuation/escapes, whitespace runs, keywords, numeric fragments, shared-prefix subwords, and multi-byte UTF-8 CJK/accented/emoji tokens).

    • Environment: Apple M4 / macOS 26.3.1 (arm64), moon 0.1.20261126 (ccd306a 2026-11-26), --target native --release
    • Reproduce:
      moon run bench --target native --release moon bench --target native --release

    #Summary across 32k / 64k / 128k Vocabularies

    Vocabulary ScaleCompile (compile / compile_json_schema)Step Validation (accept_char / accept_str)mask_vocab Latency (JSON Schema {)mask_vocab Throughput (tok/s)
    32,768 (32k)0.06 ms / 0.29 ms1.85 µs / 3.46 µs0.38 ms87,251,378 tok/s
    65,536 (64k)0.06 ms / 0.29 ms1.85 µs / 3.46 µs0.88 ms74,291,783 tok/s
    128,000 (128k)0.06 ms / 0.29 ms1.85 µs / 3.46 µs1.68 ms76,372,357 tok/s

    #Compilation & Incremental Stepping

    OperationWorkloadMean Latency
    compileArithmetic GBNF0.04 ms
    compileJSON GBNF0.06 ms
    compileC-like GBNF0.08 ms
    compile_json_schemaNested Schema ($ref + allOf + pattern + bounds + additionalProperties)0.29 ms
    accept_char (per char)JSON GBNF (69 chars)1.85 µs/step
    accept_char (per char)Nested JSON Schema (75 chars)0.60 µs/step
    accept_str (per token)Nested JSON Schema (12 tokens)3.46 µs/step

    #Large-Vocabulary mask_vocab (32k / 64k / 128k)

    Grammar & Decoder State32,768 tokens (ms/step | tok/s)65,536 tokens (ms/step | tok/s)128,000 tokens (ms/step | tok/s)
    JSON Schema (initial {)0.38 ms | 87,251,378 tok/s0.88 ms | 74,291,783 tok/s1.68 ms | 76,372,357 tok/s
    JSON Schema (mid-value pattern)0.21 ms | 157,751,429 tok/s0.50 ms | 130,286,884 tok/s1.66 ms | 76,940,428 tok/s
    JSON GBNF (initial {)0.49 ms | 66,203,640 tok/s1.03 ms | 63,870,542 tok/s3.95 ms | 32,445,933 tok/s
    JSON GBNF (mid-value {"key": )2.93 ms | 11,182,879 tok/s5.26 ms | 12,455,989 tok/s9.77 ms | 13,096,947 tok/s
    C-like GBNF (mid-body { )3.86 ms | 8,484,536 tok/s10.83 ms | 6,048,704 tok/s16.49 ms | 7,760,048 tok/s


    #打包与发布(mooncakes.io)

    使用 moon package --list 可验证可发布压缩包的纯洁性(e2e/ 与 web/ 通过 .moonignore 排除):

    moon package --list moon package

    完整的本地预检步骤与人工交互式 mooncakes.io 发布清单(严格按 moon login → moon publish --dry-run → moon publish 顺序执行)请参见 RELEASE.md。


    #开源许可与第三方声明(License & Open-Source Attribution)

    • 原创代码许可(Apache-2.0):moon-gbnf 的全部原创 MoonBit 源码、CLI、基准测试、Playground 及原创测试代码均基于官方 Apache License, Version 2.0 发布(见 LICENSE 与 NOTICE)。
    • 第三方兼容测试文法(MIT License):compat_test.mbt 及 e2e/fixtures/*.gbnf(含 e2e/fixtures/LICENSE_ATTRIBUTIONS.md 所列测试夹具)中内嵌/改编的 8 套标准 GBNF 测试文法样例(json.gbnf、arithmetic.gbnf、list.gbnf、c.gbnf、chess.gbnf、english.gbnf、japanese.gbnf、json_arr.gbnf)衍生自开源项目 ggml-org/llama.cpp(grammars/ 目录),继续保留其原作者 The ggml authors 版权声明(Copyright (c) 2023-2026 The ggml authors)及原始 MIT License 授权条款。完整的 MIT 许可全文与文件清单请见 licenses/LICENSE-llama.cpp-MIT.txt 和 THIRD_PARTY_LICENSES.md。

    CharRange

    pub(all) struct CharRange {
    start : Int
    end : Int
    } derive(Eq,
    Debug
    )

    Inclusive Unicode code point range [start, end].

    CompileError

    pub(all) enum CompileError {
    ParseFailed(ParseError)
    ValidationFailed(Array[ValidationIssue])
    } derive(Eq,
    Debug
    )

    Errors returned during full compilation (parse + validate + lower).

    CompiledGrammar

    pub(all) struct CompiledGrammar {
    root_id : Int
    rules : Array[IrRule]
    rule_index : Map[String, Int]
    } derive(Eq,
    Debug
    )

    Flat, validated, indexed representation ready for incremental decoding.

    CompiledGrammar::matches

    fn CompiledGrammar::matches(self : CompiledGrammar, s : String) -> Bool

    Return true iff the entire string s is a complete valid sentence of this grammar.

    Expr

    pub(all) enum Expr {
    Literal(Array[Int])
    CharClass(Array[CharRange], Bool)
    RuleRef(String)
    AnyChar
    Seq(Array[Expr])
    Alt(Array[Expr])
    Repeat(Expr, Int, Int?)
    } derive(Eq,
    Debug
    )

    GBNF expression AST node.

    Expr::to_gbnf

    fn Expr::to_gbnf(self : Expr) -> String

    Format an expression back into canonical GBNF syntax.

    Grammar

    pub(all) struct Grammar {
    rules : Array[Rule]
    } derive(Eq,
    Debug
    )

    A parsed GBNF grammar containing ordered production rules.

    Grammar::compile

    Validate and lower a parsed Grammar into a CompiledGrammar.

    Grammar::find_empty_cycles

    fn Grammar::find_empty_cycles(self : Grammar) -> Array[String]

    Detect rules that can cyclically derive themselves while consuming zero characters.

    Grammar::find_left_recursion

    fn Grammar::find_left_recursion(self : Grammar) -> Array[String]

    Detect rules participating in direct or indirect left recursion.

    Grammar::get_rule

    fn Grammar::get_rule(self : Grammar, name : String) -> Rule?

    Look up a rule by name.

    Grammar::issue_span

    fn Grammar::issue_span(self : Grammar, issue : ValidationIssue) -> Span?

    Resolve the best-effort source Span for a static validation diagnostic. Returns the duplicate rule's Span for DuplicateRule, the owning or referencing rule's Span for rule-scoped issues, and None for grammar-wide diagnostics (EmptyGrammar, MissingRoot).

    Grammar::nullable_rules

    fn Grammar::nullable_rules(self : Grammar) -> Map[String, Bool]

    Compute the fixed-point set of rules that can match the empty string.

    Grammar::rule_dependencies

    fn Grammar::rule_dependencies(self : Grammar) -> Map[String, Array[String]]

    Return direct rule-to-rule dependency adjacency map.

    Grammar::rule_names

    fn Grammar::rule_names(self : Grammar) -> Array[String]

    Return the ordered list of rule names defined in this grammar.

    Grammar::to_gbnf

    fn Grammar::to_gbnf(self : Grammar) -> String

    Format a full grammar into canonical GBNF text.

    Grammar::validate

    fn Grammar::validate(self : Grammar) -> ValidationReport

    Perform static semantic validation on a parsed GBNF grammar.

    GrammarState

    pub struct GrammarState {
    grammar : CompiledGrammar
    // private fields
    }

    Incremental stack-based constrained decoding state machine.

    GrammarState::accept_char

    fn GrammarState::accept_char(self : GrammarState, c : Char) -> Bool

    Transactionally feed one Char.

    GrammarState::accept_codepoint

    fn GrammarState::accept_codepoint(self : GrammarState, cp : Int) -> Bool

    Transactionally feed one Unicode code point. Returns true and advances the state if legal; returns false leaving state unchanged otherwise.

    GrammarState::accept_str

    fn GrammarState::accept_str(self : GrammarState, s : String) -> Bool

    Transactionally feed an entire UTF-8 string (e.g., an LLM token). If any character is illegal, returns false and rolls back to the prior state.

    GrammarState::active_stack_count

    fn GrammarState::active_stack_count(self : GrammarState) -> Int

    Return the number of currently active parse stacks (for diagnostics/debugging).

    GrammarState::allowed_ranges

    fn GrammarState::allowed_ranges(self : GrammarState) -> Array[CharRange]

    Compute the normalized union of all Unicode code point ranges legally accepted next.

    GrammarState::allowed_token_ids

    fn GrammarState::allowed_token_ids(self : GrammarState, vocab : Array[String], eos_token_id? : Int) -> Array[Int]

    Return the list of allowed token IDs for an LLM vocabulary at the current state.

    GrammarState::can_accept_codepoint

    fn GrammarState::can_accept_codepoint(self : GrammarState, cp : Int) -> Bool

    Non-mutating check whether a single code point can legally be accepted next.

    GrammarState::can_accept_str

    fn GrammarState::can_accept_str(self : GrammarState, s : String) -> Bool

    Non-mutating check whether a multi-character token string is legally accepted next.

    GrammarState::clone

    Deep-clone the decoding state for Beam Search, backtracking, or speculative decoding.

    GrammarState::is_complete

    fn GrammarState::is_complete(self : GrammarState) -> Bool

    Return true iff the input consumed so far constitutes a complete valid match.

    GrammarState::mask_vocab

    fn GrammarState::mask_vocab(self : GrammarState, vocab : Array[String], eos_token_id? : Int) -> Array[Bool]

    Compute a boolean allow-mask over an LLM token vocabulary. If eos_token_id is provided, that token is allowed iff self.is_complete().

    GrammarState::new

    Create a fresh incremental decoding state starting from the grammar's root rule.

    GrammarState::reset

    fn GrammarState::reset(self : GrammarState) -> Unit

    Reset this decoding state back to the initial root state, reusing internal scratch buffers.

    IrElement

    pub(all) enum IrElement {
    CharRanges(Array[CharRange])
    RuleRef(Int)
    } derive(Eq,
    Debug
    )

    Atomic element inside a compiled flat GBNF alternative.

    IrRule

    pub(all) struct IrRule {
    name : String
    alts : Array[Array[IrElement]]
    } derive(Eq,
    Debug
    )

    A compiled rule consisting of one or more flat alternatives. An empty alternative [] represents epsilon (matches zero characters).

    ParseError

    pub(all) struct ParseError {
    message : String
    span : Span
    } derive(Eq,
    Debug
    )

    Structured parse error with source position.
    impl Show for ParseError

    RegexError

    pub(all) enum RegexError {
    UnsupportedFeature(String)
    InvalidSyntax(String)
    } derive(Eq,
    Debug
    )

    Errors raised when parsing or compiling a regular expression pattern to GBNF.
    impl Show for RegexError

    Rule

    pub(all) struct Rule {
    name : String
    expr : Expr
    span : Span
    } derive(Eq,
    Debug
    )

    A single named GBNF production rule (name ::= expr).

    Rule::to_gbnf

    fn Rule::to_gbnf(self : Rule) -> String

    Format a single rule into canonical GBNF syntax (name ::= expr).

    SchemaError

    pub(all) enum SchemaError {
    InvalidJson(String)
    UnsupportedSchema(String)
    InvalidRef(String)
    CompileFailure(CompileError)
    } derive(Eq,
    Debug
    )

    Error produced while compiling a JSON Schema into GBNF.
    impl Show for SchemaError

    Span

    pub(all) struct Span {
    line : Int
    col : Int
    offset : Int
    } derive(Eq,
    Debug
    )

    Source location (1-based line and column, 0-based char index).

    ValidationCode

    pub(all) enum ValidationCode {
    EmptyGrammar
    MissingRoot
    DuplicateRule
    UndefinedRule
    EmptyCharClass
    InvalidCharRange
    UnreachableRule
    LeftRecursion
    EmptyCycle
    } derive(Eq,
    Debug
    )

    Structured diagnostic code for static validation issues.

    ValidationIssue

    pub(all) struct ValidationIssue {
    severity : ValidationSeverity
    code : ValidationCode
    rule_name : String
    message : String
    } derive(Eq,
    Debug
    )

    Single validation diagnostic with rule context and message.

    ValidationReport

    pub(all) struct ValidationReport {
    issues : Array[ValidationIssue]
    } derive(Eq,
    Debug
    )

    Aggregated static validation report.

    ValidationReport::errors

    Return only error-level issues.

    ValidationReport::is_valid

    fn ValidationReport::is_valid(self : ValidationReport) -> Bool

    Return true iff the report contains no Error-level issues.

    ValidationReport::warnings

    Return only warning-level issues.

    ValidationSeverity

    pub(all) enum ValidationSeverity {
    Error
    Warning
    } derive(Eq,
    Debug
    )

    Severity level for static grammar diagnostics.

    all_unicode_ranges

    fn all_unicode_ranges() -> Array[CharRange]

    Return the full set of valid Unicode scalar value intervals.

    compile

    fn compile(src : String) -> Result[CompiledGrammar, CompileError]

    Parse, validate, and compile GBNF source text in one call.

    compile_json_schema

    fn compile_json_schema(schema_str : String) -> Result[CompiledGrammar, SchemaError]

    Compile a JSON Schema directly into a ready-to-run CompiledGrammar.

    complement_ranges

    fn complement_ranges(ranges : Array[CharRange]) -> Array[CharRange]

    Compute the complement of ranges within valid Unicode scalar values.

    json_schema_to_gbnf

    fn json_schema_to_gbnf(schema_str : String) -> Result[String, SchemaError]

    Compile a JSON Schema document string into canonical GBNF grammar text.

    normalize_ranges

    fn normalize_ranges(ranges : Array[CharRange]) -> Array[CharRange]

    Sort and merge overlapping or adjacent character ranges into canonical form.

    parse

    fn parse(src : String) -> Result[Grammar, ParseError]

    Parse a GBNF source string into a structured Grammar AST.

    ranges_contains

    fn ranges_contains(ranges : Array[CharRange], cp : Int) -> Bool

    Binary search check whether cp lies inside a normalized range list.

    ranges_intersect

    fn ranges_intersect(a : Array[CharRange], b : Array[CharRange]) -> Array[CharRange]

    Compute the normalized intersection of two normalized range arrays.

    ranges_union

    fn ranges_union(a : Array[CharRange], b : Array[CharRange]) -> Array[CharRange]

    Compute the normalized union of two range arrays.

    regex_to_expr

    fn regex_to_expr(pattern : String, json_string? : Bool) -> Result[Expr, RegexError]

    Compile an ECMA-262 / JSON Schema regular expression pattern into a GBNF Expr.

    Patterns are unanchored by default (matching anywhere in the string) unless ^ or $ anchors are specified. When json_string is true, the returned Expr matches the unquoted RFC 8259 JSON-string-encoded body (without outer " quotes or trailing whitespace), suitable for wrapping in "\"" (...) "\"".

    regex_to_gbnf

    fn regex_to_gbnf(pattern : String, rule_name? : String, json_string? : Bool) -> Result[String, RegexError]

    Compile an ECMA-262 / JSON Schema regular expression pattern into a self-contained single-rule GBNF grammar string (rule_name ::= ...).

    Validates rule_name as a legal GBNF identifier ([a-zA-Z_][a-zA-Z0-9_-]*). When json_string is true, emits the unquoted RFC 8259 JSON-string body.

    resolve_char_class

    fn resolve_char_class(ranges : Array[CharRange], negated : Bool) -> Array[CharRange]

    Resolve a raw (ranges, negated) character class into positive normalized intervals.