Coverage Report

Created: 2026-07-23 06:51

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
50.4k
static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
18
50.4k
    auto has_max = max_items != std::numeric_limits<int>::max();
19
20
50.4k
    if (max_items == 0) {
21
685
        return "";
22
685
    }
23
49.7k
    if (min_items == 0 && max_items == 1) {
24
28.2k
        return item_rule + "?";
25
28.2k
    }
26
27
21.5k
    if (separator_rule.empty()) {
28
17.4k
        if (min_items == 1 && !has_max) {
29
937
            return item_rule + "+";
30
937
        }
31
16.4k
        if (min_items == 0 && !has_max) {
32
3.57k
            return item_rule + "*";
33
3.57k
        }
34
12.9k
        return item_rule + "{" + std::to_string(min_items) + "," + (has_max ? std::to_string(max_items) : "") + "}";
35
16.4k
    }
36
37
4.13k
    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.13k
    if (min_items == 0) {
39
3.37k
        result = "(" + result + ")?";
40
3.37k
    }
41
4.13k
    return result;
42
21.5k
}
43
44
25.5k
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
25.5k
    auto has_min = min_value != std::numeric_limits<int64_t>::min();
46
25.5k
    auto has_max = max_value != std::numeric_limits<int64_t>::max();
47
48
181k
    auto digit_range = [&](char from, char to) {
49
181k
        out << "[";
50
181k
        if (from == to) {
51
85.8k
            out << from;
52
95.4k
        } else {
53
95.4k
            out << from << "-" << to;
54
95.4k
        }
55
181k
        out << "]";
56
181k
    };
57
101k
    auto more_digits = [&](int min_digits, int max_digits) {
58
101k
        out << "[0-9]";
59
101k
        if (min_digits == max_digits && min_digits == 1) {
60
11.2k
            return;
61
11.2k
        }
62
90.6k
        out << "{";
63
90.6k
        out << min_digits;
64
90.6k
        if (max_digits != min_digits) {
65
32.2k
            out << ",";
66
32.2k
            if (max_digits != std::numeric_limits<int>::max()) {
67
32.2k
                out << max_digits;
68
32.2k
            }
69
32.2k
        }
70
90.6k
        out << "}";
71
90.6k
    };
72
25.5k
    std::function<void(const std::string_view &, const std::string_view &)> uniform_range =
73
76.3k
        [&](const std::string_view & from, const std::string_view & to) {
74
76.3k
            size_t i = 0;
75
78.4k
            while (i < from.length() && i < to.length() && from[i] == to[i]) {
76
2.12k
                i++;
77
2.12k
            }
78
76.3k
            if (i > 0) {
79
1.91k
                out << "\"" << from.substr(0, i) << "\"";
80
1.91k
            }
81
76.3k
            if (i < from.length() && i < to.length()) {
82
75.7k
                if (i > 0) {
83
1.63k
                    out << " ";
84
1.63k
                }
85
75.7k
                auto sub_len = from.length() - i - 1;
86
75.7k
                if (sub_len > 0) {
87
64.6k
                    auto from_sub = from.substr(i + 1);
88
64.6k
                    auto to_sub = to.substr(i + 1);
89
64.6k
                    auto sub_zeros = string_repeat("0", sub_len);
90
64.6k
                    auto sub_nines = string_repeat("9", sub_len);
91
92
64.6k
                    auto to_reached = false;
93
64.6k
                    out << "(";
94
64.6k
                    if (from_sub == sub_zeros) {
95
62.0k
                        digit_range(from[i], to[i] - 1);
96
62.0k
                        out << " ";
97
62.0k
                        more_digits(sub_len, sub_len);
98
62.0k
                    } else {
99
2.64k
                        out << "[" << from[i] << "] ";
100
2.64k
                        out << "(";
101
2.64k
                        uniform_range(from_sub, sub_nines);
102
2.64k
                        out << ")";
103
2.64k
                        if (from[i] < to[i] - 1) {
104
2.39k
                            out << " | ";
105
2.39k
                            if (to_sub == sub_nines) {
106
2.20k
                                digit_range(from[i] + 1, to[i]);
107
2.20k
                                to_reached = true;
108
2.20k
                            } else {
109
186
                                digit_range(from[i] + 1, to[i] - 1);
110
186
                            }
111
2.39k
                            out << " ";
112
2.39k
                            more_digits(sub_len, sub_len);
113
2.39k
                        }
114
2.64k
                    }
115
64.6k
                    if (!to_reached) {
116
62.4k
                        out << " | ";
117
62.4k
                        digit_range(to[i], to[i]);
118
62.4k
                        out << " ";
119
62.4k
                        uniform_range(sub_zeros, to_sub);
120
62.4k
                    }
121
64.6k
                    out << ")";
122
64.6k
                } else {
123
11.0k
                    out << "[" << from[i] << "-" << to[i] << "]";
124
11.0k
                }
125
75.7k
            }
126
76.3k
        };
