Coverage Report

Created: 2025-11-28 06:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/common/json-schema-to-grammar.cpp
Line
Count
Source
1
#include "json-schema-to-grammar.h"
2
#include "common.h"
3
4
#include <nlohmann/json.hpp>
5
6
#include <algorithm>
7
#include <map>
8
#include <regex>
9
#include <sstream>
10
#include <string>
11
#include <unordered_map>
12
#include <unordered_set>
13
#include <vector>
14
15
using json = nlohmann::ordered_json;
16
17
84.5k
static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
18
84.5k
    auto has_max = max_items != std::numeric_limits<int>::max();
19
20
84.5k
    if (max_items == 0) {
21
975
        return "";
22
975
    }
23
83.5k
    if (min_items == 0 && max_items == 1) {
24
13.4k
        return item_rule + "?";
25
13.4k
    }
26
27
70.1k
    if (separator_rule.empty()) {
28
67.2k
        if (min_items == 1 && !has_max) {
29
1.58k
            return item_rule + "+";
30
65.6k
        } else if (min_items == 0 && !has_max) {
31
3.80k
            return item_rule + "*";
32
61.8k
        } else {
33
61.8k
            return item_rule + "{" + std::to_string(min_items) + "," + (has_max ? std::to_string(max_items) : "") + "}";
34
61.8k
        }
35
67.2k
    }
36
37
2.90k
    auto result = item_rule + " " + build_repetition("(" + separator_rule + " " + item_rule + ")", min_items == 0 ? 0 : min_items - 1, has_max ? max_items - 1 : max_items);
38
2.90k
    if (min_items == 0) {
39
2.74k
        result = "(" + result + ")?";
40
2.74k
    }
41
2.90k
    return result;
