json-schema-to-grammar.cpp 33 KB

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