127
128
25.5k
    if (has_min && has_max) {
129
2.05k
        if (min_value < 0 && max_value < 0) {
130
347
            out << "\"-\" (";
131
347
            build_min_max_int(-max_value, -min_value, out, decimals_left, /* top_level= */ true);
132
347
            out << ")";
133
347
            return;
134
347
        }
135
136
1.70k
        if (min_value < 0) {
137
78
            out << "\"-\" (";
138
78
            build_min_max_int(0, -min_value, out, decimals_left, /* top_level= */ true);
139
78
            out << ") | ";
140
78
            min_value = 0;
141
78
        }
142
143
1.70k
        auto min_s = std::to_string(min_value);
144
1.70k
        auto max_s = std::to_string(max_value);
145
1.70k
        auto min_digits = min_s.length();
146
1.70k
        auto max_digits = max_s.length();
147
148
11.1k
        for (auto digits = min_digits; digits < max_digits; digits++) {
149
9.46k
            uniform_range(min_s, string_repeat("9", digits));
150
9.46k
            min_s = "1" + string_repeat("0", digits);
151
9.46k
            out << " | ";
152
9.46k
        }
153
1.70k
        uniform_range(min_s, max_s);
154
1.70k
        return;
155
2.05k
    }
156
157
23.5k
    auto less_decimals = std::max(decimals_left - 1, 1);
158
159
23.5k
    if (has_min) {
160
21.9k
        if (min_value < 0) {
161
359
            out << "\"-\" (";
162
359
            build_min_max_int(std::numeric_limits<int64_t>::min(), -min_value, out, decimals_left, /* top_level= */ false);
163
359
            out << ") | [0] | [1-9] ";
164
359
            more_digits(0, decimals_left - 1);
165
21.5k
        } else if (min_value == 0) {
166
798
            if (top_level) {
167
224
                out << "[0] | [1-9] ";
168
224
                more_digits(0, less_decimals);
169
574
            } else {
170
574
                more_digits(1, decimals_left);
171
574
            }
172
20.7k
        } else if (min_value <= 9) {
173
2.03k
            char c = '0' + min_value;
174
2.03k
            auto range_start = top_level ? '1' : '0';
175
2.03k
            if (c > range_start) {
176
1.53k
                digit_range(range_start, c - 1);
177
1.53k
                out << " ";
178
1.53k
                more_digits(1, less_decimals);
179
1.53k
                out << " | ";
180
1.53k
            }
181
2.03k
            digit_range(c, '9');
182
2.03k
            out << " ";
183
2.03k
            more_digits(0, less_decimals);
184
18.7k
        } else {
185
18.7k
            auto min_s = std::to_string(min_value);
186
18.7k
            auto len = min_s.length();
187
18.7k
            auto c = min_s[0];
188
189
18.7k
            if (c > '1') {
190
15.9k
                digit_range(top_level ? '1' : '0', c - 1);
191
15.9k
                out << " ";
192
15.9k
                more_digits(len, less_decimals);
193
15.9k
                out << " | ";
194
15.9k
            }
195
18.7k
            digit_range(c, c);
196
18.7k
            out << " (";
197
18.7k
            build_min_max_int(std::stoll(min_s.substr(1)), std::numeric_limits<int64_t>::max(), out, less_decimals, /* top_level= */ false);
198
18.7k
            out << ")";
199
18.7k
            if (c < '9') {
200
16.1k
                out << " | ";
201
16.1k
                digit_range(c + 1, '9');
202
16.1k
                out << " ";
203
16.1k
                more_digits(len - 1, less_decimals);
204
16.1k
            }
205
18.7k
        }
206
21.9k
        return;
207
21.9k
    }
208
209
1.58k
    if (has_max) {
210
1.58k
        if (max_value >= 0) {
211
982
            if (top_level) {
212
624
                out << "\"-\" [1-9] ";
213
624
                more_digits(0, less_decimals);
214
624
                out << " | ";
215
624
            }
216
982
            build_min_max_int(0, max_value, out, decimals_left, /* top_level= */ true);
217
982
        } else {
218
600
            out << "\"-\" (";
219
600
            build_min_max_int(-max_value, std::numeric_limits<int64_t>::max(), out, decimals_left, /* top_level= */ false);
220
600
            out << ")";
221
600
        }
222
1.58k
        return;
223
1.58k
    }
224
225
5
    throw std::runtime_error("At least one of min_value or max_value must be set");
226
1.58k
}
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
1.11M
static bool is_reserved_name(const std::string & name) {
260
1.11M
    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
1.11M
    return RESERVED_NAMES.find(name) != RESERVED_NAMES.end();
272
1.11M
}
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
545k
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch  &)> & replacement) {
285
545k
    std::smatch match;
286
545k
    std::string result;
287
288
545k
    std::string::const_iterator searchStart(input.cbegin());
289
545k
    std::string::const_iterator searchEnd(input.cend());
290
291
1.63M
    while (std::regex_search(searchStart, searchEnd, match, regex)) {
292
1.08M
        result.append(searchStart, searchStart + match.position());
293
1.08M
        result.append(replacement(match));
294
1.08M
        searchStart = match.suffix().first;
295
1.08M
    }
296
297
545k
    result.append(searchStart, searchEnd);
298
299
545k
    return result;
300
545k
}
301
302
545k
static std::string format_literal(const std::string & literal) {
303
1.08M
    std::string escaped = replacePattern(literal, GRAMMAR_LITERAL_ESCAPE_RE, [&](const std::smatch & match) {
304
1.08M
        char c = match.str()[0];
305
1.08M
        return GRAMMAR_LITERAL_ESCAPES.at(c);
306
1.08M
    });
307
545k
    return "\"" + escaped + "\"";
308
545k
}
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
3.57M
    std::string _add_rule(const std::string & name, const std::string & rule) {
325
3.57M
        std::string esc_name = regex_replace(name, INVALID_RULE_CHARS_RE, "-");
326
3.57M
        if (_rules.find(esc_name) == _rules.end() || _rules[esc_name] == rule) {
327
3.50M
            _rules[esc_name] = rule;
328
3.50M
            return esc_name;
329
3.50M
        }
330
75.1k
        int i = 0;
331
234k
        while (_rules.find(esc_name + std::to_string(i)) != _rules.end() && _rules[esc_name + std::to_string(i)] != rule) {
332
158k
            i++;
333
158k
        }
334
75.1k
        std::string key = esc_name + std::to_string(i);
335
75.1k
        _rules[key] = rule;
336
75.1k
        return key;
337
3.57M
    }
