json-schema-to-grammar.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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::unordered_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. /*
  555. Returns a rule that matches a JSON string that is none of the provided strings
  556. not_strings({"a"})
  557. -> ["] ( [a] char+ | [^"a] char* )? ["] space
  558. not_strings({"and", "also"})
  559. -> ["] ( [a] ([l] ([s] ([o] char+ | [^"o] char*) | [^"s] char*) | [n] ([d] char+ | [^"d] char*) | [^"ln] char*) | [^"a] char* )? ["] space
  560. */
  561. std::string _not_strings(const std::vector<std::string> & strings) {
  562. struct TrieNode {
  563. std::map<char, TrieNode> children;
  564. bool is_end_of_string;
  565. TrieNode() : is_end_of_string(false) {}
  566. void insert(const std::string & string) {
  567. auto node = this;
  568. for (char c : string) {
  569. node = &node->children[c];
  570. }
  571. node->is_end_of_string = true;
  572. }
  573. };
  574. TrieNode trie;
  575. for (const auto & s : strings) {
  576. trie.insert(s);
  577. }
  578. std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
  579. std::ostringstream out;
  580. out << "[\"] ( ";
  581. std::function<void(const TrieNode &)> visit = [&](const TrieNode & node) {
  582. std::ostringstream rejects;
  583. auto first = true;
  584. for (const auto & kv : node.children) {
  585. rejects << kv.first;
  586. if (first) {
  587. first = false;
  588. } else {
  589. out << " | ";
  590. }
  591. out << "[" << kv.first << "]";
  592. if (!kv.second.children.empty()) {
  593. out << " (";
  594. visit(kv.second);
  595. out << ")";
  596. } else if (kv.second.is_end_of_string) {
  597. out << " " << char_rule << "+";
  598. }
  599. }
  600. if (!node.children.empty()) {
  601. if (!first) {
  602. out << " | ";
  603. }
  604. out << "[^\"" << rejects.str() << "] " << char_rule << "*";
  605. }
  606. };
  607. visit(trie);
  608. out << " )";
  609. if (!trie.is_end_of_string) {
  610. out << "?";
  611. }
  612. out << " [\"] space";
  613. return out.str();
  614. }
  615. std::string _resolve_ref(const std::string & ref) {
  616. std::string ref_name = ref.substr(ref.find_last_of('/') + 1);
  617. if (_rules.find(ref_name) == _rules.end() && _refs_being_resolved.find(ref) == _refs_being_resolved.end()) {
  618. _refs_being_resolved.insert(ref);
  619. json resolved = _refs[ref];
  620. ref_name = visit(resolved, ref_name);
  621. _refs_being_resolved.erase(ref);
  622. }
  623. return ref_name;
  624. }
  625. std::string _build_object_rule(
  626. const std::vector<std::pair<std::string, json>> & properties,
  627. const std::unordered_set<std::string> & required,
  628. const std::string & name,
  629. const json & additional_properties)
  630. {
  631. std::vector<std::string> required_props;
  632. std::vector<std::string> optional_props;
  633. std::unordered_map<std::string, std::string> prop_kv_rule_names;
  634. std::vector<std::string> prop_names;
  635. for (const auto & kv : properties) {
  636. const auto &prop_name = kv.first;
  637. const auto &prop_schema = kv.second;
  638. std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name);
  639. prop_kv_rule_names[prop_name] = _add_rule(
  640. name + (name.empty() ? "" : "-") + prop_name + "-kv",
  641. format_literal(json(prop_name).dump()) + " space \":\" space " + prop_rule_name
  642. );
  643. if (required.find(prop_name) != required.end()) {
  644. required_props.push_back(prop_name);
  645. } else {
  646. optional_props.push_back(prop_name);
  647. }
  648. prop_names.push_back(prop_name);
  649. }
  650. if ((additional_properties.is_boolean() && additional_properties.get<bool>()) || additional_properties.is_object()) {
  651. std::string sub_name = name + (name.empty() ? "" : "-") + "additional";
  652. std::string value_rule =
  653. additional_properties.is_object() ? visit(additional_properties, sub_name + "-value")
  654. : _add_primitive("value", PRIMITIVE_RULES.at("value"));
  655. auto key_rule =
  656. prop_names.empty() ? _add_primitive("string", PRIMITIVE_RULES.at("string"))
  657. : _add_rule(sub_name + "-k", _not_strings(prop_names));
  658. std::string kv_rule = _add_rule(sub_name + "-kv", key_rule + " \":\" space " + value_rule);
  659. prop_kv_rule_names["*"] = kv_rule;
  660. optional_props.push_back("*");
  661. }
  662. std::string rule = "\"{\" space ";
  663. for (size_t i = 0; i < required_props.size(); i++) {
  664. if (i > 0) {
  665. rule += " \",\" space ";
  666. }
  667. rule += prop_kv_rule_names[required_props[i]];
  668. }
  669. if (!optional_props.empty()) {
  670. rule += " (";
  671. if (!required_props.empty()) {
  672. rule += " \",\" space ( ";
  673. }
  674. std::function<std::string(const std::vector<std::string> &, bool)> get_recursive_refs = [&](const std::vector<std::string> & ks, bool first_is_optional) {
  675. std::string res;
  676. if (ks.empty()) {
  677. return res;
  678. }
  679. std::string k = ks[0];
  680. std::string kv_rule_name = prop_kv_rule_names[k];
  681. std::string comma_ref = "( \",\" space " + kv_rule_name + " )";
  682. if (first_is_optional) {
  683. res = comma_ref + (k == "*" ? "*" : "?");
  684. } else {
  685. res = kv_rule_name + (k == "*" ? " " + comma_ref + "*" : "");
  686. }
  687. if (ks.size() > 1) {
  688. res += " " + _add_rule(
  689. name + (name.empty() ? "" : "-") + k + "-rest",
  690. get_recursive_refs(std::vector<std::string>(ks.begin() + 1, ks.end()), true)
  691. );
  692. }
  693. return res;
  694. };
  695. for (size_t i = 0; i < optional_props.size(); i++) {
  696. if (i > 0) {
  697. rule += " | ";
  698. }
  699. rule += get_recursive_refs(std::vector<std::string>(optional_props.begin() + i, optional_props.end()), false);
  700. }
  701. if (!required_props.empty()) {
  702. rule += " )";
  703. }
  704. rule += " )?";
  705. }
  706. rule += " \"}\" space";
  707. return rule;
  708. }
  709. std::string _add_primitive(const std::string & name, const BuiltinRule & rule) {
  710. auto n = _add_rule(name, rule.content);
  711. for (const auto & dep : rule.deps) {
  712. BuiltinRule dep_rule;
  713. auto it = PRIMITIVE_RULES.find(dep);
  714. if (it == PRIMITIVE_RULES.end()) {
  715. it = STRING_FORMAT_RULES.find(dep);
  716. if (it == STRING_FORMAT_RULES.end()) {
  717. _errors.push_back("Rule " + dep + " not known");
  718. continue;
  719. }
  720. }
  721. if (_rules.find(dep) == _rules.end()) {
  722. _add_primitive(dep, it->second);
  723. }
  724. }
  725. return n;
  726. }
  727. public:
  728. SchemaConverter(
  729. const std::function<json(const std::string &)> & fetch_json,
  730. bool dotall)
  731. : _fetch_json(fetch_json), _dotall(dotall)
  732. {
  733. _rules["space"] = SPACE_RULE;
  734. }
  735. void resolve_refs(json & schema, const std::string & url) {
  736. /*
  737. * Resolves all $ref fields in the given schema, fetching any remote schemas,
  738. * replacing each $ref with absolute reference URL and populates _refs with the
  739. * respective referenced (sub)schema dictionaries.
  740. */
  741. std::function<void(json &)> visit_refs = [&](json & n) {
  742. if (n.is_array()) {
  743. for (auto & x : n) {
  744. visit_refs(x);
  745. }
  746. } else if (n.is_object()) {
  747. if (n.contains("$ref")) {
  748. std::string ref = n["$ref"];
  749. if (_refs.find(ref) == _refs.end()) {
  750. json target;
  751. if (ref.find("https://") == 0) {
  752. std::string base_url = ref.substr(0, ref.find('#'));
  753. auto it = _refs.find(base_url);
  754. if (it != _refs.end()) {
  755. target = it->second;
  756. } else {
  757. // Fetch the referenced schema and resolve its refs
  758. auto referenced = _fetch_json(ref);
  759. resolve_refs(referenced, base_url);
  760. _refs[base_url] = referenced;
  761. }
  762. if (ref.find('#') == std::string::npos || ref.substr(ref.find('#') + 1).empty()) {
  763. return;
  764. }
  765. } else if (ref.find("#/") == 0) {
  766. target = schema;
  767. n["$ref"] = url + ref;
  768. ref = url + ref;
  769. } else {
  770. _errors.push_back("Unsupported ref: " + ref);
  771. return;
  772. }
  773. std::string pointer = ref.substr(ref.find('#') + 1);
  774. std::vector<std::string> tokens = split(pointer, "/");
  775. for (size_t i = 1; i < tokens.size(); ++i) {
  776. std::string sel = tokens[i];
  777. if (target.is_null() || !target.contains(sel)) {
  778. _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
  779. return;
  780. }
  781. target = target[sel];
  782. }
  783. _refs[ref] = target;
  784. }
  785. } else {
  786. for (auto & kv : n.items()) {
  787. visit_refs(kv.value());
  788. }
  789. }
  790. }
  791. };
  792. visit_refs(schema);
  793. }
  794. std::string _generate_constant_rule(const json & value) {
  795. return format_literal(value.dump());
  796. }
  797. std::string visit(const json & schema, const std::string & name) {
  798. json schema_type = schema.contains("type") ? schema["type"] : json();
  799. std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
  800. std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
  801. if (schema.contains("$ref")) {
  802. return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
  803. } else if (schema.contains("oneOf") || schema.contains("anyOf")) {
  804. std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
  805. return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
  806. } else if (schema_type.is_array()) {
  807. std::vector<json> schema_types;
  808. for (const auto & t : schema_type) {
  809. json schema_copy(schema);
  810. schema_copy["type"] = t;
  811. schema_types.push_back(schema_copy);
  812. }
  813. return _add_rule(rule_name, _generate_union_rule(name, schema_types));
  814. } else if (schema.contains("const")) {
  815. return _add_rule(rule_name, _generate_constant_rule(schema["const"]) + " space");
  816. } else if (schema.contains("enum")) {
  817. std::vector<std::string> enum_values;
  818. for (const auto & v : schema["enum"]) {
  819. enum_values.push_back(_generate_constant_rule(v));
  820. }
  821. return _add_rule(rule_name, "(" + join(enum_values.begin(), enum_values.end(), " | ") + ") space");
  822. } else if ((schema_type.is_null() || schema_type == "object")
  823. && (schema.contains("properties") ||
  824. (schema.contains("additionalProperties") && schema["additionalProperties"] != true))) {
  825. std::unordered_set<std::string> required;
  826. if (schema.contains("required") && schema["required"].is_array()) {
  827. for (const auto & item : schema["required"]) {
  828. if (item.is_string()) {
  829. required.insert(item.get<std::string>());
  830. }
  831. }
  832. }
  833. std::vector<std::pair<std::string, json>> properties;
  834. if (schema.contains("properties")) {
  835. for (const auto & prop : schema["properties"].items()) {
  836. properties.emplace_back(prop.key(), prop.value());
  837. }
  838. }
  839. return _add_rule(rule_name,
  840. _build_object_rule(
  841. properties, required, name,
  842. schema.contains("additionalProperties") ? schema["additionalProperties"] : json()));
  843. } else if ((schema_type.is_null() || schema_type == "object") && schema.contains("allOf")) {
  844. std::unordered_set<std::string> required;
  845. std::vector<std::pair<std::string, json>> properties;
  846. std::string hybrid_name = name;
  847. std::function<void(const json &, bool)> add_component = [&](const json & comp_schema, bool is_required) {
  848. if (comp_schema.contains("$ref")) {
  849. add_component(_refs[comp_schema["$ref"]], is_required);
  850. } else if (comp_schema.contains("properties")) {
  851. for (const auto & prop : comp_schema["properties"].items()) {
  852. properties.emplace_back(prop.key(), prop.value());
  853. if (is_required) {
  854. required.insert(prop.key());
  855. }
  856. }
  857. } else {
  858. // todo warning
  859. }
  860. };
  861. for (auto & t : schema["allOf"]) {
  862. if (t.contains("anyOf")) {
  863. for (auto & tt : t["anyOf"]) {
  864. add_component(tt, false);
  865. }
  866. } else {
  867. add_component(t, true);
  868. }
  869. }
  870. return _add_rule(rule_name, _build_object_rule(properties, required, hybrid_name, json()));
  871. } else if ((schema_type.is_null() || schema_type == "array") && (schema.contains("items") || schema.contains("prefixItems"))) {
  872. json items = schema.contains("items") ? schema["items"] : schema["prefixItems"];
  873. if (items.is_array()) {
  874. std::string rule = "\"[\" space ";
  875. for (size_t i = 0; i < items.size(); i++) {
  876. if (i > 0) {
  877. rule += " \",\" space ";
  878. }
  879. rule += visit(items[i], name + (name.empty() ? "" : "-") + "tuple-" + std::to_string(i));
  880. }
  881. rule += " \"]\" space";
  882. return _add_rule(rule_name, rule);
  883. } else {
  884. std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
  885. int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
  886. json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
  887. int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
  888. return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
  889. }
  890. } else if ((schema_type.is_null() || schema_type == "string") && schema.contains("pattern")) {
  891. return _visit_pattern(schema["pattern"], rule_name);
  892. } else if ((schema_type.is_null() || schema_type == "string") && std::regex_match(schema_format, std::regex("^uuid[1-5]?$"))) {
  893. return _add_primitive(rule_name == "root" ? "root" : schema_format, PRIMITIVE_RULES.at("uuid"));
  894. } else if ((schema_type.is_null() || schema_type == "string") && STRING_FORMAT_RULES.find(schema_format + "-string") != STRING_FORMAT_RULES.end()) {
  895. auto prim_name = schema_format + "-string";
  896. return _add_rule(rule_name, _add_primitive(prim_name, STRING_FORMAT_RULES.at(prim_name)));
  897. } else if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
  898. std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
  899. int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
  900. int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
  901. return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
  902. } else if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
  903. int min_value = std::numeric_limits<int>::min();
  904. int max_value = std::numeric_limits<int>::max();
  905. if (schema.contains("minimum")) {
  906. min_value = schema["minimum"].get<int>();
  907. } else if (schema.contains("exclusiveMinimum")) {
  908. min_value = schema["exclusiveMinimum"].get<int>() + 1;
  909. }
  910. if (schema.contains("maximum")) {
  911. max_value = schema["maximum"].get<int>();
  912. } else if (schema.contains("exclusiveMaximum")) {
  913. max_value = schema["exclusiveMaximum"].get<int>() - 1;
  914. }
  915. std::stringstream out;
  916. out << "(";
  917. _build_min_max_int(min_value, max_value, out);
  918. out << ") space";
  919. return _add_rule(rule_name, out.str());
  920. } else if (schema.empty() || schema_type == "object") {
  921. return _add_rule(rule_name, _add_primitive("object", PRIMITIVE_RULES.at("object")));
  922. } else {
  923. if (!schema_type.is_string() || PRIMITIVE_RULES.find(schema_type.get<std::string>()) == PRIMITIVE_RULES.end()) {
  924. _errors.push_back("Unrecognized schema: " + schema.dump());
  925. return "";
  926. }
  927. // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
  928. return _add_primitive(rule_name == "root" ? "root" : schema_type.get<std::string>(), PRIMITIVE_RULES.at(schema_type.get<std::string>()));
  929. }
  930. }
  931. void check_errors() {
  932. if (!_errors.empty()) {
  933. throw std::runtime_error("JSON schema conversion failed:\n" + join(_errors.begin(), _errors.end(), "\n"));
  934. }
  935. if (!_warnings.empty()) {
  936. fprintf(stderr, "WARNING: JSON schema conversion was incomplete: %s\n", join(_warnings.begin(), _warnings.end(), "; ").c_str());
  937. }
  938. }
  939. std::string format_grammar() {
  940. std::stringstream ss;
  941. for (const auto & kv : _rules) {
  942. ss << kv.first << " ::= " << kv.second << std::endl;
  943. }
  944. return ss.str();
  945. }
  946. };
  947. std::string json_schema_to_grammar(const json & schema) {
  948. SchemaConverter converter([](const std::string &) { return json::object(); }, /* dotall= */ false);
  949. auto copy = schema;
  950. converter.resolve_refs(copy, "input");
  951. converter.visit(copy, "");
  952. converter.check_errors();
  953. return converter.format_grammar();
  954. }