42
70.1k
}
43
44
0
static void _build_min_max_int(int64_t min_value, int64_t max_value, std::stringstream & out, int decimals_left = 16, bool top_level = true) {
45
0
    auto has_min = min_value != std::numeric_limits<int64_t>::min();
46
0
    auto has_max = max_value != std::numeric_limits<int64_t>::max();
47
48
0
    auto digit_range = [&](char from, char to) {
49
0
        out << "[";
50
0
        if (from == to) {
51
0
            out << from;
52
0
        } else {
53
0
            out << from << "-" << to;
54
0
        }
55
0
        out << "]";
56
0
    };
57
0
    auto more_digits = [&](int min_digits, int max_digits) {
58
0
        out << "[0-9]";
59
0
        if (min_digits == max_digits && min_digits == 1) {
60
0
            return;
61
0
        }
62
0
        out << "{";
63
0
        out << min_digits;
64
0
        if (max_digits != min_digits) {
65
0
            out << ",";
66
0
            if (max_digits != std::numeric_limits<int>::max()) {
67
0
                out << max_digits;
68
0
            }
69
0
        }
70
0
        out << "}";
71
0
    };
72
0
    std::function<void(const std::string_view &, const std::string_view &)> uniform_range =
73
0
        [&](const std::string_view & from, const std::string_view & to) {
74
0
            size_t i = 0;
75
0
            while (i < from.length() && i < to.length() && from[i] == to[i]) {
76
0
                i++;
77
0
            }
78
0
            if (i > 0) {
79
0
                out << "\"" << from.substr(0, i) << "\"";
80
0
            }
81
0
            if (i < from.length() && i < to.length()) {
82
0
                if (i > 0) {
83
0
                    out << " ";
84
0
                }
85
0
                auto sub_len = from.length() - i - 1;
86
0
                if (sub_len > 0) {
87
0
                    auto from_sub = from.substr(i + 1);
88
0
                    auto to_sub = to.substr(i + 1);
89
0
                    auto sub_zeros = string_repeat("0", sub_len);
90
0
                    auto sub_nines = string_repeat("9", sub_len);
91
92
0
                    auto to_reached = false;
93
0
                    out << "(";
94
0
                    if (from_sub == sub_zeros) {
95
0
                        digit_range(from[i], to[i] - 1);
96
0
                        out << " ";
97
0
                        more_digits(sub_len, sub_len);
98
0
                    } else {
99
0
                        out << "[" << from[i] << "] ";
100
0
                        out << "(";
101
0
                        uniform_range(from_sub, sub_nines);
102
0
                        out << ")";
103
0
                        if (from[i] < to[i] - 1) {
104
0
                            out << " | ";
105
0
                            if (to_sub == sub_nines) {
106
0
                                digit_range(from[i] + 1, to[i]);
107
0
                                to_reached = true;
108
0
                            } else {
109
0
                                digit_range(from[i] + 1, to[i] - 1);
110
0
                            }
111
0
                            out << " ";
112
0
                            more_digits(sub_len, sub_len);
113
0
                        }
114
0
                    }
115
0
                    if (!to_reached) {
116
0
                        out << " | ";
117
0
                        digit_range(to[i], to[i]);
118
0
                        out << " ";
119
0
                        uniform_range(sub_zeros, to_sub);
120
0
                    }
121
0
                    out << ")";
122
0
                } else {
123
0
                    out << "[" << from[i] << "-" << to[i] << "]";
124
0
                }
125
0
            }
126
0
        };
127
128
0
    if (has_min && has_max) {
129
0
        if (min_value < 0 && max_value < 0) {
130
0
            out << "\"-\" (";
131
0
            _build_min_max_int(-max_value, -min_value, out, decimals_left, /* top_level= */ true);
132
0
            out << ")";
133
0
            return;
134
0
        }
135
136
0
        if (min_value < 0) {
137
0
            out << "\"-\" (";
138
0
            _build_min_max_int(0, -min_value, out, decimals_left, /* top_level= */ true);
139
0
            out << ") | ";
140
0
            min_value = 0;
141
0
        }
142
143
0
        auto min_s = std::to_string(min_value);
144
0
        auto max_s = std::to_string(max_value);
145
0
        auto min_digits = min_s.length();
146
0
        auto max_digits = max_s.length();
147
148
0
        for (auto digits = min_digits; digits < max_digits; digits++) {
149
0
            uniform_range(min_s, string_repeat("9", digits));
150
0
            min_s = "1" + string_repeat("0", digits);
151
0
            out << " | ";
152
0
        }
153
0
        uniform_range(min_s, max_s);
154
0
        return;
155
0
    }
156
157
0
    auto less_decimals = std::max(decimals_left - 1, 1);
158
159
0
    if (has_min) {
160
0
        if (min_value < 0) {
161
0
            out << "\"-\" (";
162
0
            _build_min_max_int(std::numeric_limits<int64_t>::min(), -min_value, out, decimals_left, /* top_level= */ false);
163
0
            out << ") | [0] | [1-9] ";
164
0
            more_digits(0, decimals_left - 1);
165
0
        } else if (min_value == 0) {
166
0
            if (top_level) {
167
0
                out << "[0] | [1-9] ";
168
0
                more_digits(0, less_decimals);
169
0
            } else {
170
0
                more_digits(1, decimals_left);
171
0
            }
172
0
        } else if (min_value <= 9) {
173
0
            char c = '0' + min_value;
174
0
            auto range_start = top_level ? '1' : '0';
175
0
            if (c > range_start) {
176
0
                digit_range(range_start, c - 1);
177
0
                out << " ";
178
0
                more_digits(1, less_decimals);
179
0
                out << " | ";
180
0
            }
181
0
            digit_range(c, '9');
182
0
            out << " ";
183
0
            more_digits(0, less_decimals);
184
0
        } else {
185
0
            auto min_s = std::to_string(min_value);
186
0
            auto len = min_s.length();
187
0
            auto c = min_s[0];
188
189
0
            if (c > '1') {
190
0
                digit_range(top_level ? '1' : '0', c - 1);
191
0
                out << " ";
192
0
                more_digits(len, less_decimals);
193
0
                out << " | ";
194
0
            }
195
0
            digit_range(c, c);
196
0
            out << " (";
197
0
            _build_min_max_int(std::stoll(min_s.substr(1)), std::numeric_limits<int64_t>::max(), out, less_decimals, /* top_level= */ false);
198
0
            out << ")";
199
0
            if (c < '9') {
200
0
                out << " | ";
201
0
                digit_range(c + 1, '9');
202
0
                out << " ";
203
0
                more_digits(len - 1, less_decimals);
204
0
            }
205
0
        }
206
0
        return;
207
0
    }
208
209
0
    if (has_max) {
210
0
        if (max_value >= 0) {
211
0
            if (top_level) {
212
0
                out << "\"-\" [1-9] ";
213
0
                more_digits(0, less_decimals);
214
0
                out << " | ";
215
0
            }
216
0
            _build_min_max_int(0, max_value, out, decimals_left, /* top_level= */ true);
217
0
        } else {
218
0
            out << "\"-\" (";
219
0
            _build_min_max_int(-max_value, std::numeric_limits<int64_t>::max(), out, decimals_left, /* top_level= */ false);
220
0
            out << ")";
221
0
        }
222
0
        return;
223
0
    }
224
225
0
    throw std::runtime_error("At least one of min_value or max_value must be set");
226
0
}
227
228
const std::string SPACE_RULE = "| \" \" | \"\\n\"{1,2} [ \\t]{0,20}";
229
230
struct BuiltinRule {
231
    std::string content;
232
    std::vector<std::string> deps;
233
};
234
235
std::unordered_map<std::string, BuiltinRule> PRIMITIVE_RULES = {
236
    {"boolean", {"(\"true\" | \"false\") space", {}}},
237
    {"decimal-part", {"[0-9]{1,16}", {}}},
238
    {"integral-part", {"[0] | [1-9] [0-9]{0,15}", {}}},
239
    {"number", {"(\"-\"? integral-part) (\".\" decimal-part)? ([eE] [-+]? integral-part)? space", {"integral-part", "decimal-part"}}},
240
    {"integer", {"(\"-\"? integral-part) space", {"integral-part"}}},
241
    {"value", {"object | array | string | number | boolean | null", {"object", "array", "string", "number", "boolean", "null"}}},
242
    {"object", {"\"{\" space ( string \":\" space value (\",\" space string \":\" space value)* )? \"}\" space", {"string", "value"}}},
243
    {"array", {"\"[\" space ( value (\",\" space value)* )? \"]\" space", {"value"}}},
244
    {"uuid", {"\"\\\"\" [0-9a-fA-F]{8} \"-\" [0-9a-fA-F]{4} \"-\" [0-9a-fA-F]{4} \"-\" [0-9a-fA-F]{4} \"-\" [0-9a-fA-F]{12} \"\\\"\" space", {}}},
245
    {"char",   {"[^\"\\\\\\x7F\\x00-\\x1F] | [\\\\] ([\"\\\\bfnrt] | \"u\" [0-9a-fA-F]{4})", {}}},
246
    {"string", {"\"\\\"\" char* \"\\\"\" space", {"char"}}},
247
    {"null", {"\"null\" space", {}}},
248
};
249
250
std::unordered_map<std::string, BuiltinRule> STRING_FORMAT_RULES = {
251
    {"date", {"[0-9]{4} \"-\" ( \"0\" [1-9] | \"1\" [0-2] ) \"-\" ( \"0\" [1-9] | [1-2] [0-9] | \"3\" [0-1] )", {}}},
252
    {"time", {"([01] [0-9] | \"2\" [0-3]) \":\" [0-5] [0-9] \":\" [0-5] [0-9] ( \".\" [0-9]{3} )? ( \"Z\" | ( \"+\" | \"-\" ) ( [01] [0-9] | \"2\" [0-3] ) \":\" [0-5] [0-9] )", {}}},
253
    {"date-time", {"date \"T\" time", {"date", "time"}}},
254
    {"date-string", {"\"\\\"\" date \"\\\"\" space", {"date"}}},
255
    {"time-string", {"\"\\\"\" time \"\\\"\" space", {"time"}}},
256
    {"date-time-string", {"\"\\\"\" date-time \"\\\"\" space", {"date-time"}}}
257
};
258
259
320k
static bool is_reserved_name(const std::string & name) {
260
320k
    static const std::unordered_set<std::string> RESERVED_NAMES = [] {
261
1
        std::unordered_set<std::string> s;
262
1
        s.insert("root");
263
12
        for (const auto & p : PRIMITIVE_RULES) s.insert(p.first);
264
6
        for (const auto & p : STRING_FORMAT_RULES) s.insert(p.first);
265
1
        return s;
266
1
    }();
267
320k
    return RESERVED_NAMES.find(name) != RESERVED_NAMES.end();
268
320k
}
269
270
std::regex INVALID_RULE_CHARS_RE("[^a-zA-Z0-9-]+");
271
std::regex GRAMMAR_LITERAL_ESCAPE_RE("[\r\n\"]");
272
std::regex GRAMMAR_RANGE_LITERAL_ESCAPE_RE("[\r\n\"\\]\\-\\\\]");
273
std::unordered_map<char, std::string> GRAMMAR_LITERAL_ESCAPES = {
274
    {'\r', "\\r"}, {'\n', "\\n"}, {'"', "\\\""}, {'-', "\\-"}, {']', "\\]"}
275
};
276
277
std::unordered_set<char> NON_LITERAL_SET = {'|', '.', '(', ')', '[', ']', '{', '}', '*', '+', '?'};
278
std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
279
280
205k
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch  &)> & replacement) {
281
205k
    std::smatch match;
282
205k
    std::string result;
283
284
205k
    std::string::const_iterator searchStart(input.cbegin());
285
205k
    std::string::const_iterator searchEnd(input.cend());
286
287
605k
    while (std::regex_search(searchStart, searchEnd, match, regex)) {
288
399k
        result.append(searchStart, searchStart + match.position());
289
399k
        result.append(replacement(match));
290
399k
        searchStart = match.suffix().first;
291
399k
    }
292
293
205k
    result.append(searchStart, searchEnd);
294
295
205k
    return result;
296
205k
}
297
298
205k
static std::string format_literal(const std::string & literal) {
299
399k
    std::string escaped = replacePattern(literal, GRAMMAR_LITERAL_ESCAPE_RE, [&](const std::smatch & match) {
300
399k
        char c = match.str()[0];
301
399k
        return GRAMMAR_LITERAL_ESCAPES.at(c);
302
399k
    });
303
205k
    return "\"" + escaped + "\"";
304
205k
}
305
306
0
std::string gbnf_format_literal(const std::string & literal) { return format_literal(literal); }
307
308
class SchemaConverter {
309
private:
310
    friend std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options);
