json-schema-to-grammar.cpp 34 KB

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