json-schema-to-grammar.cpp 42 KB

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