338
339
10.1k
    std::string _generate_union_rule(const std::string & name, const std::vector<json> & alt_schemas) {
340
10.1k
        std::vector<std::string> rules;
341
10.1k
        rules.reserve(alt_schemas.size());
342
193k
        for (size_t i = 0; i < alt_schemas.size(); i++) {
343
183k
            rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
344
183k
        }
345
10.1k
        return string_join(rules, " | ");
346
10.1k
    }
347
348
11.3k
    std::string _visit_pattern(const std::string & pattern, const std::string & name) {
349
11.3k
        if (!(pattern.front() == '^' && pattern.back() == '$')) {
350
4.99k
            _errors.push_back("Pattern must start with '^' and end with '$'");
351
4.99k
            return "";
352
4.99k
        }
353
6.32k
        std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
354
6.32k
        std::unordered_map<std::string, std::string> sub_rule_ids;
355
356
6.32k
        size_t i = 0;
357
6.32k
        size_t length = sub_pattern.length();
358
359
6.32k
        using literal_or_rule = std::pair<std::string, bool>;
360
2.14M
        auto to_rule = [&](const literal_or_rule & ls) {
361
2.14M
            auto is_literal = ls.second;
362
2.14M
            auto s = ls.first;
363
2.14M
            return is_literal ? "\"" + s + "\"" : s;
364
2.14M
        };
365
99.4k
        std::function<literal_or_rule()> transform = [&]() -> literal_or_rule {
366
99.4k
            size_t start = i;
367
99.4k
            std::vector<literal_or_rule> seq;
368
369
1.50M
            auto get_dot = [&]() {
370
1.50M
                std::string rule;
371
1.50M
                if (_dotall) {
372
0
                    rule = "[\\U00000000-\\U0010FFFF]";
373
1.50M
                } else {
374
1.50M
                    rule = "[^\\x0A\\x0D]";
375
1.50M
                }
376
1.50M
                return _add_rule("dot", rule);
377
1.50M
            };
378
379
            // Joins the sequence, merging consecutive literals together.
380
99.4k
            auto join_seq = [&]() {
381
98.2k
                std::vector<literal_or_rule> ret;
382
383
98.2k
                std::string literal;
384
1.90M
                auto flush_literal = [&]() {
385
1.90M
                    if (literal.empty()) {
386
1.66M
                        return false;
387
1.66M
                    }
388
232k
                    ret.emplace_back(literal, true);
389
232k
                    literal.clear();
390
232k
                    return true;
391
1.90M
                };
392
393
2.06M
                for (const auto & item : seq) {
394
2.06M
                    auto is_literal = item.second;
395
2.06M
                    if (is_literal) {
396
258k
                        literal += item.first;
397
1.80M
                    } else {
398
1.80M
                        flush_literal();
399
1.80M
                        ret.push_back(item);
400
1.80M
                    }
401
2.06M
                }
402
98.2k
                flush_literal();
403
404
98.2k
                std::vector<std::string> results;
405
98.2k
                results.reserve(ret.size());
406
2.03M
                for (const auto & item : ret) {
407
2.03M
                    results.push_back(to_rule(item));
408
2.03M
                }
409
98.2k
                return std::make_pair(string_join(results, " "), false);
410
98.2k
            };
411
412
2.22M
            while (i < length) {
413
2.13M
                char c = sub_pattern[i];
414
2.13M
                if (c == '.') {
415
1.50M
                    seq.emplace_back(get_dot(), false);
416
1.50M
                    i++;
417
1.50M
                } else if (c == '(') {
418
96.2k
                    i++;
419
96.2k
                    if (i < length && sub_pattern[i] == '?') {
420
4.44k
                        if (i + 1 < length && sub_pattern[i + 1] == ':') {
421
1.38k
                            i += 2; // skip "?:" for non-capturing group, treat as regular group
422
3.06k
                        } else {
423
                            // lookahead/lookbehind (?=, ?!, ?<=, ?<!) - not supported
424
3.06k
                            _warnings.push_back("Unsupported pattern syntax");
425
                            // skip to matching ')' to avoid UB on empty seq
426
3.06k
                            int depth = 1;
427
138k
                            while (i < length && depth > 0) {
428
135k
                                if (sub_pattern[i] == '\\' && i + 1 < length) {
429
237
                                    i += 2; // skip escaped character
430
135k
                                } else {
431
135k
                                    if (sub_pattern[i] == '(') depth++;
432
128k
                                    else if (sub_pattern[i] == ')') depth--;
433
135k
                                    i++;
434
135k
                                }
435
135k
                            }
436
3.06k
                            continue;
437
3.06k
                        }
438
4.44k
                    }
439
93.1k
                    seq.emplace_back("(" + to_rule(transform()) + ")", false);
440
530k
                } else if (c == ')') {
441
7.79k
                    i++;
442
7.79k
                    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
7.79k
                    return join_seq();
446
522k
                } else if (c == '[') {
447
28.3k
                    std::string square_brackets = std::string(1, c);
448
28.3k
                    i++;
449
1.96M
                    while (i < length && sub_pattern[i] != ']') {
450
1.93M
                        if (sub_pattern[i] == '\\') {
451
125k
                            square_brackets += sub_pattern.substr(i, 2);
452
125k
                            i += 2;
453
1.80M
                        } else {
454
1.80M
                            square_brackets += sub_pattern[i];
455
1.80M
                            i++;
456
1.80M
                        }
457
1.93M
                    }
458
28.3k
                    if (i >= length) {
459
2.14k
                        _errors.push_back("Unbalanced square brackets");
460
2.14k
                    }
461
28.3k
                    square_brackets += ']';
462
28.3k
                    i++;
463
28.3k
                    seq.emplace_back(square_brackets, false);
464
494k
                } else if (c == '|') {
465
150k
                    seq.emplace_back("|", false);
466
150k
                    i++;
467
343k
                } else if (c == '*' || c == '+' || c == '?') {
468
8.70k
                    seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
469
8.70k
                    i++;
470
334k
                } else if (c == '{') {
471
39.2k
                    std::string curly_brackets = std::string(1, c);
472
39.2k
                    i++;
473
6.39M
                    while (i < length && sub_pattern[i] != '}') {
474
6.35M
                        curly_brackets += sub_pattern[i];
475
6.35M
                        i++;
476
6.35M
                    }
477
39.2k
                    if (i >= length) {
478
1.36k
                        _errors.push_back("Unbalanced curly brackets");
479
1.36k
                    }
480
39.2k
                    curly_brackets += '}';
481
39.2k
                    i++;
482
39.2k
                    auto nums = string_split(curly_brackets.substr(1, curly_brackets.length() - 2), ",");
483
39.2k
                    int min_times = 0;
484
39.2k
                    int max_times = std::numeric_limits<int>::max();
485
39.2k
                    try {
486
39.2k
                        if (nums.size() == 1) {
487
7.08k
                            min_times = max_times = std::stoi(nums[0]);
488
32.2k
                        } else if (nums.size() != 2) {
489
1.35k
                            _errors.push_back("Wrong number of values in curly brackets");
490
30.8k
                        } else {
491
30.8k
                            if (!nums[0].empty()) {
492
28.8k
                                min_times = std::stoi(nums[0]);
493
28.8k
                            }
494
30.8k
                            if (!nums[1].empty()) {
495
29.3k
                                max_times = std::stoi(nums[1]);
496
29.3k
                            }
497
30.8k
                        }
498
39.2k
                    } catch (const std::invalid_argument & e) {
499
963
                        _errors.push_back("Invalid number in curly brackets");
500
963
                        return std::make_pair("", false);
501
963
                    }
502
38.2k
                    auto &last = seq.back();
503
38.2k
                    auto &sub = last.first;
504
38.2k
                    auto sub_is_literal = last.second;
505
506
38.2k
                    if (!sub_is_literal) {
507
8.72k
                        std::string & sub_id = sub_rule_ids[sub];
508
8.72k
                        if (sub_id.empty()) {
509
5.88k
                            sub_id = _add_rule(name + "-" + std::to_string(sub_rule_ids.size()), sub);
510
5.88k
                        }
511
8.72k
                        sub = sub_id;
512
8.72k
                    }
513
38.2k
                    seq.back().first = build_repetition(
514
38.2k
                        sub_is_literal ? "\"" + sub + "\"" : sub,
515
38.2k
                        min_times,
516
38.2k
                        max_times,
517
38.2k
                        ""
518
38.2k
                    );
519
38.2k
                    seq.back().second = false;
520
295k
                } else {
521
295k
                    std::string literal;
522
42.3M
                    auto is_non_literal = [&](char c) {
523
42.3M
                        return NON_LITERAL_SET.find(c) != NON_LITERAL_SET.end();
524
42.3M
                    };
525
21.5M
                    while (i < length) {
526
21.5M
                        if (sub_pattern[i] == '\\' && i < length - 1) {
527
69.6k
                            char next = sub_pattern[i + 1];
528
69.6k
                            if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
529
897
                                i++;
530
897
                                literal += sub_pattern[i];
531
897
                                i++;
532
68.7k
                            } else {
533
68.7k
                                literal += sub_pattern.substr(i, 2);
534
68.7k
                                i += 2;
535
68.7k
                            }
536
21.4M
                        } else if (sub_pattern[i] == '"') {
537
301
                            literal += "\\\"";
538
301
                            i++;
539
21.4M
                        } else if (!is_non_literal(sub_pattern[i]) &&
540
21.2M
                                (i == length - 1 || literal.empty() || sub_pattern[i + 1] == '.' || !is_non_literal(sub_pattern[i + 1]))) {
541
21.1M
                            literal += sub_pattern[i];
542
21.1M
                            i++;
543
21.1M
                        } else {
544
293k
                            break;
545
293k
                        }
546
21.5M
                    }
547
295k
                    if (!literal.empty()) {
548
295k
                        seq.emplace_back(literal, true);
549
295k
                    }
550
295k
                }
551
2.13M
            }
552
90.6k
            return join_seq();
553
99.4k
        };
