Coverage Report

Created: 2026-01-11 07:13

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
150k
static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
18
150k
    auto has_max = max_items != std::numeric_limits<int>::max();
19
20
150k
    if (max_items == 0) {
21
1.52k
        return "";
22
1.52k
    }
23
148k
    if (min_items == 0 && max_items == 1) {
24
18.9k
        return item_rule + "?";
25
18.9k
    }
26
27
129k
    if (separator_rule.empty()) {
28
127k
        if (min_items == 1 && !has_max) {
29
27.0k
            return item_rule + "+";
30
100k
        } else if (min_items == 0 && !has_max) {
31
11.1k
            return item_rule + "*";
32
89.1k
        } else {
33
89.1k
            return item_rule + "{" + std::to_string(min_items) + "," + (has_max ? std::to_string(max_items) : "") + "}";
34
89.1k
        }
35
127k
    }
36
37
2.62k
    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.62k
    if (min_items == 0) {
39
2.33k
        result = "(" + result + ")?";
40
2.33k
    }
41
2.62k
    return result;
42
129k
}
43
44
5.51k
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
5.51k
    auto has_min = min_value != std::numeric_limits<int64_t>::min();
46
5.51k
    auto has_max = max_value != std::numeric_limits<int64_t>::max();
47
48
23.8k
    auto digit_range = [&](char from, char to) {
49
23.8k
        out << "[";
50
23.8k
        if (from == to) {
51
10.7k
            out << from;
52
13.0k
        } else {
53
13.0k
            out << from << "-" << to;
54
13.0k
        }
55
23.8k
        out << "]";
56
23.8k
    };
57
14.4k
    auto more_digits = [&](int min_digits, int max_digits) {
58
14.4k
        out << "[0-9]";
59
14.4k
        if (min_digits == max_digits && min_digits == 1) {
60
1.52k
            return;
61
1.52k
        }
62
12.9k
        out << "{";
63
12.9k
        out << min_digits;
64
12.9k
        if (max_digits != min_digits) {
65
7.73k
            out << ",";
66
7.73k
            if (max_digits != std::numeric_limits<int>::max()) {
67
7.73k
                out << max_digits;
68
7.73k
            }
69
7.73k
        }
70
12.9k
        out << "}";
71
12.9k
    };
72
5.51k
    std::function<void(const std::string_view &, const std::string_view &)> uniform_range =
73
8.31k
        [&](const std::string_view & from, const std::string_view & to) {
74
8.31k
            size_t i = 0;
75
8.59k
            while (i < from.length() && i < to.length() && from[i] == to[i]) {
76
278
                i++;
77
278
            }
78
8.31k
            if (i > 0) {
79
163
                out << "\"" << from.substr(0, i) << "\"";
80
163
            }
81
8.31k
            if (i < from.length() && i < to.length()) {
82
8.09k
                if (i > 0) {
83
126
                    out << " ";
84
126
                }
85
8.09k
                auto sub_len = from.length() - i - 1;
86
8.09k
                if (sub_len > 0) {
87
6.46k
                    auto from_sub = from.substr(i + 1);
88
6.46k
                    auto to_sub = to.substr(i + 1);
89
6.46k
                    auto sub_zeros = string_repeat("0", sub_len);
90
6.46k
                    auto sub_nines = string_repeat("9", sub_len);
91
92
6.46k
                    auto to_reached = false;
93
6.46k
                    out << "(";
94
6.46k
                    if (from_sub == sub_zeros) {
95
5.51k
                        digit_range(from[i], to[i] - 1);
96
5.51k
                        out << " ";
97
5.51k
                        more_digits(sub_len, sub_len);
98
5.51k
                    } else {
99
948
                        out << "[" << from[i] << "] ";
100
948
                        out << "(";
101
948
                        uniform_range(from_sub, sub_nines);
102
948
                        out << ")";
103
948
                        if (from[i] < to[i] - 1) {
104
632
                            out << " | ";
105
632
                            if (to_sub == sub_nines) {
106
587
                                digit_range(from[i] + 1, to[i]);
107
587
                                to_reached = true;
108
587
                            } else {
109
45
                                digit_range(from[i] + 1, to[i] - 1);
110
45
                            }
111
632
                            out << " ";
112
632
                            more_digits(sub_len, sub_len);
113
632
                        }
114
948
                    }
115
6.46k
                    if (!to_reached) {
116
5.87k
                        out << " | ";
117
5.87k
                        digit_range(to[i], to[i]);
118
5.87k
                        out << " ";
119
5.87k
                        uniform_range(sub_zeros, to_sub);
120
5.87k
                    }
121
6.46k
                    out << ")";
122
6.46k
                } else {
123
1.63k
                    out << "[" << from[i] << "-" << to[i] << "]";
124
1.63k
                }
125
8.09k
            }
126
8.31k
        };
127
128
5.51k
    if (has_min && has_max) {
129
475
        if (min_value < 0 && max_value < 0) {
130
7
            out << "\"-\" (";
131
7
            _build_min_max_int(-max_value, -min_value, out, decimals_left, /* top_level= */ true);
132
7
            out << ")";
133
7
            return;
134
7
        }
135
136
468
        if (min_value < 0) {
137
9
            out << "\"-\" (";
138
9
            _build_min_max_int(0, -min_value, out, decimals_left, /* top_level= */ true);
139
9
            out << ") | ";
140
9
            min_value = 0;
141
9
        }
142
143
468
        auto min_s = std::to_string(min_value);
144
468
        auto max_s = std::to_string(max_value);
145
468
        auto min_digits = min_s.length();
146
468
        auto max_digits = max_s.length();
147
148
1.49k
        for (auto digits = min_digits; digits < max_digits; digits++) {
149
1.02k
            uniform_range(min_s, string_repeat("9", digits));
150
1.02k
            min_s = "1" + string_repeat("0", digits);
151
1.02k
            out << " | ";
152
1.02k
        }
153
468
        uniform_range(min_s, max_s);
154
468
        return;
155
475
    }
156
157
5.03k
    auto less_decimals = std::max(decimals_left - 1, 1);
