/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 | 124k | static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") { |
18 | 124k | auto has_max = max_items != std::numeric_limits<int>::max(); |
19 | | |
20 | 124k | if (max_items == 0) { |
21 | 892 | return ""; |
22 | 892 | } |
23 | 123k | if (min_items == 0 && max_items == 1) { |
24 | 21.7k | return item_rule + "?"; |
25 | 21.7k | } |
26 | | |
27 | 101k | if (separator_rule.empty()) { |
28 | 98.4k | if (min_items == 1 && !has_max) { |
29 | 1.74k | return item_rule + "+"; |
30 | 96.6k | } else if (min_items == 0 && !has_max) { |
31 | 3.82k | return item_rule + "*"; |
32 | 92.8k | } else { |
33 | 92.8k | return item_rule + "{" + std::to_string(min_items) + "," + (has_max ? std::to_string(max_items) : "") + "}"; |
34 | 92.8k | } |
35 | 98.4k | } |
36 | | |
37 | 2.94k | 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.94k | if (min_items == 0) { |
39 | 2.67k | result = "(" + result + ")?"; |
40 | 2.67k | } |
41 | 2.94k | return result; |
42 | 101k | } |
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 | 373k | static bool is_reserved_name(const std::string & name) { |
260 | 373k | 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 | 373k | return RESERVED_NAMES.find(name) != RESERVED_NAMES.end(); |
268 | 373k | } |
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 | 239k | static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) { |
281 | 239k | std::smatch match; |
282 | 239k | std::string result; |
283 | | |
284 | 239k | std::string::const_iterator searchStart(input.cbegin()); |
285 | 239k | std::string::const_iterator searchEnd(input.cend()); |
286 | | |
287 | 711k | while (std::regex_search(searchStart, searchEnd, match, regex)) { |
288 | 472k | result.append(searchStart, searchStart + match.position()); |
289 | 472k | result.append(replacement(match)); |
290 | 472k | searchStart = match.suffix().first; |
291 | 472k | } |
292 | | |
293 | 239k | result.append(searchStart, searchEnd); |
294 | | |
295 | 239k | return result; |
296 | 239k | } |
297 | | |
298 | 239k | static std::string format_literal(const std::string & literal) { |
299 | 472k | std::string escaped = replacePattern(literal, GRAMMAR_LITERAL_ESCAPE_RE, [&](const std::smatch & match) { |
300 | 472k | char c = match.str()[0]; |
301 | 472k | return GRAMMAR_LITERAL_ESCAPES.at(c); |
302 | 472k | }); |
303 | 239k | return "\"" + escaped + "\""; |
304 | 239k | } |
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.57M | std::string _add_rule(const std::string & name, const std::string & rule) { |
320 | 1.57M | std::string esc_name = regex_replace(name, INVALID_RULE_CHARS_RE, "-"); |
321 | 1.57M | if (_rules.find(esc_name) == _rules.end() || _rules[esc_name] == rule) { |
322 | 1.47M | _rules[esc_name] = rule; |
323 | 1.47M | return esc_name; |
324 | 1.47M | } else { |
325 | 92.5k | int i = 0; |
326 | 335k | while (_rules.find(esc_name + std::to_string(i)) != _rules.end() && _rules[esc_name + std::to_string(i)] != rule) { |
327 | 242k | i++; |
328 | 242k | } |
329 | 92.5k | std::string key = esc_name + std::to_string(i); |
330 | 92.5k | _rules[key] = rule; |
331 | 92.5k | return key; |
332 | 92.5k | } |
333 | 1.57M | } |
334 | | |
335 | 4.96k | std::string _generate_union_rule(const std::string & name, const std::vector<json> & alt_schemas) { |
336 | 4.96k | std::vector<std::string> rules; |
337 | 65.0k | for (size_t i = 0; i < alt_schemas.size(); i++) { |
338 | 60.0k | rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i))); |
339 | 60.0k | } |
340 | 4.96k | return string_join(rules, " | "); |
341 | 4.96k | } |
342 | | |
343 | 5.72k | std::string _visit_pattern(const std::string & pattern, const std::string & name) { |
344 | 5.72k | if (!(pattern.front() == '^' && pattern.back() == '$')) { |
345 | 1.30k | _errors.push_back("Pattern must start with '^' and end with '$'"); |
346 | 1.30k | return ""; |
347 | 1.30k | } |
348 | 4.41k | std::string sub_pattern = pattern.substr(1, pattern.length() - 2); |
349 | 4.41k | std::unordered_map<std::string, std::string> sub_rule_ids; |
350 | | |
351 | 4.41k | size_t i = 0; |
352 | 4.41k | size_t length = sub_pattern.length(); |
353 | | |
354 | 4.41k | using literal_or_rule = std::pair<std::string, bool>; |
355 | 953k | auto to_rule = [&](const literal_or_rule & ls) { |
356 | 953k | auto is_literal = ls.second; |
357 | 953k | auto s = ls.first; |
358 | 953k | return is_literal ? "\"" + s + "\"" : s; |
359 | 953k | }; |
360 | 99.9k | std::function<literal_or_rule()> transform = [&]() -> literal_or_rule { |
361 | 99.9k | size_t start = i; |
362 | 99.9k | std::vector<literal_or_rule> seq; |
363 | | |
364 | 332k | auto get_dot = [&]() { |
365 | 332k | std::string rule; |
366 | 332k | if (_dotall) { |
367 | 0 | rule = "[\\U00000000-\\U0010FFFF]"; |
368 | 332k | } else { |
369 | 332k | rule = "[^\\x0A\\x0D]"; |
370 | 332k | } |
371 | 332k | return _add_rule("dot", rule); |
372 | 332k | }; |
373 | | |
374 | | // Joins the sequence, merging consecutive literals together. |
375 | 99.9k | auto join_seq = [&]() { |
376 | 98.4k | std::vector<literal_or_rule> ret; |
377 | | |
378 | 98.4k | std::string literal; |
379 | 741k | auto flush_literal = [&]() { |
380 | 741k | if (literal.empty()) { |
381 | 590k | return false; |
382 | 590k | } |
383 | 151k | ret.emplace_back(literal, true); |
384 | 151k | literal.clear(); |
385 | 151k | return true; |
386 | 741k | }; |
387 | | |
388 | 812k | for (const auto & item : seq) { |
389 | 812k | auto is_literal = item.second; |
390 | 812k | if (is_literal) { |
391 | 169k | literal += item.first; |
392 | 643k | } else { |
393 | 643k | flush_literal(); |
394 | 643k | ret.push_back(item); |
395 | 643k | } |
396 | 812k | } |
397 | 98.4k | flush_literal(); |
398 | | |
399 | 98.4k | std::vector<std::string> results; |
400 | 794k | for (const auto & item : ret) { |
401 | 794k | results.push_back(to_rule(item)); |
402 | 794k | } |
403 | 98.4k | return std::make_pair(string_join(results, " "), false); |
404 | 98.4k | }; |
405 | | |
406 | 1.10M | while (i < length) { |
407 | 1.00M | char c = sub_pattern[i]; |
408 | 1.00M | if (c == '.') { |
409 | 332k | seq.emplace_back(get_dot(), false); |
410 | 332k | i++; |
411 | 677k | } else if (c == '(') { |
412 | 95.5k | i++; |
413 | 95.5k | if (i < length) { |
414 | 95.1k | if (sub_pattern[i] == '?') { |
415 | 0 | _warnings.push_back("Unsupported pattern syntax"); |
416 | 0 | } |
417 | 95.1k | } |
418 | 95.5k | seq.emplace_back("(" + to_rule(transform()) + ")", false); |
419 | 581k | } else if (c == ')') { |
420 | 5.98k | i++; |
421 | 5.98k | if (start > 0 && sub_pattern[start - 1] != '(') { |
422 | 0 | _errors.push_back("Unbalanced parentheses"); |
423 | 0 | } |
424 | 5.98k | return join_seq(); |
425 | 575k | } else if (c == '[') { |
426 | 11.1k | std::string square_brackets = std::string(1, c); |
427 | 11.1k | i++; |
428 | 1.99M | while (i < length && sub_pattern[i] != ']') { |
429 | 1.98M | if (sub_pattern[i] == '\\') { |
430 | 28.0k | square_brackets += sub_pattern.substr(i, 2); |
431 | 28.0k | i += 2; |
432 | 1.95M | } else { |
433 | 1.95M | square_brackets += sub_pattern[i]; |
434 | 1.95M | i++; |
435 | 1.95M | } |
436 | 1.98M | } |
437 | 11.1k | if (i >= length) { |
438 | 1.00k | _errors.push_back("Unbalanced square brackets"); |
439 | 1.00k | } |
440 | 11.1k | square_brackets += ']'; |
441 | 11.1k | i++; |
442 | 11.1k | seq.emplace_back(square_brackets, false); |
443 | 564k | } else if (c == '|') { |
444 | 176k | seq.emplace_back("|", false); |
445 | 176k | i++; |
446 | 387k | } else if (c == '*' || c == '+' || c == '?') { |
447 | 59.2k | seq.back() = std::make_pair(to_rule(seq.back()) + c, false); |
448 | 59.2k | i++; |
449 | 328k | } else if (c == '{') { |
450 | 119k | std::string curly_brackets = std::string(1, c); |
451 | 119k | i++; |
452 | 8.52M | while (i < length && sub_pattern[i] != '}') { |
453 | 8.40M | curly_brackets += sub_pattern[i]; |
454 | 8.40M | i++; |
455 | 8.40M | } |
456 | 119k | if (i >= length) { |
457 | 1.04k | _errors.push_back("Unbalanced curly brackets"); |
458 | 1.04k | } |
459 | 119k | curly_brackets += '}'; |
460 | 119k | i++; |
461 | 119k | auto nums = string_split(curly_brackets.substr(1, curly_brackets.length() - 2), ","); |
462 | 119k | int min_times = 0; |
463 | 119k | int max_times = std::numeric_limits<int>::max(); |
464 | 119k | try { |
465 | 119k | if (nums.size() == 1) { |
466 | 88.7k | min_times = max_times = std::stoi(nums[0]); |
467 | 88.7k | } else if (nums.size() != 2) { |
468 | 1.16k | _errors.push_back("Wrong number of values in curly brackets"); |
469 | 29.4k | } else { |
470 | 29.4k | if (!nums[0].empty()) { |
471 | 26.8k | min_times = std::stoi(nums[0]); |
472 | 26.8k | } |
473 | 29.4k | if (!nums[1].empty()) { |
474 | 27.2k | max_times = std::stoi(nums[1]); |
475 | 27.2k | } |
476 | 29.4k | } |
477 | 119k | } catch (const std::invalid_argument & e) { |
478 | 1.22k | _errors.push_back("Invalid number in curly brackets"); |
479 | 1.22k | return std::make_pair("", false); |
480 | 1.22k | } |
481 | 118k | auto &last = seq.back(); |
482 | 118k | auto &sub = last.first; |
483 | 118k | auto sub_is_literal = last.second; |
484 | | |
485 | 118k | if (!sub_is_literal) { |
486 | 89.3k | std::string & sub_id = sub_rule_ids[sub]; |
487 | 89.3k | if (sub_id.empty()) { |
488 | 85.3k | sub_id = _add_rule(name + "-" + std::to_string(sub_rule_ids.size()), sub); |
489 | 85.3k | } |
490 | 89.3k | sub = sub_id; |
491 | 89.3k | } |
492 | 118k | seq.back().first = build_repetition( |
493 | 118k | sub_is_literal ? "\"" + sub + "\"" : sub, |
494 | 118k | min_times, |
495 | 118k | max_times, |
496 | 118k | "" |
497 | 118k | ); |
498 | 118k | seq.back().second = false; |
499 | 209k | } else { |
500 | 209k | std::string literal; |
501 | 48.0M | auto is_non_literal = [&](char c) { |
502 | 48.0M | return NON_LITERAL_SET.find(c) != NON_LITERAL_SET.end(); |
503 | 48.0M | }; |
504 | 24.3M | while (i < length) { |
505 | 24.3M | if (sub_pattern[i] == '\\' && i < length - 1) { |
506 | 61.3k | char next = sub_pattern[i + 1]; |
507 | 61.3k | if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) { |
508 | 124 | i++; |
509 | 124 | literal += sub_pattern[i]; |
510 | 124 | i++; |
511 | 61.2k | } else { |
512 | 61.2k | literal += sub_pattern.substr(i, 2); |
513 | 61.2k | i += 2; |
514 | 61.2k | } |
515 | 24.2M | } else if (sub_pattern[i] == '"') { |
516 | 1.82k | literal += "\\\""; |
517 | 1.82k | i++; |
518 | 24.2M | } else if (!is_non_literal(sub_pattern[i]) && |
519 | 24.0M | (i == length - 1 || literal.empty() || sub_pattern[i + 1] == '.' || !is_non_literal(sub_pattern[i + 1]))) { |
520 | 24.0M | literal += sub_pattern[i]; |
521 | 24.0M | i++; |
522 | 24.0M | } else { |
523 | 207k | break; |
524 | 207k | } |
525 | 24.3M | } |
526 | 209k | if (!literal.empty()) { |
527 | 209k | seq.emplace_back(literal, true); |
528 | 209k | } |
529 | 209k | } |
530 | 1.00M | } |
531 | 92.7k | return join_seq(); |
532 | 99.9k | }; |
533 | 4.41k | return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\" space"); |
534 | 5.72k | } |
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 | 14.9k | std::string _resolve_ref(const std::string & ref) { |
606 | 14.9k | auto it = ref.find('#'); |
607 | 14.9k | std::string ref_fragment = it != std::string::npos ? ref.substr(it + 1) : ref; |
608 | 14.9k | static const std::regex nonalphanumeric_regex(R"([^a-zA-Z0-9-]+)"); |
609 | 14.9k | std::string ref_name = "ref" + std::regex_replace(ref_fragment, nonalphanumeric_regex, "-"); |
610 | 14.9k | if (_rules.find(ref_name) == _rules.end() && _refs_being_resolved.find(ref) == _refs_being_resolved.end()) { |
611 | 3.76k | _refs_being_resolved.insert(ref); |
612 | 3.76k | json resolved = _refs[ref]; |
613 | 3.76k | ref_name = visit(resolved, ref_name); |
614 | 3.76k | _refs_being_resolved.erase(ref); |
615 | 3.76k | } |
616 | 14.9k | return ref_name; |
617 | 14.9k | } |
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.88k | { |
625 | 4.88k | std::vector<std::string> required_props; |
626 | 4.88k | std::vector<std::string> optional_props; |
627 | 4.88k | std::unordered_map<std::string, std::string> prop_kv_rule_names; |
628 | 4.88k | std::vector<std::string> prop_names; |
629 | 223k | for (const auto & kv : properties) { |
630 | 223k | const auto &prop_name = kv.first; |
631 | 223k | const auto &prop_schema = kv.second; |
632 | | |
633 | 223k | std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name); |
634 | 223k | prop_kv_rule_names[prop_name] = _add_rule( |
635 | 223k | name + (name.empty() ? "" : "-") + prop_name + "-kv", |
636 | 223k | format_literal(json(prop_name).dump()) + " space \":\" space " + prop_rule_name |
637 | 223k | ); |
638 | 223k | if (required.find(prop_name) != required.end()) { |
639 | 202k | required_props.push_back(prop_name); |
640 | 202k | } else { |
641 | 20.5k | optional_props.push_back(prop_name); |
642 | 20.5k | } |
643 | 223k | prop_names.push_back(prop_name); |
644 | 223k | } |
645 | 4.88k | if ((additional_properties.is_boolean() && additional_properties.get<bool>()) || additional_properties.is_object()) { |
646 | 412 | std::string sub_name = name + (name.empty() ? "" : "-") + "additional"; |
647 | 412 | std::string value_rule = |
648 | 412 | additional_properties.is_object() ? visit(additional_properties, sub_name + "-value") |
649 | 412 | : _add_primitive("value", PRIMITIVE_RULES.at("value")); |
650 | | |
651 | 412 | auto key_rule = |
652 | 412 | prop_names.empty() ? _add_primitive("string", PRIMITIVE_RULES.at("string")) |
653 | 412 | : _add_rule(sub_name + "-k", _not_strings(prop_names)); |
654 | 412 | std::string kv_rule = _add_rule(sub_name + "-kv", key_rule + " \":\" space " + value_rule); |
655 | 412 | prop_kv_rule_names["*"] = kv_rule; |
656 | 412 | optional_props.push_back("*"); |
657 | 412 | } |
658 | | |
659 | 4.88k | std::string rule = "\"{\" space "; |
660 | 207k | for (size_t i = 0; i < required_props.size(); i++) { |
661 | 202k | if (i > 0) { |
662 | 201k | rule += " \",\" space "; |
663 | 201k | } |
664 | 202k | rule += prop_kv_rule_names[required_props[i]]; |
665 | 202k | } |
666 | | |
667 | 4.88k | if (!optional_props.empty()) { |
668 | 2.93k | rule += " ("; |
669 | 2.93k | if (!required_props.empty()) { |
670 | 36 | rule += " \",\" space ( "; |
671 | 36 | } |
672 | | |
673 | 873k | std::function<std::string(const std::vector<std::string> &, bool)> get_recursive_refs = [&](const std::vector<std::string> & ks, bool first_is_optional) { |
674 | 873k | std::string res; |
675 | 873k | if (ks.empty()) { |
676 | 0 | return res; |
677 | 0 | } |
678 | 873k | std::string k = ks[0]; |
679 | 873k | std::string kv_rule_name = prop_kv_rule_names[k]; |
680 | 873k | std::string comma_ref = "( \",\" space " + kv_rule_name + " )"; |
681 | 873k | if (first_is_optional) { |
682 | 854k | res = comma_ref + (k == "*" ? "*" : "?"); |
683 | 854k | } else { |
684 | 19.8k | res = kv_rule_name + (k == "*" ? " " + comma_ref + "*" : ""); |
685 | 19.8k | } |
686 | 873k | if (ks.size() > 1) { |
687 | 854k | res += " " + _add_rule( |
688 | 854k | name + (name.empty() ? "" : "-") + k + "-rest", |
689 | 854k | get_recursive_refs(std::vector<std::string>(ks.begin() + 1, ks.end()), true) |
690 | 854k | ); |
691 | 854k | } |
692 | 873k | return res; |
693 | 873k | }; |
694 | | |
695 | 22.7k | for (size_t i = 0; i < optional_props.size(); i++) { |
696 | 19.8k | if (i > 0) { |
697 | 16.8k | rule += " | "; |
698 | 16.8k | } |
699 | 19.8k | rule += get_recursive_refs(std::vector<std::string>(optional_props.begin() + i, optional_props.end()), false); |
700 | 19.8k | } |
701 | 2.93k | if (!required_props.empty()) { |
702 | 36 | rule += " )"; |
703 | 36 | } |
704 | 2.93k | rule += " )?"; |
705 | 2.93k | } |
706 | | |
707 | 4.88k | rule += " \"}\" space"; |
708 | | |
709 | 4.88k | return rule; |
710 | 4.88k | } |
711 | | |
712 | 25.8k | std::string _add_primitive(const std::string & name, const BuiltinRule & rule) { |
713 | 25.8k | auto n = _add_rule(name, rule.content); |
714 | 37.4k | for (const auto & dep : rule.deps) { |
715 | 37.4k | BuiltinRule dep_rule; |
716 | 37.4k | auto it = PRIMITIVE_RULES.find(dep); |
717 | 37.4k | 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 | 37.4k | if (_rules.find(dep) == _rules.end()) { |
725 | 13.7k | _add_primitive(dep, it->second); |
726 | 13.7k | } |
727 | 37.4k | } |
728 | 25.8k | return n; |
729 | 25.8k | } |
730 | | |
731 | | public: |
732 | | SchemaConverter( |
733 | | const std::function<json(const std::string &)> & fetch_json, |
734 | | bool dotall) |
735 | 7.70k | : _fetch_json(fetch_json), _dotall(dotall) |
736 | 7.70k | { |
737 | 7.70k | _rules["space"] = SPACE_RULE; |
738 | 7.70k | } |
739 | | |
740 | 12.1k | 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 | 4.13M | std::function<void(json &)> visit_refs = [&](json & n) { |
747 | 4.13M | if (n.is_array()) { |
748 | 4.05M | for (auto & x : n) { |
749 | 4.05M | visit_refs(x); |
750 | 4.05M | } |
751 | 4.11M | } else if (n.is_object()) { |
752 | 72.6k | if (n.contains("$ref")) { |
753 | 30.2k | std::string ref = n["$ref"]; |
754 | 30.2k | if (_refs.find(ref) == _refs.end()) { |
755 | 24.4k | json target; |
756 | 24.4k | if (ref.find("https://") == 0) { |
757 | 8.10k | std::string base_url = ref.substr(0, ref.find('#')); |
758 | 8.10k | auto it = _refs.find(base_url); |
759 | 8.10k | if (it != _refs.end()) { |
760 | 3.66k | target = it->second; |
761 | 4.43k | } else { |
762 | | // Fetch the referenced schema and resolve its refs |
763 | 4.43k | auto referenced = _fetch_json(ref); |
764 | 4.43k | resolve_refs(referenced, base_url); |
765 | 4.43k | _refs[base_url] = referenced; |
766 | 4.43k | } |
767 | 8.10k | if (ref.find('#') == std::string::npos || ref.substr(ref.find('#') + 1).empty()) { |
768 | 3.24k | return; |
769 | 3.24k | } |
770 | 16.3k | } else if (ref.find("#/") == 0) { |
771 | 3.38k | target = schema; |
772 | 3.38k | n["$ref"] = url + ref; |
773 | 3.38k | ref = url + ref; |
774 | 12.9k | } else { |
775 | 12.9k | _errors.push_back("Unsupported ref: " + ref); |
776 | 12.9k | return; |
777 | 12.9k | } |
778 | 8.23k | std::string pointer = ref.substr(ref.find('#') + 1); |
779 | 8.23k | std::vector<std::string> tokens = string_split(pointer, "/"); |
780 | 9.05k | for (size_t i = 1; i < tokens.size(); ++i) { |
781 | 6.80k | std::string sel = tokens[i]; |
782 | 6.80k | if (target.is_object() && target.contains(sel)) { |
783 | 820 | target = target[sel]; |
784 | 5.98k | } else if (target.is_array()) { |
785 | 851 | size_t sel_index; |
786 | 851 | try { |
787 | 851 | sel_index = std::stoul(sel); |
788 | 851 | } catch (const std::invalid_argument & e) { |
789 | 845 | sel_index = target.size(); |
790 | 845 | } |
791 | 851 | if (sel_index >= target.size()) { |
792 | 849 | _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump()); |
793 | 849 | return; |
794 | 849 | } |
795 | 1 | target = target[sel_index]; |
796 | 5.13k | } else { |
797 | 5.13k | _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump()); |
798 | 5.13k | return; |
799 | 5.13k | } |
800 | 6.80k | } |
801 | 2.25k | _refs[ref] = target; |
802 | 2.25k | } |
803 | 42.4k | } else { |
804 | 60.1k | for (auto & kv : n.items()) { |
805 | 60.1k | visit_refs(kv.value()); |
806 | 60.1k | } |
807 | 42.4k | } |
808 | 72.6k | } |
809 | 4.13M | }; |
810 | | |
811 | 12.1k | visit_refs(schema); |
812 | 12.1k | } |
813 | | |
814 | 16.0k | std::string _generate_constant_rule(const json & value) { |
815 | 16.0k | return format_literal(value.dump()); |
816 | 16.0k | } |
817 | | |
818 | 374k | std::string visit(const json & schema, const std::string & name) { |
819 | 374k | json schema_type = schema.contains("type") ? schema["type"] : json(); |
820 | 374k | std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : ""; |
821 | 374k | std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name; |
822 | | |
823 | 374k | if (schema.contains("$ref")) { |
824 | 14.9k | return _add_rule(rule_name, _resolve_ref(schema["$ref"])); |
825 | 359k | } else if (schema.contains("oneOf") || schema.contains("anyOf")) { |
826 | 580 | std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>(); |
827 | 580 | return _add_rule(rule_name, _generate_union_rule(name, alt_schemas)); |
828 | 358k | } else if (schema_type.is_array()) { |
829 | 4.40k | std::vector<json> schema_types; |
830 | 40.7k | for (const auto & t : schema_type) { |
831 | 40.7k | json schema_copy(schema); |
832 | 40.7k | schema_copy["type"] = t; |
833 | 40.7k | schema_types.push_back(schema_copy); |
834 | 40.7k | } |
835 | 4.40k | return _add_rule(rule_name, _generate_union_rule(name, schema_types)); |
836 | 354k | } else if (schema.contains("const")) { |
837 | 832 | return _add_rule(rule_name, _generate_constant_rule(schema["const"]) + " space"); |
838 | 353k | } else if (schema.contains("enum")) { |
839 | 6.47k | std::vector<std::string> enum_values; |
840 | 11.0k | for (const auto & v : schema["enum"]) { |
841 | 11.0k | enum_values.push_back(_generate_constant_rule(v)); |
842 | 11.0k | } |
843 | 6.47k | return _add_rule(rule_name, "(" + string_join(enum_values, " | ") + ") space"); |
844 | 346k | } else if ((schema_type.is_null() || schema_type == "object") |
845 | 317k | && (schema.contains("properties") || |
846 | 314k | (schema.contains("additionalProperties") && schema["additionalProperties"] != true))) { |
847 | 3.25k | std::unordered_set<std::string> required; |
848 | 3.25k | if (schema.contains("required") && schema["required"].is_array()) { |
849 | 36 | for (const auto & item : schema["required"]) { |
850 | 36 | if (item.is_string()) { |
851 | 0 | required.insert(item.get<std::string>()); |
852 | 0 | } |
853 | 36 | } |
854 | 5 | } |
855 | 3.25k | std::vector<std::pair<std::string, json>> properties; |
856 | 3.25k | if (schema.contains("properties")) { |
857 | 19.3k | for (const auto & prop : schema["properties"].items()) { |
858 | 19.3k | properties.emplace_back(prop.key(), prop.value()); |
859 | 19.3k | } |
860 | 2.55k | } |
861 | 3.25k | return _add_rule(rule_name, |
862 | 3.25k | _build_object_rule( |
863 | 3.25k | properties, required, name, |
864 | 3.25k | schema.contains("additionalProperties") ? schema["additionalProperties"] : json())); |
865 | 343k | } else if ((schema_type.is_null() || schema_type == "object" || schema_type == "string") && schema.contains("allOf")) { |
866 | 1.63k | std::unordered_set<std::string> required; |
867 | 1.63k | std::vector<std::pair<std::string, json>> properties; |
868 | 1.63k | std::map<std::string, size_t> enum_values; |
869 | 1.63k | std::string hybrid_name = name; |
870 | 58.1k | std::function<void(const json &, bool)> add_component = [&](const json & comp_schema, bool is_required) { |
871 | 58.1k | if (comp_schema.contains("$ref")) { |
872 | 12.2k | add_component(_refs[comp_schema["$ref"]], is_required); |
873 | 45.9k | } else if (comp_schema.contains("properties")) { |
874 | 204k | for (const auto & prop : comp_schema["properties"].items()) { |
875 | 204k | properties.emplace_back(prop.key(), prop.value()); |
876 | 204k | if (is_required) { |
877 | 202k | required.insert(prop.key()); |
878 | 202k | } |
879 | 204k | } |
880 | 43.4k | } else if (comp_schema.contains("enum")) { |
881 | 4.20k | for (const auto & v : comp_schema["enum"]) { |
882 | 4.20k | const auto rule = _generate_constant_rule(v); |
883 | 4.20k | if (enum_values.find(rule) == enum_values.end()) { |
884 | 1.37k | enum_values[rule] = 0; |
885 | 1.37k | } |
886 | 4.20k | enum_values[rule] += 1; |
887 | 4.20k | } |
888 | 39.2k | } else { |
889 | | // todo warning |
890 | 39.2k | } |
891 | 58.1k | }; |
892 | 45.0k | for (auto & t : schema["allOf"]) { |
893 | 45.0k | if (t.contains("anyOf")) { |
894 | 1.34k | for (auto & tt : t["anyOf"]) { |
895 | 1.34k | add_component(tt, false); |
896 | 1.34k | } |
897 | 44.6k | } else { |
898 | 44.6k | add_component(t, true); |
899 | 44.6k | } |
900 | 45.0k | } |
901 | 1.63k | if (!enum_values.empty()) { |
902 | 135 | std::vector<std::string> enum_intersection; |
903 | 1.37k | for (const auto & p : enum_values) { |
904 | 1.37k | if (p.second == schema["allOf"].size()) { |
905 | 0 | enum_intersection.push_back(p.first); |
906 | 0 | } |
907 | 1.37k | } |
908 | 135 | if (!enum_intersection.empty()) { |
909 | 0 | return _add_rule(rule_name, "(" + string_join(enum_intersection, " | ") + ") space"); |
910 | 0 | } |
911 | 135 | } |
912 | 1.63k | return _add_rule(rule_name, _build_object_rule(properties, required, hybrid_name, json())); |
913 | 341k | } else if ((schema_type.is_null() || schema_type == "array") && (schema.contains("items") || schema.contains("prefixItems"))) { |
914 | 4.58k | json items = schema.contains("items") ? schema["items"] : schema["prefixItems"]; |
915 | 4.58k | if (items.is_array()) { |
916 | 1.28k | std::string rule = "\"[\" space "; |
917 | 76.9k | for (size_t i = 0; i < items.size(); i++) { |
918 | 75.6k | if (i > 0) { |
919 | 74.3k | rule += " \",\" space "; |
920 | 74.3k | } |
921 | 75.6k | rule += visit(items[i], name + (name.empty() ? "" : "-") + "tuple-" + std::to_string(i)); |
922 | 75.6k | } |
923 | 1.28k | rule += " \"]\" space"; |
924 | 1.28k | return _add_rule(rule_name, rule); |
925 | 3.29k | } else { |
926 | 3.29k | std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item"); |
927 | 3.29k | int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0; |
928 | 3.29k | json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json(); |
929 | 3.29k | int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max(); |
930 | | |
931 | 3.29k | return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space"); |
932 | 3.29k | } |
933 | 337k | } else if ((schema_type.is_null() || schema_type == "string") && schema.contains("pattern")) { |
934 | 5.72k | return _visit_pattern(schema["pattern"], rule_name); |
935 | 331k | } 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 | 331k | } 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 | 331k | } else if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) { |
941 | 7 | std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char")); |
942 | 7 | int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0; |
943 | 7 | int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max(); |
944 | 7 | return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space"); |
945 | 331k | } 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 | 331k | } else if (schema.empty() || schema_type == "object") { |
964 | 10.6k | return _add_rule(rule_name, _add_primitive("object", PRIMITIVE_RULES.at("object"))); |
965 | 320k | } else { |
966 | 320k | if (!schema_type.is_string() || PRIMITIVE_RULES.find(schema_type.get<std::string>()) == PRIMITIVE_RULES.end()) { |
967 | 319k | _errors.push_back("Unrecognized schema: " + schema.dump()); |
968 | 319k | return ""; |
969 | 319k | } |
970 | | // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero |
971 | 1.00k | return _add_primitive(rule_name == "root" ? "root" : schema_type.get<std::string>(), PRIMITIVE_RULES.at(schema_type.get<std::string>())); |
972 | 320k | } |
973 | 374k | } |
974 | | |
975 | 7.59k | void check_errors() { |
976 | 7.59k | if (!_errors.empty()) { |
977 | 6.25k | throw std::invalid_argument("JSON schema conversion failed:\n" + string_join(_errors, "\n")); |
978 | 6.25k | } |
979 | 1.33k | if (!_warnings.empty()) { |
980 | 0 | fprintf(stderr, "WARNING: JSON schema conversion was incomplete: %s\n", string_join(_warnings, "; ").c_str()); |
981 | 0 | } |
982 | 1.33k | } |
983 | | |
984 | 1.33k | std::string format_grammar() { |
985 | 1.33k | std::stringstream ss; |
986 | 16.1k | for (const auto & kv : _rules) { |
987 | 16.1k | ss << kv.first << " ::= " << kv.second << std::endl; |
988 | 16.1k | } |
989 | 1.33k | return ss.str(); |
990 | 1.33k | } |
991 | | }; |
992 | | |
993 | 7.70k | std::string json_schema_to_grammar(const json & schema, bool force_gbnf) { |
994 | | #ifdef LLAMA_USE_LLGUIDANCE |
995 | | if (!force_gbnf) { |
996 | | return "%llguidance {}\nstart: %json " + schema.dump(); |
997 | | } |
998 | | #else |
999 | 7.70k | (void)force_gbnf; |
1000 | 7.70k | #endif // LLAMA_USE_LLGUIDANCE |
1001 | 7.70k | return build_grammar([&](const common_grammar_builder & callbacks) { |
1002 | 7.70k | auto copy = schema; |
1003 | 7.70k | callbacks.resolve_refs(copy); |
1004 | 7.70k | callbacks.add_schema("", copy); |
1005 | 7.70k | }); |
1006 | 7.70k | } |
1007 | | |
1008 | 7.70k | std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options) { |
1009 | 7.70k | SchemaConverter converter([&](const std::string &) { return json(); }, options.dotall); |
1010 | 7.70k | common_grammar_builder builder { |
1011 | 7.70k | /* .add_rule = */ [&](const std::string & name, const std::string & rule) { |
1012 | 0 | return converter._add_rule(name, rule); |
1013 | 0 | }, |
1014 | 7.70k | /* .add_schema = */ [&](const std::string & name, const nlohmann::ordered_json & schema) { |
1015 | 7.68k | return converter.visit(schema, name == "root" ? "" : name); |
1016 | 7.68k | }, |
1017 | 7.70k | /* .resolve_refs = */ [&](nlohmann::ordered_json & schema) { |
1018 | 7.70k | converter.resolve_refs(schema, ""); |
1019 | 7.70k | } |
1020 | 7.70k | }; |
1021 | 7.70k | cb(builder); |
1022 | 7.70k | converter.check_errors(); |
1023 | 7.70k | return converter.format_grammar(); |
1024 | 7.70k | } |