554
6.32k
        return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\"");
555
11.3k
    }
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
77.8k
    std::string _resolve_ref(const std::string & ref) {
627
77.8k
        auto it = ref.find('#');
628
77.8k
        std::string ref_fragment = it != std::string::npos ? ref.substr(it + 1) : ref;
629
77.8k
        static const std::regex nonalphanumeric_regex(R"([^a-zA-Z0-9-]+)");
630
77.8k
        std::string ref_name = "ref" + std::regex_replace(ref_fragment, nonalphanumeric_regex, "-");
631
77.8k
        if (_rules.find(ref_name) == _rules.end() && _refs_being_resolved.find(ref) == _refs_being_resolved.end()) {
632
13.7k
            _refs_being_resolved.insert(ref);
633
13.7k
            json resolved = _refs[ref];
634
13.7k
            ref_name = visit(resolved, ref_name);
635
13.7k
            _refs_being_resolved.erase(ref);
636
13.7k
        }
637
77.8k
        return ref_name;
638
77.8k
    }
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.49k
    {
646
8.49k
        std::vector<std::string> required_props;
647
8.49k
        std::vector<std::string> optional_props;
648
8.49k
        std::unordered_map<std::string, std::string> prop_kv_rule_names;
649
8.49k
        std::vector<std::string> prop_names;
650
518k
        for (const auto & kv : properties) {
651
518k
            const auto &prop_name = kv.first;
652
518k
            const auto &prop_schema = kv.second;
653
654
518k
            std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name);
655
518k
            prop_kv_rule_names[prop_name] = _add_rule(
656
518k
                name + (name.empty() ? "" : "-") + prop_name + "-kv",
657
518k
                format_literal(json(prop_name).dump()) + " space \":\" space " + prop_rule_name
658
518k
            );
659
518k
            if (required.find(prop_name) != required.end()) {
660
485k
                required_props.push_back(prop_name);
661
485k
            } else {
662
33.5k
                optional_props.push_back(prop_name);
663
33.5k
            }
664
518k
            prop_names.push_back(prop_name);
665
518k
        }