158
159
5.03k
    if (has_min) {
160
4.62k
        if (min_value < 0) {
161
26
            out << "\"-\" (";
162
26
            _build_min_max_int(std::numeric_limits<int64_t>::min(), -min_value, out, decimals_left, /* top_level= */ false);
163
26
            out << ") | [0] | [1-9] ";
164
26
            more_digits(0, decimals_left - 1);
165
4.59k
        } else if (min_value == 0) {
166
265
            if (top_level) {
167
6
                out << "[0] | [1-9] ";
168
6
                more_digits(0, less_decimals);
169
259
            } else {
170
259
                more_digits(1, decimals_left);
171
259
            }
172
4.33k
        } else if (min_value <= 9) {
173
306
            char c = '0' + min_value;
174
306
            auto range_start = top_level ? '1' : '0';
175
306
            if (c > range_start) {
176
295
                digit_range(range_start, c - 1);
177
295
                out << " ";
178
295
                more_digits(1, less_decimals);
179
295
                out << " | ";
180
295
            }
181
306
            digit_range(c, '9');
182
306
            out << " ";
183
306
            more_digits(0, less_decimals);
184
4.02k
        } else {
185
4.02k
            auto min_s = std::to_string(min_value);
186
4.02k
            auto len = min_s.length();
187
4.02k
            auto c = min_s[0];
188
189
4.02k
            if (c > '1') {
190
3.51k
                digit_range(top_level ? '1' : '0', c - 1);
191
3.51k
                out << " ";
192
3.51k
                more_digits(len, less_decimals);
193
3.51k
                out << " | ";
194
3.51k
            }
195
4.02k
            digit_range(c, c);
196
4.02k
            out << " (";
197
4.02k
            _build_min_max_int(std::stoll(min_s.substr(1)), std::numeric_limits<int64_t>::max(), out, less_decimals, /* top_level= */ false);
198
4.02k
            out << ")";
199
4.02k
            if (c < '9') {
200
3.65k
                out << " | ";
201
3.65k
                digit_range(c + 1, '9');
202
3.65k
                out << " ";
203
3.65k
                more_digits(len - 1, less_decimals);
204
3.65k
            }
205
4.02k
        }
206
4.62k
        return;
207
4.62k
    }
208
209
410
    if (has_max) {
210
408
        if (max_value >= 0) {
211
242
            if (top_level) {
212
216
                out << "\"-\" [1-9] ";
213
216
                more_digits(0, less_decimals);
214
216
                out << " | ";
215
216
            }
216
242
            _build_min_max_int(0, max_value, out, decimals_left, /* top_level= */ true);
217
242
        } else {
218
166
            out << "\"-\" (";
219
166
            _build_min_max_int(-max_value, std::numeric_limits<int64_t>::max(), out, decimals_left, /* top_level= */ false);
220
166
            out << ")";
221
166
        }
222
408
        return;
223
408
    }
224
225
2
    throw std::runtime_error("At least one of min_value or max_value must be set");
226
410
}
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
438k
static bool is_reserved_name(const std::string & name) {
260
438k
    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
438k
    return RESERVED_NAMES.find(name) != RESERVED_NAMES.end();
268
438k
}
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
302k
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch  &)> & replacement) {
281
302k
    std::smatch match;
282
302k
    std::string result;
283
284
302k
    std::string::const_iterator searchStart(input.cbegin());
285
302k
    std::string::const_iterator searchEnd(input.cend());
286
287
924k
    while (std::regex_search(searchStart, searchEnd, match, regex)) {
288
622k
        result.append(searchStart, searchStart + match.position());
289
622k
        result.append(replacement(match));
290
622k
        searchStart = match.suffix().first;
291
622k
    }
292
293
302k
    result.append(searchStart, searchEnd);
294
295
302k
    return result;
296
302k
}
297
298
302k
static std::string format_literal(const std::string & literal) {
299
622k
    std::string escaped = replacePattern(literal, GRAMMAR_LITERAL_ESCAPE_RE, [&](const std::smatch & match) {
300
622k
        char c = match.str()[0];
301
622k
        return GRAMMAR_LITERAL_ESCAPES.at(c);
302
622k
    });
303
302k
    return "\"" + escaped + "\"";
304
302k
}
305
306
0
std::string gbnf_format_literal(const std::string & literal) { return format_literal(literal); }
307
308
class common_schema_converter {
309
private:
310
    friend class common_schema_info;
311
    friend std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options);
312
    std::function<json(const std::string &)> _fetch_json;
313
    bool _dotall;
314
    std::map<std::string, std::string> _rules;
315
    std::unordered_map<std::string, json> _refs;
316
    std::unordered_set<std::string> _refs_being_resolved;
317
    std::vector<std::string> _errors;
318
    std::vector<std::string> _warnings;
319
320
1.70M
    std::string _add_rule(const std::string & name, const std::string & rule) {
321
1.70M
        std::string esc_name = regex_replace(name, INVALID_RULE_CHARS_RE, "-");
322
1.70M
        if (_rules.find(esc_name) == _rules.end() || _rules[esc_name] == rule) {
323
1.64M
            _rules[esc_name] = rule;
324
1.64M
            return esc_name;
325
1.64M
        } else {
326
63.3k
            int i = 0;
327
181k
            while (_rules.find(esc_name + std::to_string(i)) != _rules.end() && _rules[esc_name + std::to_string(i)] != rule) {
328
117k
                i++;
329
117k
            }
330
63.3k
            std::string key = esc_name + std::to_string(i);
331
63.3k
            _rules[key] = rule;
332
63.3k
            return key;
333
63.3k
        }
334
1.70M
    }
335
336
5.72k
    std::string _generate_union_rule(const std::string & name, const std::vector<json> & alt_schemas) {
337
5.72k
        std::vector<std::string> rules;
338
87.5k
        for (size_t i = 0; i < alt_schemas.size(); i++) {
339
81.7k
            rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
340
81.7k
        }
341
5.72k
        return string_join(rules, " | ");
342
5.72k
    }
