json-schema-to-grammar.cpp 42 KB

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