666
8.49k
        if ((additional_properties.is_boolean() && additional_properties.get<bool>()) || additional_properties.is_object()) {
667
536
            std::string sub_name = name + (name.empty() ? "" : "-") + "additional";
668
536
            std::string value_rule =
669
536
                additional_properties.is_object() ? visit(additional_properties, sub_name + "-value")
670
536
                : _add_primitive("value", PRIMITIVE_RULES.at("value"));
671
672
536
            auto key_rule =
673
536
                prop_names.empty() ? _add_primitive("string", PRIMITIVE_RULES.at("string"))
674
536
                : _add_rule(sub_name + "-k", _not_strings(prop_names));
675
536
            std::string kv_rule = _add_rule(sub_name + "-kv", key_rule + " \":\" space " + value_rule);
676
536
            prop_kv_rule_names["*"] = kv_rule;
677
536
            optional_props.push_back("*");
678
536
        }
679
680
8.49k
        std::string rule = "\"{\" space ";
681
493k
        for (size_t i = 0; i < required_props.size(); i++) {
682
485k
            if (i > 0) {
683
483k
                rule += " \",\" space ";
684
483k
            }
685
485k
            rule += prop_kv_rule_names[required_props[i]];
686
485k
        }
687
688
8.49k
        if (!optional_props.empty()) {
689
5.70k
            rule += " (";
690
5.70k
            if (!required_props.empty()) {
691
26
                rule += " \",\" space ( ";
692
26
            }
693
694
1.36M
            std::function<std::string(const std::vector<std::string> &, bool)> get_recursive_refs = [&](const std::vector<std::string> & ks, bool first_is_optional) {
695
1.36M
                std::string res;
696
1.36M
                if (ks.empty()) {
697
0
                    return res;
698
0
                }
699
1.36M
                const std::string& k = ks[0];
700
1.36M
                std::string kv_rule_name = prop_kv_rule_names[k];
701
1.36M
                std::string comma_ref = "( \",\" space " + kv_rule_name + " )";
702
1.36M
                if (first_is_optional) {
703
1.33M
                    res = comma_ref + (k == "*" ? "*" : "?");
704
1.33M
                } else {
705
32.1k
                    res = kv_rule_name + (k == "*" ? " " + comma_ref + "*" : "");
706
32.1k
                }
707
1.36M
                if (ks.size() > 1) {
708
1.33M
                    res += " " + _add_rule(
709
1.33M
                        name + (name.empty() ? "" : "-") + k + "-rest",
710
1.33M
                        get_recursive_refs(std::vector<std::string>(ks.begin() + 1, ks.end()), true)
711
1.33M
                    );
712
1.33M
                }
713
1.36M
                return res;
714
1.36M
            };
715
716
37.8k
            for (size_t i = 0; i < optional_props.size(); i++) {
717
32.1k
                if (i > 0) {
718
26.4k
                    rule += " | ";
719
26.4k
                }
720
32.1k
                rule += get_recursive_refs(std::vector<std::string>(optional_props.begin() + i, optional_props.end()), false);
721
32.1k
            }
722
5.70k
            if (!required_props.empty()) {
723
26
                rule += " )";
724
26
            }
725
5.70k
            rule += " )?";
726
5.70k
        }
