Coverage Report

Created: 2026-06-22 06:47

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