343
344
3.98k
    std::string _visit_pattern(const std::string & pattern, const std::string & name) {
345
3.98k
        if (!(pattern.front() == '^' && pattern.back() == '$')) {
346
775
            _errors.push_back("Pattern must start with '^' and end with '$'");
347
775
            return "";
348
775
        }
349
3.21k
        std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
350
3.21k
        std::unordered_map<std::string, std::string> sub_rule_ids;
351
352
3.21k
        size_t i = 0;
353
3.21k
        size_t length = sub_pattern.length();
354
355
3.21k
        using literal_or_rule = std::pair<std::string, bool>;
356
1.12M
        auto to_rule = [&](const literal_or_rule & ls) {
357
1.12M
            auto is_literal = ls.second;
358
1.12M
            auto s = ls.first;
359
1.12M
            return is_literal ? "\"" + s + "\"" : s;
360
1.12M
        };
361
81.7k
        std::function<literal_or_rule()> transform = [&]() -> literal_or_rule {
362
81.7k
            size_t start = i;
363
81.7k
            std::vector<literal_or_rule> seq;
364
365
599k
            auto get_dot = [&]() {
366
599k
                std::string rule;
367
599k
                if (_dotall) {
368
0
                    rule = "[\\U00000000-\\U0010FFFF]";
369
599k
                } else {
370
599k
                    rule = "[^\\x0A\\x0D]";
371
599k
                }
372
599k
                return _add_rule("dot", rule);
373
599k
            };
374
375
            // Joins the sequence, merging consecutive literals together.
376
81.7k
            auto join_seq = [&]() {
377
80.7k
                std::vector<literal_or_rule> ret;
378
379
80.7k
                std::string literal;
380
952k
                auto flush_literal = [&]() {
381
952k
                    if (literal.empty()) {
382
795k
                        return false;
383
795k
                    }
384
157k
                    ret.emplace_back(literal, true);
385
157k
                    literal.clear();
386
157k
                    return true;
387
952k
                };
388
389
1.04M
                for (const auto & item : seq) {
390
1.04M
                    auto is_literal = item.second;
391
1.04M
                    if (is_literal) {
392
172k
                        literal += item.first;
393
872k
                    } else {
394
872k
                        flush_literal();
395
872k
                        ret.push_back(item);
396
872k
                    }
397
1.04M
                }
398
80.7k
                flush_literal();
399
400
80.7k
                std::vector<std::string> results;
401
1.02M
                for (const auto & item : ret) {
402
1.02M
                    results.push_back(to_rule(item));
403
1.02M
                }
404
80.7k
                return std::make_pair(string_join(results, " "), false);
405
80.7k
            };
406
407
1.29M
            while (i < length) {
408
1.22M
                char c = sub_pattern[i];
409
1.22M
                if (c == '.') {
410
599k
                    seq.emplace_back(get_dot(), false);
411
599k
                    i++;
412
625k
                } else if (c == '(') {
413
78.5k
                    i++;
414
78.5k
                    if (i < length) {
415
78.3k
                        if (sub_pattern[i] == '?') {
416
0
                            _warnings.push_back("Unsupported pattern syntax");
417
0
                        }
418
78.3k
                    }
419
78.5k
                    seq.emplace_back("(" + to_rule(transform()) + ")", false);
420
546k
                } else if (c == ')') {
421
9.01k
                    i++;
422
9.01k
                    if (start > 0 && sub_pattern[start - 1] != '(') {
423
0
                        _errors.push_back("Unbalanced parentheses");
424
0
                    }
425
9.01k
                    return join_seq();
426
537k
                } else if (c == '[') {
427
11.7k
                    std::string square_brackets = std::string(1, c);
428
11.7k
                    i++;
429
3.01M
                    while (i < length && sub_pattern[i] != ']') {
430
3.00M
                        if (sub_pattern[i] == '\\') {
431
40.2k
                            square_brackets += sub_pattern.substr(i, 2);
432
40.2k
                            i += 2;
433
2.96M
                        } else {
434
2.96M
                            square_brackets += sub_pattern[i];
435
2.96M
                            i++;
436
2.96M
                        }
437
3.00M
                    }
438
11.7k
                    if (i >= length) {
439
964
                        _errors.push_back("Unbalanced square brackets");
440
964
                    }
441
11.7k
                    square_brackets += ']';
442
11.7k
                    i++;
443
11.7k
                    seq.emplace_back(square_brackets, false);
444
525k
                } else if (c == '|') {
445
74.0k
                    seq.emplace_back("|", false);
446
74.0k
                    i++;
447
451k
                } else if (c == '*' || c == '+' || c == '?') {
448
15.2k
                    seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
449
15.2k
                    i++;
450
436k
                } else if (c == '{') {
451
145k
                    std::string curly_brackets = std::string(1, c);
452
145k
                    i++;
453
7.42M
                    while (i < length && sub_pattern[i] != '}') {
454
7.27M
                        curly_brackets += sub_pattern[i];
455
7.27M
                        i++;
456
7.27M
                    }
457
145k
                    if (i >= length) {
458
814
                        _errors.push_back("Unbalanced curly brackets");
459
814
                    }
460
145k
                    curly_brackets += '}';
461
145k
                    i++;
462
145k
                    auto nums = string_split(curly_brackets.substr(1, curly_brackets.length() - 2), ",");
463
145k
                    int min_times = 0;
464
145k
                    int max_times = std::numeric_limits<int>::max();
465
145k
                    try {
466
145k
                        if (nums.size() == 1) {
467
9.45k
                            min_times = max_times = std::stoi(nums[0]);
468
136k
                        } else if (nums.size() != 2) {
469
6.24k
                            _errors.push_back("Wrong number of values in curly brackets");
470
129k
                        } else {
471
129k
                            if (!nums[0].empty()) {
472
87.6k
                                min_times = std::stoi(nums[0]);
473
87.6k
                            }
474
129k
                            if (!nums[1].empty()) {
475
94.8k
                                max_times = std::stoi(nums[1]);
476
94.8k
                            }
477
129k
                        }
478
145k
                    } catch (const std::invalid_argument & e) {
479
702
                        _errors.push_back("Invalid number in curly brackets");
480
702
                        return std::make_pair("", false);
481
702
                    }
482
144k
                    auto &last = seq.back();
483
144k
                    auto &sub = last.first;
484
144k
                    auto sub_is_literal = last.second;
485
486
144k
                    if (!sub_is_literal) {
487
32.8k
                        std::string & sub_id = sub_rule_ids[sub];
488
32.8k
                        if (sub_id.empty()) {
489
6.06k
                            sub_id = _add_rule(name + "-" + std::to_string(sub_rule_ids.size()), sub);
490
6.06k
                        }
491
32.8k
                        sub = sub_id;
492
32.8k
                    }
493
144k
                    seq.back().first = build_repetition(
494
144k
                        sub_is_literal ? "\"" + sub + "\"" : sub,
495
144k
                        min_times,
496
144k
                        max_times,
497
144k
                        ""
498
144k
                    );
499
144k
                    seq.back().second = false;
500
291k
                } else {
501
291k
                    std::string literal;
502
53.6M
                    auto is_non_literal = [&](char c) {
503
53.6M
                        return NON_LITERAL_SET.find(c) != NON_LITERAL_SET.end();
504
53.6M
                    };
505
27.1M
                    while (i < length) {
506
27.1M
                        if (sub_pattern[i] == '\\' && i < length - 1) {
507
52.8k
                            char next = sub_pattern[i + 1];
508
52.8k
                            if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
509
1.00k
                                i++;
510
1.00k
                                literal += sub_pattern[i];
511
1.00k
                                i++;
512
51.8k
                            } else {
513
51.8k
                                literal += sub_pattern.substr(i, 2);
514
51.8k
                                i += 2;
515
51.8k
                            }
516
27.0M
                        } else if (sub_pattern[i] == '"') {
517
1.76k
                            literal += "\\\"";
518
1.76k
                            i++;
519
27.0M
                        } else if (!is_non_literal(sub_pattern[i]) &&
520
26.8M
                                (i == length - 1 || literal.empty() || sub_pattern[i + 1] == '.' || !is_non_literal(sub_pattern[i + 1]))) {
521
26.8M
                            literal += sub_pattern[i];
522
26.8M
                            i++;
523
26.8M
                        } else {
524
290k
                            break;
525
290k
                        }
526
27.1M
                    }
527
291k
                    if (!literal.empty()) {
528
291k
                        seq.emplace_back(literal, true);
529
291k
                    }
530
291k
                }
531
1.22M
            }
532
71.9k
            return join_seq();
533
81.7k
        };