727
728
8.49k
        rule += " space \"}\"";
729
730
8.49k
        return rule;
731
8.49k
    }
732
733
55.7k
    std::string _add_primitive(const std::string & name, const BuiltinRule & rule) {
734
55.7k
        auto n = _add_rule(name, rule.content);
735
136k
        for (const auto & dep : rule.deps) {
736
136k
            BuiltinRule dep_rule;
737
136k
            auto it = PRIMITIVE_RULES.find(dep);
738
136k
            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
136k
            if (_rules.find(dep) == _rules.end()) {
746
26.5k
                _add_primitive(dep, it->second);
747
26.5k
            }
748
136k
        }
749
55.7k
        return n;
750
55.7k
    }
751
752
public:
753
    common_schema_converter(
754
        const std::function<json(const std::string &)> & fetch_json,
755
        bool dotall)
756
10.4k
          : _fetch_json(fetch_json), _dotall(dotall)
757
10.4k
    {
758
10.4k
        _rules["space"] = SPACE_RULE;
759
10.4k
    }
760
761
13.9k
    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
6.45M
        std::function<void(json &)> visit_refs = [&](json & n) {
768
6.45M
            if (n.is_array()) {
769
6.37M
                for (auto & x : n) {
770
6.37M
                    visit_refs(x);
771
6.37M
                }
772
6.43M
            } else if (n.is_object()) {
773
80.0k
                if (n.contains("$ref")) {
774
33.0k
                    std::string ref = n["$ref"];
775
33.0k
                    if (_refs.find(ref) == _refs.end()) {
776
28.7k
                        json target;
777
28.7k
                        if (ref.find("https://") == 0) {
778
6.98k
                            std::string base_url = ref.substr(0, ref.find('#'));
779
6.98k
                            auto it = _refs.find(base_url);
780
6.98k
                            if (it != _refs.end()) {
781
3.46k
                                target = it->second;
782
3.52k
                            } else {
783
                                // Fetch the referenced schema and resolve its refs
784
3.52k
                                auto referenced = _fetch_json(ref);
785
3.52k
                                resolve_refs(referenced, base_url);
786
3.52k
                                _refs[base_url] = referenced;
787
3.52k
                            }
788
6.98k
                            if (ref.find('#') == std::string::npos || ref.substr(ref.find('#') + 1).empty()) {
789
4.22k
                                return;
790
4.22k
                            }
791
21.8k
                        } else if (ref.find("#/") == 0) {
792
10.4k
                            target = schema;
793
10.4k
                            n["$ref"] = url + ref;
794
10.4k
                            ref = url + ref;
795
11.3k
                        } else {
796
11.3k
                            _errors.push_back("Unsupported ref: " + ref);
797
11.3k
                            return;
798
11.3k
                        }
799
13.2k
                        std::string pointer = ref.substr(ref.find('#') + 1);
800
13.2k
                        std::vector<std::string> tokens = string_split(pointer, "/");
801
21.9k
                        for (size_t i = 1; i < tokens.size(); ++i) {
802
17.7k
                            const std::string& sel = tokens[i];
803
17.7k
                            if (target.is_object() && target.contains(sel)) {
804
5.40k
                                target = target[sel];
805
12.3k
                            } else if (target.is_array()) {
806
5.88k
                                size_t sel_index;
807
5.88k
                                try {
808
5.88k
                                    sel_index = std::stoull(sel);
809
5.88k
                                } catch (const std::invalid_argument & e) {
810
1.26k
                                    sel_index = target.size();
811
1.26k
                                }
812
5.88k
                                if (sel_index >= target.size()) {
813
2.54k
                                    _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
814
2.54k
                                    return;
815
2.54k
                                }
816
3.33k
                                target = target[sel_index];
817
6.50k
                            } else {
818
6.50k
                                _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
819
6.50k
                                return;
820
6.50k
                            }
821
17.7k
                        }
822
4.15k
                        _refs[ref] = target;
823
4.15k
                    }
824
47.0k
                } else {
825
66.5k
                    for (const auto & kv : n.items()) {
826
66.5k
                        visit_refs(kv.value());
827
66.5k
                    }
828
47.0k
                }
829
80.0k
            }
830
6.45M
        };
831
832
13.9k
        visit_refs(schema);
833
13.9k
    }
834
835
26.7k
    static std::string _generate_constant_rule(const json & value) {
836
26.7k
        return format_literal(value.dump());
837
26.7k
    }
