json-schema-to-grammar.cpp 40 KB

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