534
3.21k
        return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\" space");
535
3.98k
    }
536
537
    /*
538
        Returns a rule that matches a JSON string that is none of the provided strings
539
540
        not_strings({"a"})
541
            -> ["] ( [a] char+ | [^"a] char* )? ["] space
542
        not_strings({"and", "also"})
543
            -> ["] ( [a] ([l] ([s] ([o] char+ | [^"o] char*) | [^"s] char*) | [n] ([d] char+ | [^"d] char*) | [^"ln] char*) | [^"a] char* )? ["] space
544
    */
545
0
    std::string _not_strings(const std::vector<std::string> & strings) {
546
547
0
        struct TrieNode {
548
0
            std::map<char, TrieNode> children;
549
0
            bool is_end_of_string;
550
551
0
            TrieNode() : is_end_of_string(false) {}
552
553
0
            void insert(const std::string & string) {
554
0
                auto node = this;
555
0
                for (char c : string) {
556
0
                    node = &node->children[c];
557
0
                }
558
0
                node->is_end_of_string = true;
559
0
            }
560
0
        };
561
562
0
        TrieNode trie;
563
0
        for (const auto & s : strings) {
564
0
            trie.insert(s);
565
0
        }
566
567
0
        std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
568
0
        std::ostringstream out;
569
0
        out << "[\"] ( ";
570
0
        std::function<void(const TrieNode &)> visit = [&](const TrieNode & node) {
571
0
            std::ostringstream rejects;
572
0
            auto first = true;
573
0
            for (const auto & kv : node.children) {
574
0
                rejects << kv.first;
575
0
                if (first) {
576
0
                    first = false;
577
0
                } else {
578
0
                    out << " | ";
579
0
                }
580
0
                out << "[" << kv.first << "]";
581
0
                if (!kv.second.children.empty()) {
582
0
                    out << " (";
583
0
                    visit(kv.second);
584
0
                    out << ")";
585
0
                } else if (kv.second.is_end_of_string) {
586
0
                    out << " " << char_rule << "+";
587
0
                }
588
0
            }
589
0
            if (!node.children.empty()) {
590
0
                if (!first) {
591
0
                    out << " | ";
592
0
                }
593
0
                out << "[^\"" << rejects.str() << "] " << char_rule << "*";
594
0
            }
595
0
        };
596
0
        visit(trie);
597
598
0
        out << " )";
599
0
        if (!trie.is_end_of_string) {
600
0
            out << "?";
601
0
        }
602
0
        out << " [\"] space";
603
0
        return out.str();
604
0
    }
605
606
9.11k
    std::string _resolve_ref(const std::string & ref) {
607
9.11k
        auto it = ref.find('#');
608
9.11k
        std::string ref_fragment = it != std::string::npos ? ref.substr(it + 1) : ref;
609
9.11k
        static const std::regex nonalphanumeric_regex(R"([^a-zA-Z0-9-]+)");
610
9.11k
        std::string ref_name = "ref" + std::regex_replace(ref_fragment, nonalphanumeric_regex, "-");
611
9.11k
        if (_rules.find(ref_name) == _rules.end() && _refs_being_resolved.find(ref) == _refs_being_resolved.end()) {
612
3.48k
            _refs_being_resolved.insert(ref);
613
3.48k
            json resolved = _refs[ref];
614
3.48k
            ref_name = visit(resolved, ref_name);
615
3.48k
            _refs_being_resolved.erase(ref);
616
3.48k
        }
617
9.11k
        return ref_name;
618
9.11k
    }
619
620
    std::string _build_object_rule(
621
        const std::vector<std::pair<std::string, json>> & properties,
622
        const std::unordered_set<std::string> & required,
623
        const std::string & name,
624
        const json & additional_properties)