838
839
1.11M
    std::string visit(const json & schema, const std::string & name) {
840
1.11M
        json schema_type = schema.contains("type") ? schema["type"] : json();
841
1.11M
        std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
842
1.11M
        std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
843
844
1.11M
        if (schema.contains("$ref")) {
845
77.8k
            return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
846
77.8k
        }
847
1.03M
        if (schema.contains("oneOf") || schema.contains("anyOf")) {
848
1.59k
            std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
849
1.59k
            return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
850
1.59k
        }
851
1.03M
        if (schema_type.is_array()) {
852
8.61k
            std::vector<json> schema_types;
853
74.3k
            for (const auto & t : schema_type) {
854
74.3k
                json schema_copy(schema);
855
74.3k
                schema_copy["type"] = t;
856
74.3k
                schema_types.push_back(schema_copy);
857
74.3k
            }
858
8.61k
            return _add_rule(rule_name, _generate_union_rule(name, schema_types));
859
8.61k
        }
860
1.02M
        if (schema.contains("const")) {
861
2.36k
            return _add_rule(rule_name, _generate_constant_rule(schema["const"]));
862
2.36k
        }
863
1.02M
        if (schema.contains("enum")) {
864
6.96k
            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
6.96k
            return _add_rule(rule_name, "(" + string_join(enum_values, " | ") + ")");
869
6.96k
        }
870
1.01M
        if ((schema_type.is_null() || schema_type == "object")
871
962k
                && (schema.contains("properties") ||
872
956k
                    (schema.contains("additionalProperties") && schema["additionalProperties"] != true))) {
873
6.25k
            std::unordered_set<std::string> required;
874
6.25k
            if (schema.contains("required") && schema["required"].is_array()) {
875
30.1k
                for (const auto & item : schema["required"]) {
876
30.1k
                    if (item.is_string()) {
877
15.1k
                        required.insert(item.get<std::string>());
878
15.1k
                    }
879
30.1k
                }
880
1.90k
            }
881
6.25k
            std::vector<std::pair<std::string, json>> properties;
882
6.25k
            if (schema.contains("properties")) {
883
32.5k
                for (const auto & prop : schema["properties"].items()) {
884
32.5k
                    properties.emplace_back(prop.key(), prop.value());
885
32.5k
                }
886
5.37k
            }
887
6.25k
            return _add_rule(rule_name,
888
6.25k
                _build_object_rule(
889
6.25k
                    properties, required, name,
890
6.25k
                    schema.contains("additionalProperties") ? schema["additionalProperties"] : json()));
891
6.25k
        }
892
1.00M
        if ((schema_type.is_null() || schema_type == "object" || schema_type == "string") && schema.contains("allOf")) {
893
2.27k
            std::unordered_set<std::string> required;
894
2.27k
            std::vector<std::pair<std::string, json>> properties;
895
2.27k
            std::map<std::string, size_t> enum_values;
896
2.27k
            const std::string& hybrid_name = name;
897
40.4k
            std::function<void(const json &, bool)> add_component = [&](const json & comp_schema, bool is_required) {
898
40.4k
                if (comp_schema.contains("$ref")) {
899
7.62k
                    add_component(_refs[comp_schema["$ref"]], is_required);
900
32.8k
                } else if (comp_schema.contains("properties")) {
901
486k
                    for (const auto & prop : comp_schema["properties"].items()) {
902
486k
                        properties.emplace_back(prop.key(), prop.value());
903
486k
                        if (is_required) {
904
484k
                            required.insert(prop.key());
905
484k
                        }
906
486k
                    }
907
30.2k
                } else if (comp_schema.contains("enum")) {
908
11.2k
                    for (const auto & v : comp_schema["enum"]) {
909
11.2k
                        const auto rule = _generate_constant_rule(v);
910
11.2k
                        if (enum_values.find(rule) == enum_values.end()) {
911
3.43k
                            enum_values[rule] = 0;
912
3.43k
                        }
913
11.2k
                        enum_values[rule] += 1;
914
11.2k
                    }
915
28.0k
                } else {
916
                  // todo warning
917
28.0k
                }
918
40.4k
            };
919
30.7k
            for (const auto & t : schema["allOf"]) {
920
30.7k
                if (t.contains("anyOf")) {
921
2.63k
                    for (const auto & tt : t["anyOf"]) {
922
2.63k
                        add_component(tt, false);
923
2.63k
                    }
924
30.1k
                } else {
925
30.1k
                    add_component(t, true);
926
30.1k
                }
927
30.7k
            }
928
2.27k
            if (!enum_values.empty()) {
929
297
                std::vector<std::string> enum_intersection;
930
3.43k
                for (const auto & p : enum_values) {
931
3.43k
                    if (p.second == schema["allOf"].size()) {
932
66
                        enum_intersection.push_back(p.first);
933
66
                    }
934
3.43k
                }
935
297
                if (!enum_intersection.empty()) {
936
33
                    return _add_rule(rule_name, "(" + string_join(enum_intersection, " | ") + ")");
937
33
                }
938
297
            }
939
2.24k
            return _add_rule(rule_name, _build_object_rule(properties, required, hybrid_name, json()));
940
2.27k
        }
941
1.00M
        if ((schema_type.is_null() || schema_type == "array") && (schema.contains("items") || schema.contains("prefixItems"))) {
942
12.2k
            json items = schema.contains("items") ? schema["items"] : schema["prefixItems"];
943
12.2k
            if (items.is_array()) {
944
4.30k
                std::string rule = "\"[\" space ";
945
381k
                for (size_t i = 0; i < items.size(); i++) {
946
377k
                    if (i > 0) {
947
372k
                        rule += " \",\" space ";
948
372k
                    }
949
377k
                    rule += visit(items[i], name + (name.empty() ? "" : "-") + "tuple-" + std::to_string(i));
950
377k
                }
951
4.30k
                rule += " space \"]\"";
952
4.30k
                return _add_rule(rule_name, rule);
953
4.30k
            }
954
7.94k
            std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
955
7.94k
            int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
956
7.94k
            json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
957
7.94k
            int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
958
959
7.94k
            return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " space \"]\"");
960
12.2k
        }