311
    std::function<json(const std::string &)> _fetch_json;
312
    bool _dotall;
313
    std::map<std::string, std::string> _rules;
314
    std::unordered_map<std::string, json> _refs;
315
    std::unordered_set<std::string> _refs_being_resolved;
316
    std::vector<std::string> _errors;
317
    std::vector<std::string> _warnings;
318
319
1.39M
    std::string _add_rule(const std::string & name, const std::string & rule) {
320
1.39M
        std::string esc_name = regex_replace(name, INVALID_RULE_CHARS_RE, "-");
321
1.39M
        if (_rules.find(esc_name) == _rules.end() || _rules[esc_name] == rule) {
322
1.34M
            _rules[esc_name] = rule;
323
1.34M
            return esc_name;
324
1.34M
        } else {
325
46.3k
            int i = 0;
326
163k
            while (_rules.find(esc_name + std::to_string(i)) != _rules.end() && _rules[esc_name + std::to_string(i)] != rule) {
327
116k
                i++;
328
116k
            }
329
46.3k
            std::string key = esc_name + std::to_string(i);
330
46.3k
            _rules[key] = rule;
331
46.3k
            return key;
332
46.3k
        }
333
1.39M
    }
334
335
5.13k
    std::string _generate_union_rule(const std::string & name, const std::vector<json> & alt_schemas) {
336
5.13k
        std::vector<std::string> rules;
337
52.0k
        for (size_t i = 0; i < alt_schemas.size(); i++) {
338
46.9k
            rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
339
46.9k
        }
340
5.13k
        return string_join(rules, " | ");
341
5.13k
    }