625
5.50k
    {
626
5.50k
        std::vector<std::string> required_props;
627
5.50k
        std::vector<std::string> optional_props;
628
5.50k
        std::unordered_map<std::string, std::string> prop_kv_rule_names;
629
5.50k
        std::vector<std::string> prop_names;
630
288k
        for (const auto & kv : properties) {
631
288k
            const auto &prop_name = kv.first;
632
288k
            const auto &prop_schema = kv.second;
633
634
288k
            std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name);
635
288k
            prop_kv_rule_names[prop_name] = _add_rule(
636
288k
                name + (name.empty() ? "" : "-") + prop_name + "-kv",
637
288k
                format_literal(json(prop_name).dump()) + " space \":\" space " + prop_rule_name
638
288k
            );
639
288k
            if (required.find(prop_name) != required.end()) {
640
263k
                required_props.push_back(prop_name);
641
263k
            } else {
642
25.5k
                optional_props.push_back(prop_name);
643
25.5k
            }
644
288k
            prop_names.push_back(prop_name);
645
288k
        }
646
5.50k
        if ((additional_properties.is_boolean() && additional_properties.get<bool>()) || additional_properties.is_object()) {
647
471
            std::string sub_name = name + (name.empty() ? "" : "-") + "additional";
648
471
            std::string value_rule =
649
471
                additional_properties.is_object() ? visit(additional_properties, sub_name + "-value")
650
471
                : _add_primitive("value", PRIMITIVE_RULES.at("value"));
651
652
471
            auto key_rule =
653
471
                prop_names.empty() ? _add_primitive("string", PRIMITIVE_RULES.at("string"))
654
471
                : _add_rule(sub_name + "-k", _not_strings(prop_names));
655
471
            std::string kv_rule = _add_rule(sub_name + "-kv", key_rule + " \":\" space " + value_rule);
656
471
            prop_kv_rule_names["*"] = kv_rule;
657
471
            optional_props.push_back("*");
658
471
        }
659
660
5.50k
        std::string rule = "\"{\" space ";
661
268k
        for (size_t i = 0; i < required_props.size(); i++) {
662
263k
            if (i > 0) {
663
262k
                rule += " \",\" space ";
664
262k
            }
665
263k
            rule += prop_kv_rule_names[required_props[i]];
666
263k
        }
667
668
5.50k
        if (!optional_props.empty()) {
669
3.55k
            rule += " (";
670
3.55k
            if (!required_props.empty()) {
671
24
                rule += " \",\" space ( ";
672
24
            }
673
674
771k
            std::function<std::string(const std::vector<std::string> &, bool)> get_recursive_refs = [&](const std::vector<std::string> & ks, bool first_is_optional) {
675
771k
                std::string res;
676
771k
                if (ks.empty()) {
677
0
                    return res;
678
0
                }
679
771k
                std::string k = ks[0];
680
771k
                std::string kv_rule_name = prop_kv_rule_names[k];
681
771k
                std::string comma_ref = "( \",\" space " + kv_rule_name + " )";
682
771k
                if (first_is_optional) {
683
749k
                    res = comma_ref + (k == "*" ? "*" : "?");
684
749k
                } else {
685
21.2k
                    res = kv_rule_name + (k == "*" ? " " + comma_ref + "*" : "");
686
21.2k
                }
687
771k
                if (ks.size() > 1) {
688
749k
                    res += " " + _add_rule(
689
749k
                        name + (name.empty() ? "" : "-") + k + "-rest",
690
749k
                        get_recursive_refs(std::vector<std::string>(ks.begin() + 1, ks.end()), true)
691
749k
                    );
692
749k
                }
693
771k
                return res;
694
771k
            };
695
696
24.7k
            for (size_t i = 0; i < optional_props.size(); i++) {
697
21.2k
                if (i > 0) {
698
17.6k
                    rule += " | ";
699
17.6k
                }
700
21.2k
                rule += get_recursive_refs(std::vector<std::string>(optional_props.begin() + i, optional_props.end()), false);
701
21.2k
            }
702
3.55k
            if (!required_props.empty()) {
703
24
                rule += " )";
704
24
            }
705
3.55k
            rule += " )?";
706
3.55k
        }
707
708
5.50k
        rule += " \"}\" space";
709
710
5.50k
        return rule;
711
5.50k
    }
712
713
21.9k
    std::string _add_primitive(const std::string & name, const BuiltinRule & rule) {
714
21.9k
        auto n = _add_rule(name, rule.content);
715
31.3k
        for (const auto & dep : rule.deps) {
716
31.3k
            BuiltinRule dep_rule;
717
31.3k
            auto it = PRIMITIVE_RULES.find(dep);
718
31.3k
            if (it == PRIMITIVE_RULES.end()) {
719
0
                it = STRING_FORMAT_RULES.find(dep);
720
0
                if (it == STRING_FORMAT_RULES.end()) {
721
0
                    _errors.push_back("Rule " + dep + " not known");
722
0
                    continue;
723
0
                }
724
0
            }
725
31.3k
            if (_rules.find(dep) == _rules.end()) {
726
11.5k
                _add_primitive(dep, it->second);
727
11.5k
            }
728
31.3k
        }
729
21.9k
        return n;
730
21.9k
    }
731
732
public:
733
    common_schema_converter(
734
        const std::function<json(const std::string &)> & fetch_json,
735
        bool dotall)
736
7.18k
          : _fetch_json(fetch_json), _dotall(dotall)
737
7.18k
    {
738
7.18k
        _rules["space"] = SPACE_RULE;
739
7.18k
    }
