1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
//! JSON Schema to GBNF, a port of llama.cpp's
//! `common/json-schema-to-grammar.cpp` (MIT; see
//! `docs/THIRD_PARTY_NOTICES.md`).
//!
//! This is what `response_format: {"type": "json_schema"}` needs. The
//! output is GBNF text that [`crate::grammar::parse`] accepts, so it feeds
//! the same pushdown machine as a hand-written grammar -- and every
//! conversion re-parses its own output before returning it, because a
//! grammar that does not parse is a bug in this module and should not
//! reach a caller as a string.
//!
//! # What is ported
//!
//! | Keyword | Behaviour |
//! |---|---|
//! | `type` | `object` `array` `string` `number` `integer` `boolean` `null`, and an array of them as a union |
//! | `properties`, `required` | in declaration order, required first |
//! | `additionalProperties` | `false`/absent closes the object, a schema types the tail, `true` opens it |
//! | `items`, `prefixItems` | a single schema is a list, an array is a fixed tuple |
//! | `minItems`, `maxItems` | beside a single-schema `items` |
//! | `minLength`, `maxLength` | beside an explicit `"type": "string"` |
//! | `enum`, `const` | literal alternatives, JSON-encoded |
//! | `oneOf`, `anyOf` | union of alternatives |
//! | `$ref`, `$defs`, `definitions` | same-document `#/` pointers, recursion included |
//! | `format` | `date`, `time`, `date-time`, `uuid`, `uuid1`..`uuid5` |
//! | `pattern` | an anchored ECMA-262 regex, via [`pattern`] |
//!
//! Annotations (`title`, `description`, `default`, `examples`, `$schema`,
//! `$id`, `$comment`, `deprecated`, `readOnly`, `writeOnly`) are ignored,
//! which is safe: they constrain nothing.
//!
//! # What is refused, by name
//!
//! Everything else, via [`SchemaError::UnsupportedKeyword`]. The rule is
//! in [`branch`]: a keyword the chosen branch did not act on is refused
//! unless the schema's declared `type` makes it vacuous -- `items` beside
//! `"type": "null"` says nothing about a null, so it is dropped, while
//! `pattern` beside `"type": "string"` is refused.
//!
//! The notable refusals are `allOf` (schema intersection), the numeric
//! bounds `minimum` / `maximum` / `exclusiveMinimum` / `exclusiveMaximum`
//! (llama.cpp builds a digit-by-digit range grammar for integers), `not` /
//! `if` / `then` / `else`, `patternProperties`, `propertyNames`,
//! `uniqueItems`, `minProperties` / `maxProperties`, `multipleOf`, the
//! `dependent*` family, and any `format` outside the six above.
//!
//! **This is stricter than llama.cpp on purpose.** Upstream's `visit` is a
//! chain of `if`s: a keyword no branch tested falls off the end and is
//! discarded, so `{"type": "string", "pattern": "^[a-z]+$"}` compiles to a
//! grammar for *any* string. That grammar accepts documents the caller
//! declared invalid, which is a wrong answer, not a missing feature. Per
//! `CLAUDE.md`, a refusal is coverage.
//!
//! # Where this differs from llama.cpp on schemas it accepts
//!
//! - `_not_strings` writes property-name bytes into a GBNF character class
//! unescaped, so upstream emits an unparseable grammar for a property
//! named `a-b`, `a]b` or `añb`. This port escapes the class and keys the
//! trie on `char` rather than `u8`.
//! - JSON Pointer escapes (`~1`, `~0`) in a `$ref` are decoded. Upstream
//! splits on `/` and cannot address such a member at all.
//! - Remote (`https://`) `$ref`s are refused rather than fetched.
//! - `pattern` compiles the subset of ECMA-262 that upstream compiles, but
//! refuses several inputs upstream mishandles rather than reproducing the
//! mishandling: a lookaround group (upstream warns, then silently drops
//! the group), an escape its own GBNF parser rejects (`\s`, `\b`, a
//! backreference, a dangling `\`), a stray `]` or `}` (upstream loops
//! forever), `*` with nothing before it (upstream reads past the end of a
//! vector), and a top-level `)` (upstream returns early, discarding the
//! rest of the pattern). `\d` / `\D` / `\w` / `\W` are translated to
//! their exact ECMA-262 classes, where upstream copies them through into
//! a grammar that does not parse. See [`pattern`].
//! - A top-level schema whose rule ends up named something other than
//! `root` is refused ([`SchemaError::RootDisplaced`]) instead of silently
//! producing a grammar that starts from a subschema; upstream reaches
//! this whenever a property is named `""`.
//!
//! # Property order
//!
//! The order of `properties` is part of the accepted language: required
//! members are emitted in declaration order. [`json_schema_to_grammar`]
//! parses the schema text with [`value::JsonValue`], which keeps document
//! order the way llama.cpp's `nlohmann::ordered_json` does.
//! [`json_schema_to_grammar_value`] can only carry the order its
//! `serde_json::Value` already has, and this workspace builds `serde_json`
//! without `preserve_order`, so that entry point orders properties
//! lexicographically. Prefer the text entry point when the caller has the
//! raw JSON.
pub use SchemaError;
pub use JsonValue;
use Converter;
/// Convert JSON Schema text to a GBNF grammar.
///
/// This is the entry point to prefer: it keeps `properties` in the order
/// the schema declares them.
/// Convert an already-parsed `serde_json::Value` schema.
///
/// See the module docs on property order: without `serde_json`'s
/// `preserve_order` feature a `Value` has already lost the schema's
/// declaration order, and required members will be required in
/// lexicographic order instead.
/// Several schemas and some hand-written rules, compiled into ONE
/// grammar.
///
/// `common_grammar_builder` upstream (`common/chat.cpp` builds every
/// tool-call grammar through it): each schema becomes a NAMED rule
/// instead of `root`, and the caller writes the rule that composes them.
/// One converter, so the shared `space` / `char` / `string` builtins are
/// emitted once and a rule name used by two schemas is disambiguated
/// rather than silently redefined.
///
/// The single-schema [`json_schema_to_grammar`] is not a special case of
/// this and is left alone: it must produce `root` itself, and refuses if
/// a subschema takes that name first.
///
/// ```
/// use ferrox_models::grammar::json_schema::GrammarBuilder;
/// let mut b = GrammarBuilder::new();
/// let args = b
/// .add_schema_value("get-weather-args", &serde_json::json!({
/// "type": "object",
/// "properties": {"city": {"type": "string"}},
/// "required": ["city"],
/// }))
/// .unwrap();
/// b.add_rule("root", &format!("\"call \" {args}"));
/// let grammar = b.finish().unwrap();
/// assert!(grammar.contains("root ::="));
/// ```
/// `json_schema_to_grammar` / `build_grammar`: resolve refs, visit the
/// root, emit, and check the result against this repo's own GBNF parser.