342
343
6.90k
    std::string _visit_pattern(const std::string & pattern, const std::string & name) {
344
6.90k
        if (!(pattern.front() == '^' && pattern.back() == '$')) {
345
1.84k
            _errors.push_back("Pattern must start with '^' and end with '$'");
346
1.84k
            return "";
347
1.84k
        }
348
5.06k
        std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
349
5.06k
        std::unordered_map<std::string, std::string> sub_rule_ids;
350
351
5.06k
        size_t i = 0;
352
5.06k
        size_t length = sub_pattern.length();
353
354
5.06k
        using literal_or_rule = std::pair<std::string, bool>;
355
827k
        auto to_rule = [&](const literal_or_rule & ls) {
356
827k
            auto is_literal = ls.second;
357
827k
            auto s = ls.first;
358
827k
            return is_literal ? "\"" + s + "\"" : s;
359
827k
        };
360
85.3k
        std::function<literal_or_rule()> transform = [&]() -> literal_or_rule {
361
85.3k
            size_t start = i;
362
85.3k
            std::vector<literal_or_rule> seq;
363
364
349k
            auto get_dot = [&]() {
365
349k
                std::string rule;
366
349k
                if (_dotall) {
367
0
                    rule = "[\\U00000000-\\U0010FFFF]";
368
349k
                } else {
369
349k
                    rule = "[^\\x0A\\x0D]";
370
349k
                }
371
349k
                return _add_rule("dot", rule);
372
349k
            };
373
374
            // Joins the sequence, merging consecutive literals together.
375
85.3k
            auto join_seq = [&]() {
376
83.8k
                std::vector<literal_or_rule> ret;
377
378
83.8k
                std::string literal;
379
674k
                auto flush_literal = [&]() {
380
674k
                    if (literal.empty()) {
381
553k
                        return false;
382
553k
                    }
383
121k
                    ret.emplace_back(literal, true);
384
121k
                    literal.clear();
385
121k
                    return true;
386
674k
                };
387
388
724k
                for (const auto & item : seq) {
389
724k
                    auto is_literal = item.second;
390
724k
                    if (is_literal) {
391
133k
                        literal += item.first;
392
590k
                    } else {
393
590k
                        flush_literal();
394
590k
                        ret.push_back(item);
395
590k
                    }
396
724k
                }
397
83.8k
                flush_literal();
398
399
83.8k
                std::vector<std::string> results;
400
711k
                for (const auto & item : ret) {
401
711k
                    results.push_back(to_rule(item));
402
711k
                }
403
83.8k
                return std::make_pair(string_join(results, " "), false);
404
83.8k
            };
405
406
929k
            while (i < length) {
407
847k
                char c = sub_pattern[i];
408
847k
                if (c == '.') {
409
349k
                    seq.emplace_back(get_dot(), false);
410
349k
                    i++;
411
498k
                } else if (c == '(') {
412
80.3k
                    i++;
413
80.3k
                    if (i < length) {
414
79.9k
                        if (sub_pattern[i] == '?') {
415
0
                            _warnings.push_back("Unsupported pattern syntax");
416
0
                        }
417
79.9k
                    }
418
80.3k
                    seq.emplace_back("(" + to_rule(transform()) + ")", false);
419
418k
                } else if (c == ')') {
420
2.30k
                    i++;
421
2.30k
                    if (start > 0 && sub_pattern[start - 1] != '(') {
422
0
                        _errors.push_back("Unbalanced parentheses");
423
0
                    }
424
2.30k
                    return join_seq();
425
416k
                } else if (c == '[') {
426
7.89k
                    std::string square_brackets = std::string(1, c);
427
7.89k
                    i++;
428
1.11M
                    while (i < length && sub_pattern[i] != ']') {
429
1.11M
                        if (sub_pattern[i] == '\\') {
430
13.3k
                            square_brackets += sub_pattern.substr(i, 2);
431
13.3k
                            i += 2;
432
1.09M
                        } else {
433
1.09M
                            square_brackets += sub_pattern[i];
434
1.09M
                            i++;
435
1.09M
                        }
436
1.11M
                    }
437
7.89k
                    if (i >= length) {
438
1.51k
                        _errors.push_back("Unbalanced square brackets");
439
1.51k
                    }
440
7.89k
                    square_brackets += ']';
441
7.89k
                    i++;
442
7.89k
                    seq.emplace_back(square_brackets, false);
443
408k
                } else if (c == '|') {
444
136k
                    seq.emplace_back("|", false);
445
136k
                    i++;
446
271k
                } else if (c == '*' || c == '+' || c == '?') {
447
30.5k
                    seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
448
30.5k
                    i++;
449
241k
                } else if (c == '{') {
450
79.9k
                    std::string curly_brackets = std::string(1, c);
451
79.9k
                    i++;
452
6.94M
                    while (i < length && sub_pattern[i] != '}') {
453
6.86M
                        curly_brackets += sub_pattern[i];
454
6.86M
                        i++;
455
6.86M
                    }
456
79.9k
                    if (i >= length) {
457
1.29k
                        _errors.push_back("Unbalanced curly brackets");
458
1.29k
                    }
459
79.9k
                    curly_brackets += '}';
460
79.9k
                    i++;
461
79.9k
                    auto nums = string_split(curly_brackets.substr(1, curly_brackets.length() - 2), ",");
462
79.9k
                    int min_times = 0;
463
79.9k
                    int max_times = std::numeric_limits<int>::max();
464
79.9k
                    try {
465
79.9k
                        if (nums.size() == 1) {
466
59.0k
                            min_times = max_times = std::stoi(nums[0]);
467
59.0k
                        } else if (nums.size() != 2) {
468
1.13k
                            _errors.push_back("Wrong number of values in curly brackets");
469
19.8k
                        } else {
470
19.8k
                            if (!nums[0].empty()) {
471
17.7k
                                min_times = std::stoi(nums[0]);
472
17.7k
                            }
473
19.8k
                            if (!nums[1].empty()) {
474
17.8k
                                max_times = std::stoi(nums[1]);
475
17.8k
                            }
476
19.8k
                        }
477
79.9k
                    } catch (const std::invalid_argument & e) {
478
1.29k
                        _errors.push_back("Invalid number in curly brackets");
479
1.29k
                        return std::make_pair("", false);
480
1.29k
                    }
481
78.6k
                    auto &last = seq.back();
482
78.6k
                    auto &sub = last.first;
483
78.6k
                    auto sub_is_literal = last.second;
484
485
78.6k
                    if (!sub_is_literal) {
486
59.3k
                        std::string & sub_id = sub_rule_ids[sub];
487
59.3k
                        if (sub_id.empty()) {
488
55.6k
                            sub_id = _add_rule(name + "-" + std::to_string(sub_rule_ids.size()), sub);
489
55.6k
                        }
490
59.3k
                        sub = sub_id;
491
59.3k
                    }
492
78.6k
                    seq.back().first = build_repetition(
493
78.6k
                        sub_is_literal ? "\"" + sub + "\"" : sub,
494
78.6k
                        min_times,
495
78.6k
                        max_times,
496
78.6k
                        ""
497
78.6k
                    );
498
78.6k
                    seq.back().second = false;
499
161k
                } else {
500
161k
                    std::string literal;
501
38.2M
                    auto is_non_literal = [&](char c) {
502
38.2M
                        return NON_LITERAL_SET.find(c) != NON_LITERAL_SET.end();
503
38.2M
                    };
504
19.3M
                    while (i < length) {
505
19.3M
                        if (sub_pattern[i] == '\\' && i < length - 1) {
506
39.4k
                            char next = sub_pattern[i + 1];
507
39.4k
                            if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
508
125
                                i++;
509
125
                                literal += sub_pattern[i];
510
125
                                i++;
511
39.3k
                            } else {
512
39.3k
                                literal += sub_pattern.substr(i, 2);
513
39.3k
                                i += 2;
514
39.3k
                            }
515
19.2M
                        } else if (sub_pattern[i] == '"') {
516
1.74k
                            literal += "\\\"";
517
1.74k
                            i++;
518
19.2M
                        } else if (!is_non_literal(sub_pattern[i]) &&
519
19.1M
                                (i == length - 1 || literal.empty() || sub_pattern[i + 1] == '.' || !is_non_literal(sub_pattern[i + 1]))) {
520
19.1M
                            literal += sub_pattern[i];
521
19.1M
                            i++;
522
19.1M
                        } else {
523
159k
                            break;
524
159k
                        }
525
19.3M
                    }
526
161k
                    if (!literal.empty()) {
527
161k
                        seq.emplace_back(literal, true);
528
161k
                    }
529
161k
                }
530
847k
            }
531
81.7k
            return join_seq();
532
85.3k
        };
