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