json-schema-to-grammar.cpp 32 KB

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