533
5.06k
        return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\" space");
534
6.90k
    }
535
536
    /*
537
        Returns a rule that matches a JSON string that is none of the provided strings
538
539
        not_strings({"a"})
540
            -> ["] ( [a] char+ | [^"a] char* )? ["] space
541
        not_strings({"and", "also"})
542
            -> ["] ( [a] ([l] ([s] ([o] char+ | [^"o] char*) | [^"s] char*) | [n] ([d] char+ | [^"d] char*) | [^"ln] char*) | [^"a] char* )? ["] space
543
    */
544
0
    std::string _not_strings(const std::vector<std::string> & strings) {
545
546
0
        struct TrieNode {
547
0
            std::map<char, TrieNode> children;
548
0
            bool is_end_of_string;
549
550
0
            TrieNode() : is_end_of_string(false) {}
551
552
0
            void insert(const std::string & string) {
553
0
                auto node = this;
554
0
                for (char c : string) {
555
0
                    node = &node->children[c];
556
0
                }
557
0
                node->is_end_of_string = true;
558
0
            }
559
0
        };
560
561
0
        TrieNode trie;
562
0
        for (const auto & s : strings) {
563
0
            trie.insert(s);
564
0
        }
565
566
0
        std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
567
0
        std::ostringstream out;
568
0
        out << "[\"] ( ";
569
0
        std::function<void(const TrieNode &)> visit = [&](const TrieNode & node) {
570
0
            std::ostringstream rejects;
571
0
            auto first = true;
572
0
            for (const auto & kv : node.children) {
573
0
                rejects << kv.first;
574
0
                if (first) {
575
0
                    first = false;
576
0
                } else {
577
0
                    out << " | ";
578
0
                }
579
0
                out << "[" << kv.first << "]";
580
0
                if (!kv.second.children.empty()) {
581
0
                    out << " (";
582
0
                    visit(kv.second);
583
0
                    out << ")";
584
0
                } else if (kv.second.is_end_of_string) {
585
0
                    out << " " << char_rule << "+";
586
0
                }
587
0
            }
588
0
            if (!node.children.empty()) {
589
0
                if (!first) {
590
0
                    out << " | ";
591
0
                }
592
0
                out << "[^\"" << rejects.str() << "] " << char_rule << "*";
593
0
            }
594
0
        };
595
0
        visit(trie);
596
597
0
        out << " )";
598
0
        if (!trie.is_end_of_string) {
599
0
            out << "?";
600
0
        }
601
0
        out << " [\"] space";
602
0
        return out.str();
603
0
    }
604
605
8.35k
    std::string _resolve_ref(const std::string & ref) {
606
8.35k
        auto it = ref.find('#');
607
8.35k
        std::string ref_fragment = it != std::string::npos ? ref.substr(it + 1) : ref;
608
8.35k
        static const std::regex nonalphanumeric_regex(R"([^a-zA-Z0-9-]+)");
609
8.35k
        std::string ref_name = "ref" + std::regex_replace(ref_fragment, nonalphanumeric_regex, "-");
610
8.35k
        if (_rules.find(ref_name) == _rules.end() && _refs_being_resolved.find(ref) == _refs_being_resolved.end()) {
611
2.65k
            _refs_being_resolved.insert(ref);
612
2.65k
            json resolved = _refs[ref];
613
2.65k
            ref_name = visit(resolved, ref_name);
614
2.65k
            _refs_being_resolved.erase(ref);
615
2.65k
        }
616
8.35k
        return ref_name;
617
8.35k
    }
618
619
    std::string _build_object_rule(
620
        const std::vector<std::pair<std::string, json>> & properties,
621
        const std::unordered_set<std::string> & required,
622
        const std::string & name,
623
        const json & additional_properties)
624
4.39k
    {
625
4.39k
        std::vector<std::string> required_props;
626
4.39k
        std::vector<std::string> optional_props;
627
4.39k
        std::unordered_map<std::string, std::string> prop_kv_rule_names;
628
4.39k
        std::vector<std::string> prop_names;
629
197k
        for (const auto & kv : properties) {
630
197k
            const auto &prop_name = kv.first;
631
197k
            const auto &prop_schema = kv.second;
632
633
197k
            std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name);
634
197k
            prop_kv_rule_names[prop_name] = _add_rule(
635
197k
                name + (name.empty() ? "" : "-") + prop_name + "-kv",
636
197k
                format_literal(json(prop_name).dump()) + " space \":\" space " + prop_rule_name
637
197k
            );
638
197k
            if (required.find(prop_name) != required.end()) {
639
179k
                required_props.push_back(prop_name);
640
179k
            } else {
641
18.3k
                optional_props.push_back(prop_name);
642
18.3k
            }
643
197k
            prop_names.push_back(prop_name);
644
197k
        }
645
4.39k
        if ((additional_properties.is_boolean() && additional_properties.get<bool>()) || additional_properties.is_object()) {
646
372
            std::string sub_name = name + (name.empty() ? "" : "-") + "additional";
647
372
            std::string value_rule =
648
372
                additional_properties.is_object() ? visit(additional_properties, sub_name + "-value")
649
372
                : _add_primitive("value", PRIMITIVE_RULES.at("value"));
650
651
372
            auto key_rule =
652
372
                prop_names.empty() ? _add_primitive("string", PRIMITIVE_RULES.at("string"))
653
372
                : _add_rule(sub_name + "-k", _not_strings(prop_names));
654
372
            std::string kv_rule = _add_rule(sub_name + "-kv", key_rule + " \":\" space " + value_rule);
655
372
            prop_kv_rule_names["*"] = kv_rule;
656
372
            optional_props.push_back("*");
657
372
        }