961
993k
        if ((schema_type.is_null() || schema_type == "string") && schema.contains("pattern")) {
962
11.3k
            return _visit_pattern(schema["pattern"], rule_name);
963
11.3k
        }
964
982k
        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
982k
        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
982k
        if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
972
368
            std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
973
368
            int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
974
368
            int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
975
368
            return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\"");
976
368
        }
977
981k
        if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
978
4.46k
            int64_t min_value = std::numeric_limits<int64_t>::min();
979
4.46k
            int64_t max_value = std::numeric_limits<int64_t>::max();
980
4.46k
            if (schema.contains("minimum")) {
981
3.18k
                min_value = schema["minimum"].get<int64_t>();
982
3.18k
            } else if (schema.contains("exclusiveMinimum")) {
983
78
                min_value = schema["exclusiveMinimum"].get<int64_t>() + 1;
984
78
            }
985
4.46k
            if (schema.contains("maximum")) {
986
1.75k
                max_value = schema["maximum"].get<int64_t>();
987
2.70k
            } else if (schema.contains("exclusiveMaximum")) {
988
115
                max_value = schema["exclusiveMaximum"].get<int64_t>() - 1;
989
115
            }
990
4.46k
            std::stringstream out;
991
4.46k
            out << "(";
992
4.46k
            build_min_max_int(min_value, max_value, out);
993
4.46k
            out << ")";
994
4.46k
            return _add_rule(rule_name, out.str());
995
4.46k
        }
996
977k
        if (schema.empty() || schema_type == "object") {
997
12.4k
            return _add_rule(rule_name, _add_primitive("object", PRIMITIVE_RULES.at("object")));
998
12.4k
        }
999
965k
        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
13.8k
            return _add_rule(rule_name, _add_primitive("value", PRIMITIVE_RULES.at("value")));
1003
13.8k
        }
1004
951k
        if (!schema_type.is_string() || PRIMITIVE_RULES.find(schema_type.get<std::string>()) == PRIMITIVE_RULES.end()) {
1005
949k
            _errors.push_back("Unrecognized schema: " + schema.dump());
1006
949k
            return "";
1007
949k
        }
1008
        // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
1009
2.05k
        return _add_primitive(rule_name == "root" ? "root" : schema_type.get<std::string>(), PRIMITIVE_RULES.at(schema_type.get<std::string>()));
1010
951k
    }
1011
1012
10.3k
    void check_errors() {
1013
10.3k
        if (!_errors.empty()) {
1014
8.03k
            throw std::invalid_argument("JSON schema conversion failed:\n" + string_join(_errors, "\n"));
1015
8.03k
        }
1016
2.27k
        if (!_warnings.empty()) {
1017
136
            fprintf(stderr, "WARNING: JSON schema conversion was incomplete: %s\n", string_join(_warnings, "; ").c_str());
1018
136
        }
1019
2.27k
    }
1020
1021
2.27k
    std::string format_grammar() {
1022
2.27k
        std::stringstream ss;
1023
26.8k
        for (const auto & kv : _rules) {
1024
26.8k
            ss << kv.first << " ::= " << kv.second << '\n';
1025
26.8k
        }
1026
2.27k
        return ss.str();
1027
2.27k
    }
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
10.4k
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
10.4k
    (void)force_gbnf;
1165
10.4k
#endif // LLAMA_USE_LLGUIDANCE
1166
10.4k
    return build_grammar([&](const common_grammar_builder & callbacks) {
1167
10.4k
        auto copy = schema;
1168
10.4k
        callbacks.resolve_refs(copy);
1169
10.4k
        callbacks.add_schema("", copy);
1170
10.4k
    });
1171
10.4k
}
1172
1173
10.4k
std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options) {
1174
10.4k
    common_schema_converter converter([&](const std::string &) { return json(); }, options.dotall);
1175
10.4k
    common_grammar_builder builder {
1176
10.4k
        /* .add_rule = */ [&](const std::string & name, const std::string & rule) {
1177
0
            return converter._add_rule(name, rule);
1178
0
        },
1179
10.4k
        /* .add_schema = */ [&](const std::string & name, const nlohmann::ordered_json & schema) {
1180
10.4k
            return converter.visit(schema, name == "root" ? "" : name);
1181
10.4k
        },
1182
10.4k
        /* .resolve_refs = */ [&](nlohmann::ordered_json & schema) {
1183
10.4k
            converter.resolve_refs(schema, "");
1184
10.4k
        }
1185
10.4k
    };
1186
10.4k
    cb(builder);
1187
10.4k
    converter.check_errors();
1188
10.4k
    return converter.format_grammar();
1189
10.4k
}