json-schema-to-grammar.cpp 33 KB

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