658
659
4.39k
        std::string rule = "\"{\" space ";
660
183k
        for (size_t i = 0; i < required_props.size(); i++) {
661
179k
            if (i > 0) {
662
178k
                rule += " \",\" space ";
663
178k
            }
664
179k
            rule += prop_kv_rule_names[required_props[i]];
665
179k
        }
666
667
4.39k
        if (!optional_props.empty()) {
668
2.73k
            rule += " (";
669
2.73k
            if (!required_props.empty()) {
670
23
                rule += " \",\" space ( ";
671
23
            }
672
673
746k
            std::function<std::string(const std::vector<std::string> &, bool)> get_recursive_refs = [&](const std::vector<std::string> & ks, bool first_is_optional) {
674
746k
                std::string res;
675
746k
                if (ks.empty()) {
676
0
                    return res;
677
0
                }
678
746k
                std::string k = ks[0];
679
746k
                std::string kv_rule_name = prop_kv_rule_names[k];
680
746k
                std::string comma_ref = "( \",\" space " + kv_rule_name + " )";
681
746k
                if (first_is_optional) {
682
729k
                    res = comma_ref + (k == "*" ? "*" : "?");
683
729k
                } else {
684
17.5k
                    res = kv_rule_name + (k == "*" ? " " + comma_ref + "*" : "");
685
17.5k
                }
686
746k
                if (ks.size() > 1) {
687
729k
                    res += " " + _add_rule(
688
729k
                        name + (name.empty() ? "" : "-") + k + "-rest",
689
729k
                        get_recursive_refs(std::vector<std::string>(ks.begin() + 1, ks.end()), true)
690
729k
                    );
691
729k
                }
692
746k
                return res;
693
746k
            };
694
695
20.2k
            for (size_t i = 0; i < optional_props.size(); i++) {
696
17.5k
                if (i > 0) {
697
14.7k
                    rule += " | ";
698
14.7k
                }
699
17.5k
                rule += get_recursive_refs(std::vector<std::string>(optional_props.begin() + i, optional_props.end()), false);
700
17.5k
            }
701
2.73k
            if (!required_props.empty()) {
702
23
                rule += " )";
703
23
            }
704
2.73k
            rule += " )?";
705
2.73k
        }
706
707
4.39k
        rule += " \"}\" space";
708
709
4.39k
        return rule;
710
4.39k
    }
711
712
22.7k
    std::string _add_primitive(const std::string & name, const BuiltinRule & rule) {
713
22.7k
        auto n = _add_rule(name, rule.content);
714
32.3k
        for (const auto & dep : rule.deps) {
715
32.3k
            BuiltinRule dep_rule;
716
32.3k
            auto it = PRIMITIVE_RULES.find(dep);
717
32.3k
            if (it == PRIMITIVE_RULES.end()) {
718
0
                it = STRING_FORMAT_RULES.find(dep);
719
0
                if (it == STRING_FORMAT_RULES.end()) {
720
0
                    _errors.push_back("Rule " + dep + " not known");
721
0
                    continue;
722
0
                }
723
0
            }
724
32.3k
            if (_rules.find(dep) == _rules.end()) {
725
12.2k
                _add_primitive(dep, it->second);
726
12.2k
            }
727
32.3k
        }
728
22.7k
        return n;
729
22.7k
    }
730
731
public:
732
    SchemaConverter(
733
        const std::function<json(const std::string &)> & fetch_json,
734
        bool dotall)
735
7.28k
          : _fetch_json(fetch_json), _dotall(dotall)
736
7.28k
    {
737
7.28k
        _rules["space"] = SPACE_RULE;
738
7.28k
    }
739
740
10.5k
    void resolve_refs(json & schema, const std::string & url) {
741
        /*
742
        * Resolves all $ref fields in the given schema, fetching any remote schemas,
743
        * replacing each $ref with absolute reference URL and populates _refs with the
744
        * respective referenced (sub)schema dictionaries.
745
        */
746
3.59M
        std::function<void(json &)> visit_refs = [&](json & n) {
747
3.59M
            if (n.is_array()) {
748
3.53M
                for (auto & x : n) {
749
3.53M
                    visit_refs(x);
750
3.53M
                }
751
3.57M
            } else if (n.is_object()) {
752
54.5k
                if (n.contains("$ref")) {
753
15.7k
                    std::string ref = n["$ref"];
754
15.7k
                    if (_refs.find(ref) == _refs.end()) {
755
14.4k
                        json target;
756
14.4k
                        if (ref.find("https://") == 0) {
757
6.09k
                            std::string base_url = ref.substr(0, ref.find('#'));
758
6.09k
                            auto it = _refs.find(base_url);
759
6.09k
                            if (it != _refs.end()) {
760
2.79k
                                target = it->second;
761
3.30k
                            } else {
762
                                // Fetch the referenced schema and resolve its refs
763
3.30k
                                auto referenced = _fetch_json(ref);
764
3.30k
                                resolve_refs(referenced, base_url);
765
3.30k
                                _refs[base_url] = referenced;
766
3.30k
                            }
767
6.09k
                            if (ref.find('#') == std::string::npos || ref.substr(ref.find('#') + 1).empty()) {
768
3.03k
                                return;
769
3.03k
                            }
770
8.31k
                        } else if (ref.find("#/") == 0) {
771
2.76k
                            target = schema;
772
2.76k
                            n["$ref"] = url + ref;
773
2.76k
                            ref = url + ref;
774
5.54k
                        } else {
775
5.54k
                            _errors.push_back("Unsupported ref: " + ref);
776
5.54k
                            return;
777
5.54k
                        }
778
5.83k
                        std::string pointer = ref.substr(ref.find('#') + 1);
779
5.83k
                        std::vector<std::string> tokens = string_split(pointer, "/");
780
6.35k
                        for (size_t i = 1; i < tokens.size(); ++i) {
781
4.81k
                            std::string sel = tokens[i];
782
4.81k
                            if (target.is_object() && target.contains(sel)) {
783
524
                                target = target[sel];
784
4.28k
                            } else if (target.is_array()) {
785
571
                                size_t sel_index;
786
571
                                try {
787
571
                                    sel_index = std::stoul(sel);
788
571
                                } catch (const std::invalid_argument & e) {
789
566
                                    sel_index = target.size();
790
566
                                }
791
571
                                if (sel_index >= target.size()) {
792
567
                                    _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
793
567
                                    return;
794
567
                                }
795
2
                                target = target[sel_index];
796
3.71k
                            } else {
797
3.71k
                                _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
798
3.71k
                                return;
799
3.71k
                            }
800
4.81k
                        }
801
1.54k
                        _refs[ref] = target;
802
1.54k
                    }
803
38.7k
                } else {
804
49.5k
                    for (auto & kv : n.items()) {
805
49.5k
                        visit_refs(kv.value());
806
49.5k
                    }
807
38.7k
                }
808
54.5k
            }
809
3.59M
        };
810
811
10.5k
        visit_refs(schema);
812
10.5k
    }
