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