json-schema-to-grammar.cpp 31 KB

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