813
814
8.08k
    std::string _generate_constant_rule(const json & value) {
815
8.08k
        return format_literal(value.dump());
816
8.08k
    }
817
818
320k
    std::string visit(const json & schema, const std::string & name) {
819
320k
        json schema_type = schema.contains("type") ? schema["type"] : json();
820
320k
        std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
821
320k
        std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
822
823
320k
        if (schema.contains("$ref")) {
824
8.35k
            return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
825
312k
        } else if (schema.contains("oneOf") || schema.contains("anyOf")) {
826
537
            std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
827
537
            return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
828
311k
        } else if (schema_type.is_array()) {
829
4.62k
            std::vector<json> schema_types;
830
32.8k
            for (const auto & t : schema_type) {
831
32.8k
                json schema_copy(schema);
832
32.8k
                schema_copy["type"] = t;
833
32.8k
                schema_types.push_back(schema_copy);
834
32.8k
            }
835
4.62k
            return _add_rule(rule_name, _generate_union_rule(name, schema_types));
836
306k
        } else if (schema.contains("const")) {
837
848
            return _add_rule(rule_name, _generate_constant_rule(schema["const"]) + " space");
838
306k
        } else if (schema.contains("enum")) {
839
4.45k
            std::vector<std::string> enum_values;
840
6.90k
            for (const auto & v : schema["enum"]) {
841
6.90k
                enum_values.push_back(_generate_constant_rule(v));
842
6.90k
            }
843
4.45k
            return _add_rule(rule_name, "(" + string_join(enum_values, " | ") + ") space");
844
301k
        } else if ((schema_type.is_null() || schema_type == "object")
845
279k
                && (schema.contains("properties") ||
846
276k
                    (schema.contains("additionalProperties") && schema["additionalProperties"] != true))) {
847
2.98k
            std::unordered_set<std::string> required;
848
2.98k
            if (schema.contains("required") && schema["required"].is_array()) {
849
36
                for (const auto & item : schema["required"]) {
850
36
                    if (item.is_string()) {
851
0
                        required.insert(item.get<std::string>());
852
0
                    }
853
36
                }
854
6
            }
855
2.98k
            std::vector<std::pair<std::string, json>> properties;
856
2.98k
            if (schema.contains("properties")) {
857
17.8k
                for (const auto & prop : schema["properties"].items()) {
858
17.8k
                    properties.emplace_back(prop.key(), prop.value());
859
17.8k
                }
860
2.41k
            }
861
2.98k
            return _add_rule(rule_name,
862
2.98k
                _build_object_rule(
863
2.98k
                    properties, required, name,
864
2.98k
                    schema.contains("additionalProperties") ? schema["additionalProperties"] : json()));
865
298k
        } else if ((schema_type.is_null() || schema_type == "object" || schema_type == "string") && schema.contains("allOf")) {
866
1.40k
            std::unordered_set<std::string> required;
867
1.40k
            std::vector<std::pair<std::string, json>> properties;
868
1.40k
            std::map<std::string, size_t> enum_values;
869
1.40k
            std::string hybrid_name = name;
870
25.9k
            std::function<void(const json &, bool)> add_component = [&](const json & comp_schema, bool is_required) {
871
25.9k
                if (comp_schema.contains("$ref")) {
872
4.84k
                    add_component(_refs[comp_schema["$ref"]], is_required);
873
21.0k
                } else if (comp_schema.contains("properties")) {
874
180k
                    for (const auto & prop : comp_schema["properties"].items()) {
875
180k
                        properties.emplace_back(prop.key(), prop.value());
876
180k
                        if (is_required) {
877
179k
                            required.insert(prop.key());
878
179k
                        }
879
180k
                    }
880
19.0k
                } else if (comp_schema.contains("enum")) {
881
336
                    for (const auto & v : comp_schema["enum"]) {
882
336
                        const auto rule = _generate_constant_rule(v);
883
336
                        if (enum_values.find(rule) == enum_values.end()) {
884
279
                            enum_values[rule] = 0;
885
279
                        }
886
336
                        enum_values[rule] += 1;
887
336
                    }
888
18.7k
                } else {
889
                  // todo warning
890
18.7k
                }
891
25.9k
            };
892
20.3k
            for (auto & t : schema["allOf"]) {
893
20.3k
                if (t.contains("anyOf")) {
894
1.07k
                    for (auto & tt : t["anyOf"]) {
895
1.07k
                        add_component(tt, false);
896
1.07k
                    }
897
19.9k
                } else {
898
19.9k
                    add_component(t, true);
899
19.9k
                }
900
20.3k
            }
901
1.40k
            if (!enum_values.empty()) {
902
50
                std::vector<std::string> enum_intersection;
903
279
                for (const auto & p : enum_values) {
904
279
                    if (p.second == schema["allOf"].size()) {
905
0
                        enum_intersection.push_back(p.first);
906
0
                    }
907
279
                }
908
50
                if (!enum_intersection.empty()) {
909
0
                    return _add_rule(rule_name, "(" + string_join(enum_intersection, " | ") + ") space");
910
0
                }
911
50
            }
912
1.40k
            return _add_rule(rule_name, _build_object_rule(properties, required, hybrid_name, json()));
913
297k
        } else if ((schema_type.is_null() || schema_type == "array") && (schema.contains("items") || schema.contains("prefixItems"))) {
914
4.40k
            json items = schema.contains("items") ? schema["items"] : schema["prefixItems"];
915
4.40k
            if (items.is_array()) {
916
1.12k
                std::string rule = "\"[\" space ";
917
63.1k
                for (size_t i = 0; i < items.size(); i++) {
918
62.0k
                    if (i > 0) {
919
60.9k
                        rule += " \",\" space ";
920
60.9k
                    }
921
62.0k
                    rule += visit(items[i], name + (name.empty() ? "" : "-") + "tuple-" + std::to_string(i));
922
62.0k
                }
923
1.12k
                rule += " \"]\" space";
924
1.12k
                return _add_rule(rule_name, rule);
925
3.28k
            } else {
926
3.28k
                std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
927
3.28k
                int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
928
3.28k
                json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
929
3.28k
                int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
930
931
3.28k
                return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
932
3.28k
            }
933
292k
        } else if ((schema_type.is_null() || schema_type == "string") && schema.contains("pattern")) {
934
6.90k
            return _visit_pattern(schema["pattern"], rule_name);
935
285k
        } else if ((schema_type.is_null() || schema_type == "string") && std::regex_match(schema_format, std::regex("^uuid[1-5]?$"))) {
936
1
            return _add_primitive(rule_name == "root" ? "root" : schema_format, PRIMITIVE_RULES.at("uuid"));
937
285k
        } else if ((schema_type.is_null() || schema_type == "string") && STRING_FORMAT_RULES.find(schema_format + "-string") != STRING_FORMAT_RULES.end()) {
938
0
            auto prim_name = schema_format + "-string";
939
0
            return _add_rule(rule_name, _add_primitive(prim_name, STRING_FORMAT_RULES.at(prim_name)));
940
285k
        } else if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
941
9
            std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
942
9
            int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
943
9
            int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
944
9
            return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
945
285k
        } else if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