740
741
10.7k
    void resolve_refs(json & schema, const std::string & url) {
742
        /*
743
        * Resolves all $ref fields in the given schema, fetching any remote schemas,
744
        * replacing each $ref with absolute reference URL and populates _refs with the
745
        * respective referenced (sub)schema dictionaries.
746
        */
747
3.53M
        std::function<void(json &)> visit_refs = [&](json & n) {
748
3.53M
            if (n.is_array()) {
749
3.46M
                for (auto & x : n) {
750
3.46M
                    visit_refs(x);
751
3.46M
                }
752
3.52M
            } else if (n.is_object()) {
753
58.3k
                if (n.contains("$ref")) {
754
20.0k
                    std::string ref = n["$ref"];
755
20.0k
                    if (_refs.find(ref) == _refs.end()) {
756
18.0k
                        json target;
757
18.0k
                        if (ref.find("https://") == 0) {
758
6.62k
                            std::string base_url = ref.substr(0, ref.find('#'));
759
6.62k
                            auto it = _refs.find(base_url);
760
6.62k
                            if (it != _refs.end()) {
761
3.07k
                                target = it->second;
762
3.55k
                            } else {
763
                                // Fetch the referenced schema and resolve its refs
764
3.55k
                                auto referenced = _fetch_json(ref);
765
3.55k
                                resolve_refs(referenced, base_url);
766
3.55k
                                _refs[base_url] = referenced;
767
3.55k
                            }
768
6.62k
                            if (ref.find('#') == std::string::npos || ref.substr(ref.find('#') + 1).empty()) {
769
3.49k
                                return;
770
3.49k
                            }
771
11.4k
                        } else if (ref.find("#/") == 0) {
772
3.59k
                            target = schema;
773
3.59k
                            n["$ref"] = url + ref;
774
3.59k
                            ref = url + ref;
775
7.84k
                        } else {
776
7.84k
                            _errors.push_back("Unsupported ref: " + ref);
777
7.84k
                            return;
778
7.84k
                        }
779
6.73k
                        std::string pointer = ref.substr(ref.find('#') + 1);
780
6.73k
                        std::vector<std::string> tokens = string_split(pointer, "/");
781
7.84k
                        for (size_t i = 1; i < tokens.size(); ++i) {
782
6.37k
                            std::string sel = tokens[i];
783
6.37k
                            if (target.is_object() && target.contains(sel)) {
784
738
                                target = target[sel];
785
5.64k
                            } else if (target.is_array()) {
786
1.35k
                                size_t sel_index;
787
1.35k
                                try {
788
1.35k
                                    sel_index = std::stoul(sel);
789
1.35k
                                } catch (const std::invalid_argument & e) {
790
911
                                    sel_index = target.size();
791
911
                                }
792
1.35k
                                if (sel_index >= target.size()) {
793
969
                                    _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
794
969
                                    return;
795
969
                                }
796
377
                                target = target[sel_index];
797
4.28k
                            } else {
798
4.28k
                                _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
799
4.28k
                                return;
800
4.28k
                            }
801
6.37k
                        }
802
1.46k
                        _refs[ref] = target;
803
1.46k
                    }
804
38.2k
                } else {
805
58.5k
                    for (auto & kv : n.items()) {
806
58.5k
                        visit_refs(kv.value());
807
58.5k
                    }
808
38.2k
                }
809
58.3k
            }
810
3.53M
        };
811
812
10.7k
        visit_refs(schema);
813
10.7k
    }
814
815
14.0k
    std::string _generate_constant_rule(const json & value) {
816
14.0k
        return format_literal(value.dump());
817
14.0k
    }
818
819
438k
    std::string visit(const json & schema, const std::string & name) {
820
438k
        json schema_type = schema.contains("type") ? schema["type"] : json();
821
438k
        std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
822
438k
        std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
823
824
438k
        if (schema.contains("$ref")) {
825
9.11k
            return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
826
429k
        } else if (schema.contains("oneOf") || schema.contains("anyOf")) {
827
618
            std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
828
618
            return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
829
429k
        } else if (schema_type.is_array()) {
830
5.14k
            std::vector<json> schema_types;
831
51.4k
            for (const auto & t : schema_type) {
832
51.4k
                json schema_copy(schema);
833
51.4k
                schema_copy["type"] = t;
834
51.4k
                schema_types.push_back(schema_copy);
835
51.4k
            }
836
5.14k
            return _add_rule(rule_name, _generate_union_rule(name, schema_types));
837
424k
        } else if (schema.contains("const")) {
838
236
            return _add_rule(rule_name, _generate_constant_rule(schema["const"]) + " space");
839
423k
        } else if (schema.contains("enum")) {
840
4.65k
            std::vector<std::string> enum_values;
841
7.40k
            for (const auto & v : schema["enum"]) {
842
7.40k
                enum_values.push_back(_generate_constant_rule(v));
843
7.40k
            }
844
4.65k
            return _add_rule(rule_name, "(" + string_join(enum_values, " | ") + ") space");
845
419k
        } else if ((schema_type.is_null() || schema_type == "object")
846
379k
                && (schema.contains("properties") ||
847
376k
                    (schema.contains("additionalProperties") && schema["additionalProperties"] != true))) {
848
3.89k
            std::unordered_set<std::string> required;
849
3.89k
            if (schema.contains("required") && schema["required"].is_array()) {
850
8.34k
                for (const auto & item : schema["required"]) {
851
8.34k
                    if (item.is_string()) {
852
4.84k
                        required.insert(item.get<std::string>());
853
4.84k
                    }
854
8.34k
                }
855
112
            }
856
3.89k
            std::vector<std::pair<std::string, json>> properties;
857
3.89k
            if (schema.contains("properties")) {
858
25.1k
                for (const auto & prop : schema["properties"].items()) {
859
25.1k
                    properties.emplace_back(prop.key(), prop.value());
860
25.1k
                }
861
3.17k
            }
862
3.89k
            return _add_rule(rule_name,
863
3.89k
                _build_object_rule(
864
3.89k
                    properties, required, name,
865
3.89k
                    schema.contains("additionalProperties") ? schema["additionalProperties"] : json()));
866
415k
        } else if ((schema_type.is_null() || schema_type == "object" || schema_type == "string") && schema.contains("allOf")) {
867
1.61k
            std::unordered_set<std::string> required;
868
1.61k
            std::vector<std::pair<std::string, json>> properties;
869
1.61k
            std::map<std::string, size_t> enum_values;
870
1.61k
            std::string hybrid_name = name;
871
41.9k
            std::function<void(const json &, bool)> add_component = [&](const json & comp_schema, bool is_required) {
872
41.9k
                if (comp_schema.contains("$ref")) {
873
7.00k
                    add_component(_refs[comp_schema["$ref"]], is_required);
874
34.9k
                } else if (comp_schema.contains("properties")) {
875
264k
                    for (const auto & prop : comp_schema["properties"].items()) {
876
264k
                        properties.emplace_back(prop.key(), prop.value());
877
264k
                        if (is_required) {
878
263k
                            required.insert(prop.key());
879
263k
                        }
880
264k
                    }
881
32.9k
                } else if (comp_schema.contains("enum")) {
882
6.45k
                    for (const auto & v : comp_schema["enum"]) {
883
6.45k
                        const auto rule = _generate_constant_rule(v);
884
6.45k
                        if (enum_values.find(rule) == enum_values.end()) {
885
1.94k
                            enum_values[rule] = 0;
886
1.94k
                        }
887
6.45k
                        enum_values[rule] += 1;
888
6.45k
                    }
889
28.1k
                } else {
890
                  // todo warning
891
28.1k
                }
892
41.9k
            };
893
34.1k
            for (auto & t : schema["allOf"]) {
894
34.1k
                if (t.contains("anyOf")) {
895
994
                    for (auto & tt : t["anyOf"]) {
896
994
                        add_component(tt, false);
897
994
                    }
898
33.9k
                } else {
899
33.9k
                    add_component(t, true);
900
33.9k
                }
901
34.1k
            }
902
1.61k
            if (!enum_values.empty()) {
903
203
                std::vector<std::string> enum_intersection;
904
1.94k
                for (const auto & p : enum_values) {
905
1.94k
                    if (p.second == schema["allOf"].size()) {
906
8
                        enum_intersection.push_back(p.first);
907
8
                    }
908
1.94k
                }
909
203
                if (!enum_intersection.empty()) {
910
7
                    return _add_rule(rule_name, "(" + string_join(enum_intersection, " | ") + ") space");
911
7
                }
912
203
            }
913
1.60k
            return _add_rule(rule_name, _build_object_rule(properties, required, hybrid_name, json()));
914
413k
        } else if ((schema_type.is_null() || schema_type == "array") && (schema.contains("items") || schema.contains("prefixItems"))) {
915
4.08k
            json items = schema.contains("items") ? schema["items"] : schema["prefixItems"];
916
4.08k
            if (items.is_array()) {
917
860
                std::string rule = "\"[\" space ";
918
55.0k
                for (size_t i = 0; i < items.size(); i++) {
919
54.1k
                    if (i > 0) {
920
53.3k
                        rule += " \",\" space ";
921
53.3k
                    }
922
54.1k
                    rule += visit(items[i], name + (name.empty() ? "" : "-") + "tuple-" + std::to_string(i));
923
54.1k
                }
924
860
                rule += " \"]\" space";
925
860
                return _add_rule(rule_name, rule);
926
3.22k
            } else {
927
3.22k
                std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
928
3.22k
                int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
929
3.22k
                json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
930
3.22k
                int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
931
932
3.22k
                return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
933
3.22k
            }
934
409k
        } else if ((schema_type.is_null() || schema_type == "string") && schema.contains("pattern")) {
935
3.98k
            return _visit_pattern(schema["pattern"], rule_name);
936
405k
        } else if ((schema_type.is_null() || schema_type == "string") && std::regex_match(schema_format, std::regex("^uuid[1-5]?$"))) {
937
1
            return _add_primitive(rule_name == "root" ? "root" : schema_format, PRIMITIVE_RULES.at("uuid"));
938
405k
        } else if ((schema_type.is_null() || schema_type == "string") && STRING_FORMAT_RULES.find(schema_format + "-string") != STRING_FORMAT_RULES.end()) {
939
0
            auto prim_name = schema_format + "-string";
940
0
            return _add_rule(rule_name, _add_primitive(prim_name, STRING_FORMAT_RULES.at(prim_name)));
941
405k
        } else if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
942
13
            std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
943
13
            int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
944
13
            int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
945
13
            return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
946
405k
        } else if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
947
1.03k
            int64_t min_value = std::numeric_limits<int64_t>::min();
948
1.03k
            int64_t max_value = std::numeric_limits<int64_t>::max();
949
1.03k
            if (schema.contains("minimum")) {
950
646
                min_value = schema["minimum"].get<int64_t>();
951
646
            } else if (schema.contains("exclusiveMinimum")) {
952
4
                min_value = schema["exclusiveMinimum"].get<int64_t>() + 1;
953
4
            }
954
1.03k
            if (schema.contains("maximum")) {
955
597
                max_value = schema["maximum"].get<int64_t>();
956
597
            } else if (schema.contains("exclusiveMaximum")) {
957
2
                max_value = schema["exclusiveMaximum"].get<int64_t>() - 1;
958
2
            }
959
1.03k
            std::stringstream out;
960
1.03k
            out << "(";
961
1.03k
            _build_min_max_int(min_value, max_value, out);
962
1.03k
            out << ") space";
963
1.03k
            return _add_rule(rule_name, out.str());
964
404k
        } else if (schema.empty() || schema_type == "object") {
965
8.43k
            return _add_rule(rule_name, _add_primitive("object", PRIMITIVE_RULES.at("object")));
966
396k
        } else {
967
396k
            if (!schema_type.is_string() || PRIMITIVE_RULES.find(schema_type.get<std::string>()) == PRIMITIVE_RULES.end()) {
968
394k
                _errors.push_back("Unrecognized schema: " + schema.dump());
969
394k
                return "";
970
394k
            }
971
            // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
972
1.47k
            return _add_primitive(rule_name == "root" ? "root" : schema_type.get<std::string>(), PRIMITIVE_RULES.at(schema_type.get<std::string>()));
973
396k
        }
974
438k
    }
975
976
7.05k
    void check_errors() {
977
7.05k
        if (!_errors.empty()) {
978
5.80k
            throw std::invalid_argument("JSON schema conversion failed:\n" + string_join(_errors, "\n"));
979
5.80k
        }
980
1.24k
        if (!_warnings.empty()) {
981
0
            fprintf(stderr, "WARNING: JSON schema conversion was incomplete: %s\n", string_join(_warnings, "; ").c_str());
982
0
        }
983
1.24k
    }
984
985
1.24k
    std::string format_grammar() {
986
1.24k
        std::stringstream ss;
987
15.2k
        for (const auto & kv : _rules) {
988
15.2k
            ss << kv.first << " ::= " << kv.second << std::endl;
989
15.2k
        }
990
1.24k
        return ss.str();
991
1.24k
    }
992
};
993
994
// common_schema_info implementation (pimpl)
995
996
common_schema_info::common_schema_info()
997
0
    : impl_(std::make_unique<common_schema_converter>(
998
0
        [](const std::string &) { return json(); },
999
0
        false)) {}