946
0
            int64_t min_value = std::numeric_limits<int64_t>::min();
947
0
            int64_t max_value = std::numeric_limits<int64_t>::max();
948
0
            if (schema.contains("minimum")) {
949
0
                min_value = schema["minimum"].get<int64_t>();
950
0
            } else if (schema.contains("exclusiveMinimum")) {
951
0
                min_value = schema["exclusiveMinimum"].get<int64_t>() + 1;
952
0
            }
953
0
            if (schema.contains("maximum")) {
954
0
                max_value = schema["maximum"].get<int64_t>();
955
0
            } else if (schema.contains("exclusiveMaximum")) {
956
0
                max_value = schema["exclusiveMaximum"].get<int64_t>() - 1;
957
0
            }
958
0
            std::stringstream out;
959
0
            out << "(";
960
0
            _build_min_max_int(min_value, max_value, out);
961
0
            out << ") space";
962
0
            return _add_rule(rule_name, out.str());
963
285k
        } else if (schema.empty() || schema_type == "object") {
964
9.11k
            return _add_rule(rule_name, _add_primitive("object", PRIMITIVE_RULES.at("object")));
965
276k
        } else {
966
276k
            if (!schema_type.is_string() || PRIMITIVE_RULES.find(schema_type.get<std::string>()) == PRIMITIVE_RULES.end()) {
967
275k
                _errors.push_back("Unrecognized schema: " + schema.dump());
968
275k
                return "";
969
275k
            }
970
            // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
971
1.00k
            return _add_primitive(rule_name == "root" ? "root" : schema_type.get<std::string>(), PRIMITIVE_RULES.at(schema_type.get<std::string>()));
972
276k
        }
973
320k
    }
974
975
7.17k
    void check_errors() {
976
7.17k
        if (!_errors.empty()) {
977
5.99k
            throw std::runtime_error("JSON schema conversion failed:\n" + string_join(_errors, "\n"));
978
5.99k
        }
979
1.17k
        if (!_warnings.empty()) {
980
0
            fprintf(stderr, "WARNING: JSON schema conversion was incomplete: %s\n", string_join(_warnings, "; ").c_str());
981
0
        }
982
1.17k
    }
983
984
1.17k
    std::string format_grammar() {
985
1.17k
        std::stringstream ss;
986
13.9k
        for (const auto & kv : _rules) {
987
13.9k
            ss << kv.first << " ::= " << kv.second << std::endl;
988
13.9k
        }
989
1.17k
        return ss.str();
990
1.17k
    }
991
};
992
993
7.28k
std::string json_schema_to_grammar(const json & schema, bool force_gbnf) {
994
#ifdef LLAMA_USE_LLGUIDANCE
995
    if (!force_gbnf) {
996
        return "%llguidance {}\nstart: %json " + schema.dump();
997
    }
998
#else
999
7.28k
    (void)force_gbnf;
1000
7.28k
#endif // LLAMA_USE_LLGUIDANCE
1001
7.28k
    return build_grammar([&](const common_grammar_builder & callbacks) {
1002
7.28k
        auto copy = schema;
1003
7.28k
        callbacks.resolve_refs(copy);
1004
7.28k
        callbacks.add_schema("", copy);
1005
7.28k
    });
1006
7.28k
}
1007
1008
7.28k
std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options) {
1009
7.28k
    SchemaConverter converter([&](const std::string &) { return json(); }, options.dotall);
1010
7.28k
    common_grammar_builder builder {
1011
7.28k
        /* .add_rule = */ [&](const std::string & name, const std::string & rule) {
1012
0
            return converter._add_rule(name, rule);
1013
0
        },
1014
7.28k
        /* .add_schema = */ [&](const std::string & name, const nlohmann::ordered_json & schema) {
1015
7.26k
            return converter.visit(schema, name == "root" ? "" : name);
1016
7.26k
        },
1017
7.28k
        /* .resolve_refs = */ [&](nlohmann::ordered_json & schema) {
1018
7.28k
            converter.resolve_refs(schema, "");
1019
7.28k
        }
1020
7.28k
    };
1021
7.28k
    cb(builder);
1022
7.28k
    converter.check_errors();
1023
7.28k
    return converter.format_grammar();
1024
7.28k
}