1000
1001
0
common_schema_info::~common_schema_info() = default;
1002
1003
0
common_schema_info::common_schema_info(common_schema_info &&) noexcept = default;
1004
0
common_schema_info & common_schema_info::operator=(common_schema_info &&) noexcept = default;
1005
1006
0
void common_schema_info::resolve_refs(nlohmann::ordered_json & schema) {
1007
0
    impl_->resolve_refs(schema, "");
1008
0
}
1009
1010
// Determines if a JSON schema can resolve to a string type through any path.
1011
// Some models emit raw string values rather than JSON-encoded strings for string parameters.
1012
// If any branch of the schema (via oneOf, anyOf, $ref, etc.) permits a string, this returns
1013
// true, allowing callers to handle the value as a raw string for simplicity.
1014
0
bool common_schema_info::resolves_to_string(const nlohmann::ordered_json & schema) {
1015
0
    std::unordered_set<std::string> visited_refs;
1016
1017
0
    std::function<bool(const json &)> check = [&](const json & s) -> bool {
1018
0
        if (!s.is_object()) {
1019
0
            return false;
1020
0
        }
1021
1022
        // Handle $ref
1023
0
        if (s.contains("$ref")) {
1024
0
            const std::string & ref = s["$ref"];
1025
0
            if (visited_refs.find(ref) != visited_refs.end()) {
1026
                // Circular reference, assume not a string to be safe
1027
0
                return false;
1028
0
            }
1029
0
            visited_refs.insert(ref);
1030
0
            auto it = impl_->_refs.find(ref);
1031
0
            if (it != impl_->_refs.end()) {
1032
0
                return check(it->second);
1033
0
            }
1034
0
            return false;
1035
0
        }
1036
1037
        // Check type field
1038
0
        if (s.contains("type")) {
1039
0
            const json & schema_type = s["type"];
1040
0
            if (schema_type.is_string()) {
1041
0
                if (schema_type == "string") {
1042
0
                    return true;
1043
0
                }
1044
0
            } else if (schema_type.is_array()) {
1045
                // Type can be an array like ["string", "null"]
1046
0
                for (const auto & t : schema_type) {
1047
0
                    if (t == "string") {
1048
0
                        return true;
1049
0
                    }
1050
0
                }
1051
0
            }
1052
0
        }
1053
1054
        // Check oneOf/anyOf - if any alternative can be a string
1055
0
        if (s.contains("oneOf")) {
1056
0
            for (const auto & alt : s["oneOf"]) {
1057
0
                if (check(alt)) {
1058
0
                    return true;
1059
0
                }
1060
0
            }
1061
0
        }
1062
0
        if (s.contains("anyOf")) {
1063
0
            for (const auto & alt : s["anyOf"]) {
1064
0
                if (check(alt)) {
1065
0
                    return true;
1066
0
                }
1067
0
            }
1068
0
        }
1069
1070
        // Check allOf - all components must be compatible with string type
1071
0
        if (s.contains("allOf")) {
1072
0
            bool all_string = true;
1073
0
            for (const auto & component : s["allOf"]) {
1074
0
                if (!check(component)) {
1075
0
                    all_string = false;
1076
0
                    break;
1077
0
                }
1078
0
            }
1079
0
            if (all_string) {
1080
0
                return true;
1081
0
            }
1082
0
        }
1083
1084
        // Check const - if the constant value is a string
1085
0
        if (s.contains("const")) {
1086
0
            if (s["const"].is_string()) {
1087
0
                return true;
1088
0
            }
1089
0
        }
1090
1091
        // Check enum - if any enum value is a string
1092
0
        if (s.contains("enum")) {
1093
0
            for (const auto & val : s["enum"]) {
1094
0
                if (val.is_string()) {
1095
0
                    return true;
1096
0
                }
1097
0
            }
1098
0
        }
1099
1100
        // String-specific keywords imply string type
1101
0
        if (s.contains("pattern") || s.contains("minLength") || s.contains("maxLength")) {
1102
0
            return true;
1103
0
        }
1104
1105
        // Check format - many formats imply string
1106
0
        if (s.contains("format")) {
1107
0
            const std::string & fmt = s["format"];
1108
0
            if (fmt == "date" || fmt == "time" || fmt == "date-time" ||
1109
0
                fmt == "uri" || fmt == "email" || fmt == "hostname" ||
1110
0
                fmt == "ipv4" || fmt == "ipv6" || fmt == "uuid" ||
1111
0
                fmt.find("uuid") == 0) {
1112
0
                return true;
1113
0
            }
1114
0
        }
1115
1116
0
        return false;
1117
0
    };
1118
1119
0
    return check(schema);
1120
0
}
1121
1122
7.18k
std::string json_schema_to_grammar(const json & schema, bool force_gbnf) {
1123
#ifdef LLAMA_USE_LLGUIDANCE
1124
    if (!force_gbnf) {
1125
        return "%llguidance {}\nstart: %json " + schema.dump();
1126
    }
1127
#else
1128
7.18k
    (void)force_gbnf;
1129
7.18k
#endif // LLAMA_USE_LLGUIDANCE
1130
7.18k
    return build_grammar([&](const common_grammar_builder & callbacks) {
1131
7.18k
        auto copy = schema;
1132
7.18k
        callbacks.resolve_refs(copy);
1133
7.18k
        callbacks.add_schema("", copy);
1134
7.18k
    });
1135
7.18k
}
1136
1137
7.18k
std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options) {
1138
7.18k
    common_schema_converter converter([&](const std::string &) { return json(); }, options.dotall);
1139
7.18k
    common_grammar_builder builder {
1140
7.18k
        /* .add_rule = */ [&](const std::string & name, const std::string & rule) {
1141
0
            return converter._add_rule(name, rule);
1142
0
        },
1143
7.18k
        /* .add_schema = */ [&](const std::string & name, const nlohmann::ordered_json & schema) {
1144
7.17k
            return converter.visit(schema, name == "root" ? "" : name);
1145
7.17k
        },
1146
7.18k
        /* .resolve_refs = */ [&](nlohmann::ordered_json & schema) {
1147
7.18k
            converter.resolve_refs(schema, "");
1148
7.18k
        }
1149
7.18k
    };
1150
7.18k
    cb(builder);
1151
7.18k
    converter.check_errors();
1152
7.18k
    return converter.format_grammar();
1153
7.18k
}