json-schema-to-grammar.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. /**
  2. * llama.cpp - commit 3f1ae2e32cde00c39b96be6d01c2997c29bae555 - 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. /* Minimalistic replacement for std::string_view, which is only available from C++17 onwards */
  61. class string_view {
  62. const std::string & _str;
  63. const size_t _start;
  64. const size_t _end;
  65. public:
  66. string_view(const std::string & str, size_t start = 0, size_t end = std::string::npos) : _str(str), _start(start), _end(end == std::string::npos ? str.length() : end) {}
  67. size_t size() const {
  68. return _end - _start;
  69. }
  70. size_t length() const {
  71. return size();
  72. }
  73. operator std::string() const {
  74. return str();
  75. }
  76. std::string str() const {
  77. return _str.substr(_start, _end - _start);
  78. }
  79. string_view substr(size_t pos, size_t len = std::string::npos) const {
  80. return string_view(_str, _start + pos, len == std::string::npos ? _end : _start + pos + len);
  81. }
  82. char operator[](size_t pos) const {
  83. auto index = _start + pos;
  84. if (index >= _end) {
  85. throw std::out_of_range("string_view index out of range");
  86. }
  87. return _str[_start + pos];
  88. }
  89. bool operator==(const string_view & other) const {
  90. std::string this_str = *this;
  91. std::string other_str = other;
  92. return this_str == other_str;
  93. }
  94. };
  95. static void _build_min_max_int(int min_value, int max_value, std::stringstream & out, int decimals_left = 16, bool top_level = true) {
  96. auto has_min = min_value != std::numeric_limits<int>::min();
  97. auto has_max = max_value != std::numeric_limits<int>::max();
  98. auto digit_range = [&](char from, char to) {
  99. out << "[";
  100. if (from == to) {
  101. out << from;
  102. } else {
  103. out << from << "-" << to;
  104. }
  105. out << "]";
  106. };
  107. auto more_digits = [&](int min_digits, int max_digits) {
  108. out << "[0-9]";
  109. if (min_digits == max_digits && min_digits == 1) {
  110. return;
  111. }
  112. out << "{";
  113. out << min_digits;
  114. if (max_digits != min_digits) {
  115. out << ",";
  116. if (max_digits != std::numeric_limits<int>::max()) {
  117. out << max_digits;
  118. }
  119. }
  120. out << "}";
  121. };
  122. std::function<void(const string_view &, const string_view &)> uniform_range =
  123. [&](const string_view & from, const string_view & to) {
  124. size_t i = 0;
  125. while (i < from.length() && i < to.length() && from[i] == to[i]) {
  126. i++;
  127. }
  128. if (i > 0) {
  129. out << "\"" << from.substr(0, i).str() << "\"";
  130. }
  131. if (i < from.length() && i < to.length()) {
  132. if (i > 0) {
  133. out << " ";
  134. }
  135. auto sub_len = from.length() - i - 1;
  136. if (sub_len > 0) {
  137. auto from_sub = from.substr(i + 1);
  138. auto to_sub = to.substr(i + 1);
  139. auto sub_zeros = repeat("0", sub_len);
  140. auto sub_nines = repeat("9", sub_len);
  141. auto to_reached = false;
  142. out << "(";
  143. if (from_sub == sub_zeros) {
  144. digit_range(from[i], to[i] - 1);
  145. out << " ";
  146. more_digits(sub_len, sub_len);
  147. } else {
  148. out << "[" << from[i] << "] ";
  149. out << "(";
  150. uniform_range(from_sub, sub_nines);
  151. out << ")";
  152. if (from[i] < to[i] - 1) {
  153. out << " | ";
  154. if (to_sub == sub_nines) {
  155. digit_range(from[i] + 1, to[i]);
  156. to_reached = true;
  157. } else {
  158. digit_range(from[i] + 1, to[i] - 1);
  159. }
  160. out << " ";
  161. more_digits(sub_len, sub_len);
  162. }
  163. }
  164. if (!to_reached) {
  165. out << " | ";
  166. digit_range(to[i], to[i]);
  167. out << " ";
  168. uniform_range(sub_zeros, to_sub);
  169. }
  170. out << ")";
  171. } else {
  172. out << "[" << from[i] << "-" << to[i] << "]";
  173. }
  174. }
  175. };
  176. if (has_min && has_max) {
  177. if (min_value < 0 && max_value < 0) {
  178. out << "\"-\" (";
  179. _build_min_max_int(-max_value, -min_value, out, decimals_left, /* top_level= */ true);
  180. out << ")";
  181. return;
  182. }
  183. if (min_value < 0) {
  184. out << "\"-\" (";
  185. _build_min_max_int(0, -min_value, out, decimals_left, /* top_level= */ true);
  186. out << ") | ";
  187. min_value = 0;
  188. }
  189. auto min_s = std::to_string(min_value);
  190. auto max_s = std::to_string(max_value);
  191. auto min_digits = min_s.length();
  192. auto max_digits = max_s.length();
  193. for (auto digits = min_digits; digits < max_digits; digits++) {
  194. uniform_range(min_s, repeat("9", digits));
  195. min_s = "1" + repeat("0", digits);
  196. out << " | ";
  197. }
  198. uniform_range(min_s, max_s);
  199. return;
  200. }
  201. auto less_decimals = std::max(decimals_left - 1, 1);
  202. if (has_min) {
  203. if (min_value < 0) {
  204. out << "\"-\" (";
  205. _build_min_max_int(std::numeric_limits<int>::min(), -min_value, out, decimals_left, /* top_level= */ false);
  206. out << ") | [0] | [1-9] ";
  207. more_digits(0, decimals_left - 1);
  208. } else if (min_value == 0) {
  209. if (top_level) {
  210. out << "[0] | [1-9] ";
  211. more_digits(0, less_decimals);
  212. } else {
  213. more_digits(1, decimals_left);
  214. }
  215. } else if (min_value <= 9) {
  216. char c = '0' + min_value;
  217. auto range_start = top_level ? '1' : '0';
  218. if (c > range_start) {
  219. digit_range(range_start, c - 1);
  220. out << " ";
  221. more_digits(1, less_decimals);
  222. out << " | ";
  223. }
  224. digit_range(c, '9');
  225. out << " ";
  226. more_digits(0, less_decimals);
  227. } else {
  228. auto min_s = std::to_string(min_value);
  229. auto len = min_s.length();
  230. auto c = min_s[0];
  231. if (c > '1') {
  232. digit_range(top_level ? '1' : '0', c - 1);
  233. out << " ";
  234. more_digits(len, less_decimals);
  235. out << " | ";
  236. }
  237. digit_range(c, c);
  238. out << " (";
  239. _build_min_max_int(std::stoi(min_s.substr(1)), std::numeric_limits<int>::max(), out, less_decimals, /* top_level= */ false);
  240. out << ")";
  241. if (c < '9') {
  242. out << " | ";
  243. digit_range(c + 1, '9');
  244. out << " ";
  245. more_digits(len - 1, less_decimals);
  246. }
  247. }
  248. return;
  249. }
  250. if (has_max) {
  251. if (max_value >= 0) {
  252. if (top_level) {
  253. out << "\"-\" [1-9] ";
  254. more_digits(0, less_decimals);
  255. out << " | ";
  256. }
  257. _build_min_max_int(0, max_value, out, decimals_left, /* top_level= */ true);
  258. } else {
  259. out << "\"-\" (";
  260. _build_min_max_int(-max_value, std::numeric_limits<int>::max(), out, decimals_left, /* top_level= */ false);
  261. out << ")";
  262. }
  263. return;
  264. }
  265. throw std::runtime_error("At least one of min_value or max_value must be set");
  266. }
  267. const std::string SPACE_RULE = "| \" \" | \"\\n\" [ \\t]{0,20}";
  268. struct BuiltinRule {
  269. std::string content;
  270. std::vector<std::string> deps;
  271. };
  272. std::unordered_map<std::string, BuiltinRule> PRIMITIVE_RULES = {
  273. {"boolean", {"(\"true\" | \"false\") space", {}}},
  274. {"decimal-part", {"[0-9]{1,16}", {}}},
  275. {"integral-part", {"[0] | [1-9] [0-9]{0,15}", {}}},
  276. {"number", {"(\"-\"? integral-part) (\".\" decimal-part)? ([eE] [-+]? integral-part)? space", {"integral-part", "decimal-part"}}},
  277. {"integer", {"(\"-\"? integral-part) space", {"integral-part"}}},
  278. {"value", {"object | array | string | number | boolean | null", {"object", "array", "string", "number", "boolean", "null"}}},
  279. {"object", {"\"{\" space ( string \":\" space value (\",\" space string \":\" space value)* )? \"}\" space", {"string", "value"}}},
  280. {"array", {"\"[\" space ( value (\",\" space value)* )? \"]\" space", {"value"}}},
  281. {"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", {}}},
  282. {"char", {"[^\"\\\\\\x7F\\x00-\\x1F] | [\\\\] ([\"\\\\bfnrt] | \"u\" [0-9a-fA-F]{4})", {}}},
  283. {"string", {"\"\\\"\" char* \"\\\"\" space", {"char"}}},
  284. {"null", {"\"null\" space", {}}},
  285. };
  286. std::unordered_map<std::string, BuiltinRule> STRING_FORMAT_RULES = {
  287. {"date", {"[0-9]{4} \"-\" ( \"0\" [1-9] | \"1\" [0-2] ) \"-\" ( \"0\" [1-9] | [1-2] [0-9] | \"3\" [0-1] )", {}}},
  288. {"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] )", {}}},
  289. {"date-time", {"date \"T\" time", {"date", "time"}}},
  290. {"date-string", {"\"\\\"\" date \"\\\"\" space", {"date"}}},
  291. {"time-string", {"\"\\\"\" time \"\\\"\" space", {"time"}}},
  292. {"date-time-string", {"\"\\\"\" date-time \"\\\"\" space", {"date-time"}}}
  293. };
  294. static bool is_reserved_name(const std::string & name) {
  295. static std::unordered_set<std::string> RESERVED_NAMES;
  296. if (RESERVED_NAMES.empty()) {
  297. RESERVED_NAMES.insert("root");
  298. for (const auto &p : PRIMITIVE_RULES) RESERVED_NAMES.insert(p.first);
  299. for (const auto &p : STRING_FORMAT_RULES) RESERVED_NAMES.insert(p.first);
  300. }
  301. return RESERVED_NAMES.find(name) != RESERVED_NAMES.end();
  302. }
  303. std::regex INVALID_RULE_CHARS_RE("[^a-zA-Z0-9-]+");
  304. std::regex GRAMMAR_LITERAL_ESCAPE_RE("[\r\n\"]");
  305. std::regex GRAMMAR_RANGE_LITERAL_ESCAPE_RE("[\r\n\"\\]\\-\\\\]");
  306. std::unordered_map<char, std::string> GRAMMAR_LITERAL_ESCAPES = {
  307. {'\r', "\\r"}, {'\n', "\\n"}, {'"', "\\\""}, {'-', "\\-"}, {']', "\\]"}
  308. };
  309. std::unordered_set<char> NON_LITERAL_SET = {'|', '.', '(', ')', '[', ']', '{', '}', '*', '+', '?'};
  310. std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
  311. template <typename Iterator>
  312. std::string join(Iterator begin, Iterator end, const std::string & separator) {
  313. std::ostringstream result;
  314. if (begin != end) {
  315. result << *begin;
  316. for (Iterator it = begin + 1; it != end; ++it) {
  317. result << separator << *it;
  318. }
  319. }
  320. return result.str();
  321. }
  322. static std::vector<std::string> split(const std::string & str, const std::string & delimiter) {
  323. std::vector<std::string> tokens;
  324. size_t start = 0;
  325. size_t end = str.find(delimiter);
  326. while (end != std::string::npos) {
  327. tokens.push_back(str.substr(start, end - start));
  328. start = end + delimiter.length();
  329. end = str.find(delimiter, start);
  330. }
  331. tokens.push_back(str.substr(start));
  332. return tokens;
  333. }
  334. static std::string repeat(const std::string & str, size_t n) {
  335. if (n == 0) {
  336. return "";
  337. }
  338. std::string result;
  339. result.reserve(str.length() * n);
  340. for (size_t i = 0; i < n; ++i) {
  341. result += str;
  342. }
  343. return result;
  344. }
  345. static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) {
  346. std::smatch match;
  347. std::string result;
  348. std::string::const_iterator searchStart(input.cbegin());
  349. std::string::const_iterator searchEnd(input.cend());
  350. while (std::regex_search(searchStart, searchEnd, match, regex)) {
  351. result.append(searchStart, searchStart + match.position());
  352. result.append(replacement(match));
  353. searchStart = match.suffix().first;
  354. }
  355. result.append(searchStart, searchEnd);
  356. return result;
  357. }
  358. static std::string format_literal(const std::string & literal) {
  359. std::string escaped = replacePattern(literal, GRAMMAR_LITERAL_ESCAPE_RE, [&](const std::smatch & match) {
  360. char c = match.str()[0];
  361. return GRAMMAR_LITERAL_ESCAPES.at(c);
  362. });
  363. return "\"" + escaped + "\"";
  364. }
  365. class SchemaConverter {
  366. private:
  367. std::function<json(const std::string &)> _fetch_json;
  368. bool _dotall;
  369. std::map<std::string, std::string> _rules;
  370. std::unordered_map<std::string, json> _refs;
  371. std::unordered_set<std::string> _refs_being_resolved;
  372. std::vector<std::string> _errors;
  373. std::vector<std::string> _warnings;
  374. std::string _add_rule(const std::string & name, const std::string & rule) {
  375. std::string esc_name = regex_replace(name, INVALID_RULE_CHARS_RE, "-");
  376. if (_rules.find(esc_name) == _rules.end() || _rules[esc_name] == rule) {
  377. _rules[esc_name] = rule;
  378. return esc_name;
  379. } else {
  380. int i = 0;
  381. while (_rules.find(esc_name + std::to_string(i)) != _rules.end() && _rules[esc_name + std::to_string(i)] != rule) {
  382. i++;
  383. }
  384. std::string key = esc_name + std::to_string(i);
  385. _rules[key] = rule;
  386. return key;
  387. }
  388. }
  389. std::string _generate_union_rule(const std::string & name, const std::vector<json> & alt_schemas) {
  390. std::vector<std::string> rules;
  391. for (size_t i = 0; i < alt_schemas.size(); i++) {
  392. rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
  393. }
  394. return join(rules.begin(), rules.end(), " | ");
  395. }
  396. std::string _visit_pattern(const std::string & pattern, const std::string & name) {
  397. if (!(pattern.front() == '^' && pattern.back() == '$')) {
  398. _errors.push_back("Pattern must start with '^' and end with '$'");
  399. return "";
  400. }
  401. std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
  402. std::unordered_map<std::string, std::string> sub_rule_ids;
  403. size_t i = 0;
  404. size_t length = sub_pattern.length();
  405. using literal_or_rule = std::pair<std::string, bool>;
  406. auto to_rule = [&](const literal_or_rule & ls) {
  407. auto is_literal = ls.second;
  408. auto s = ls.first;
  409. return is_literal ? "\"" + s + "\"" : s;
  410. };
  411. std::function<literal_or_rule()> transform = [&]() -> literal_or_rule {
  412. size_t start = i;
  413. std::vector<literal_or_rule> seq;
  414. auto get_dot = [&]() {
  415. std::string rule;
  416. if (_dotall) {
  417. rule = "[\\U00000000-\\U0010FFFF]";
  418. } else {
  419. rule = "[^\\x0A\\x0D]";
  420. }
  421. return _add_rule("dot", rule);
  422. };
  423. // Joins the sequence, merging consecutive literals together.
  424. auto join_seq = [&]() {
  425. std::vector<literal_or_rule> ret;
  426. std::string literal;
  427. auto flush_literal = [&]() {
  428. if (literal.empty()) {
  429. return false;
  430. }
  431. ret.emplace_back(literal, true);
  432. literal.clear();
  433. return true;
  434. };
  435. for (const auto & item : seq) {
  436. auto is_literal = item.second;
  437. if (is_literal) {
  438. literal += item.first;
  439. } else {
  440. flush_literal();
  441. ret.push_back(item);
  442. }
  443. }
  444. flush_literal();
  445. std::vector<std::string> results;
  446. for (const auto & item : ret) {
  447. results.push_back(to_rule(item));
  448. }
  449. return std::make_pair(join(results.begin(), results.end(), " "), false);
  450. };
  451. while (i < length) {
  452. char c = sub_pattern[i];
  453. if (c == '.') {
  454. seq.emplace_back(get_dot(), false);
  455. i++;
  456. } else if (c == '(') {
  457. i++;
  458. if (i < length) {
  459. if (sub_pattern[i] == '?') {
  460. _warnings.push_back("Unsupported pattern syntax");
  461. }
  462. }
  463. seq.emplace_back("(" + to_rule(transform()) + ")", false);
  464. } else if (c == ')') {
  465. i++;
  466. if (start > 0 && sub_pattern[start - 1] != '(') {
  467. _errors.push_back("Unbalanced parentheses");
  468. }
  469. return join_seq();
  470. } else if (c == '[') {
  471. std::string square_brackets = std::string(1, c);
  472. i++;
  473. while (i < length && sub_pattern[i] != ']') {
  474. if (sub_pattern[i] == '\\') {
  475. square_brackets += sub_pattern.substr(i, 2);
  476. i += 2;
  477. } else {
  478. square_brackets += sub_pattern[i];
  479. i++;
  480. }
  481. }
  482. if (i >= length) {
  483. _errors.push_back("Unbalanced square brackets");
  484. }
  485. square_brackets += ']';
  486. i++;
  487. seq.emplace_back(square_brackets, false);
  488. } else if (c == '|') {
  489. seq.emplace_back("|", false);
  490. i++;
  491. } else if (c == '*' || c == '+' || c == '?') {
  492. seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
  493. i++;
  494. } else if (c == '{') {
  495. std::string curly_brackets = std::string(1, c);
  496. i++;
  497. while (i < length && sub_pattern[i] != '}') {
  498. curly_brackets += sub_pattern[i];
  499. i++;
  500. }
  501. if (i >= length) {
  502. _errors.push_back("Unbalanced curly brackets");
  503. }
  504. curly_brackets += '}';
  505. i++;
  506. auto nums = split(curly_brackets.substr(1, curly_brackets.length() - 2), ",");
  507. int min_times = 0;
  508. int max_times = std::numeric_limits<int>::max();
  509. try {
  510. if (nums.size() == 1) {
  511. min_times = max_times = std::stoi(nums[0]);
  512. } else if (nums.size() != 2) {
  513. _errors.push_back("Wrong number of values in curly brackets");
  514. } else {
  515. if (!nums[0].empty()) {
  516. min_times = std::stoi(nums[0]);
  517. }
  518. if (!nums[1].empty()) {
  519. max_times = std::stoi(nums[1]);
  520. }
  521. }
  522. } catch (const std::invalid_argument & e) {
  523. _errors.push_back("Invalid number in curly brackets");
  524. return std::make_pair("", false);
  525. }
  526. auto &last = seq.back();
  527. auto &sub = last.first;
  528. auto sub_is_literal = last.second;
  529. if (!sub_is_literal) {
  530. std::string & sub_id = sub_rule_ids[sub];
  531. if (sub_id.empty()) {
  532. sub_id = _add_rule(name + "-" + std::to_string(sub_rule_ids.size()), sub);
  533. }
  534. sub = sub_id;
  535. }
  536. seq.back().first = build_repetition(
  537. sub_is_literal ? "\"" + sub + "\"" : sub,
  538. min_times,
  539. max_times,
  540. ""
  541. );
  542. seq.back().second = false;
  543. } else {
  544. std::string literal;
  545. auto is_non_literal = [&](char c) {
  546. return NON_LITERAL_SET.find(c) != NON_LITERAL_SET.end();
  547. };
  548. while (i < length) {
  549. if (sub_pattern[i] == '\\' && i < length - 1) {
  550. char next = sub_pattern[i + 1];
  551. if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
  552. i++;
  553. literal += sub_pattern[i];
  554. i++;
  555. } else {
  556. literal += sub_pattern.substr(i, 2);
  557. i += 2;
  558. }
  559. } else if (sub_pattern[i] == '"') {
  560. literal += "\\\"";
  561. i++;
  562. } else if (!is_non_literal(sub_pattern[i]) &&
  563. (i == length - 1 || literal.empty() || sub_pattern[i + 1] == '.' || !is_non_literal(sub_pattern[i + 1]))) {
  564. literal += sub_pattern[i];
  565. i++;
  566. } else {
  567. break;
  568. }
  569. }
  570. if (!literal.empty()) {
  571. seq.emplace_back(literal, true);
  572. }
  573. }
  574. }
  575. return join_seq();
  576. };
  577. return _add_rule(name, "\"\\\"\" " + to_rule(transform()) + " \"\\\"\" space");
  578. }
  579. /*
  580. Returns a rule that matches a JSON string that is none of the provided strings
  581. not_strings({"a"})
  582. -> ["] ( [a] char+ | [^"a] char* )? ["] space
  583. not_strings({"and", "also"})
  584. -> ["] ( [a] ([l] ([s] ([o] char+ | [^"o] char*) | [^"s] char*) | [n] ([d] char+ | [^"d] char*) | [^"ln] char*) | [^"a] char* )? ["] space
  585. */
  586. std::string _not_strings(const std::vector<std::string> & strings) {
  587. struct TrieNode {
  588. std::map<char, TrieNode> children;
  589. bool is_end_of_string;
  590. TrieNode() : is_end_of_string(false) {}
  591. void insert(const std::string & string) {
  592. auto node = this;
  593. for (char c : string) {
  594. node = &node->children[c];
  595. }
  596. node->is_end_of_string = true;
  597. }
  598. };
  599. TrieNode trie;
  600. for (const auto & s : strings) {
  601. trie.insert(s);
  602. }
  603. std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
  604. std::ostringstream out;
  605. out << "[\"] ( ";
  606. std::function<void(const TrieNode &)> visit = [&](const TrieNode & node) {
  607. std::ostringstream rejects;
  608. auto first = true;
  609. for (const auto & kv : node.children) {
  610. rejects << kv.first;
  611. if (first) {
  612. first = false;
  613. } else {
  614. out << " | ";
  615. }
  616. out << "[" << kv.first << "]";
  617. if (!kv.second.children.empty()) {
  618. out << " (";
  619. visit(kv.second);
  620. out << ")";
  621. } else if (kv.second.is_end_of_string) {
  622. out << " " << char_rule << "+";
  623. }
  624. }
  625. if (!node.children.empty()) {
  626. if (!first) {
  627. out << " | ";
  628. }
  629. out << "[^\"" << rejects.str() << "] " << char_rule << "*";
  630. }
  631. };
  632. visit(trie);
  633. out << " )";
  634. if (!trie.is_end_of_string) {
  635. out << "?";
  636. }
  637. out << " [\"] space";
  638. return out.str();
  639. }
  640. std::string _resolve_ref(const std::string & ref) {
  641. std::string ref_name = ref.substr(ref.find_last_of('/') + 1);
  642. if (_rules.find(ref_name) == _rules.end() && _refs_being_resolved.find(ref) == _refs_being_resolved.end()) {
  643. _refs_being_resolved.insert(ref);
  644. json resolved = _refs[ref];
  645. ref_name = visit(resolved, ref_name);
  646. _refs_being_resolved.erase(ref);
  647. }
  648. return ref_name;
  649. }
  650. std::string _build_object_rule(
  651. const std::vector<std::pair<std::string, json>> & properties,
  652. const std::unordered_set<std::string> & required,
  653. const std::string & name,
  654. const json & additional_properties)
  655. {
  656. std::vector<std::string> required_props;
  657. std::vector<std::string> optional_props;
  658. std::unordered_map<std::string, std::string> prop_kv_rule_names;
  659. std::vector<std::string> prop_names;
  660. for (const auto & kv : properties) {
  661. const auto &prop_name = kv.first;
  662. const auto &prop_schema = kv.second;
  663. std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name);
  664. prop_kv_rule_names[prop_name] = _add_rule(
  665. name + (name.empty() ? "" : "-") + prop_name + "-kv",
  666. format_literal(json(prop_name).dump()) + " space \":\" space " + prop_rule_name
  667. );
  668. if (required.find(prop_name) != required.end()) {
  669. required_props.push_back(prop_name);
  670. } else {
  671. optional_props.push_back(prop_name);
  672. }
  673. prop_names.push_back(prop_name);
  674. }
  675. if ((additional_properties.is_boolean() && additional_properties.get<bool>()) || additional_properties.is_object()) {
  676. std::string sub_name = name + (name.empty() ? "" : "-") + "additional";
  677. std::string value_rule =
  678. additional_properties.is_object() ? visit(additional_properties, sub_name + "-value")
  679. : _add_primitive("value", PRIMITIVE_RULES.at("value"));
  680. auto key_rule =
  681. prop_names.empty() ? _add_primitive("string", PRIMITIVE_RULES.at("string"))
  682. : _add_rule(sub_name + "-k", _not_strings(prop_names));
  683. std::string kv_rule = _add_rule(sub_name + "-kv", key_rule + " \":\" space " + value_rule);
  684. prop_kv_rule_names["*"] = kv_rule;
  685. optional_props.push_back("*");
  686. }
  687. std::string rule = "\"{\" space ";
  688. for (size_t i = 0; i < required_props.size(); i++) {
  689. if (i > 0) {
  690. rule += " \",\" space ";
  691. }
  692. rule += prop_kv_rule_names[required_props[i]];
  693. }
  694. if (!optional_props.empty()) {
  695. rule += " (";
  696. if (!required_props.empty()) {
  697. rule += " \",\" space ( ";
  698. }
  699. std::function<std::string(const std::vector<std::string> &, bool)> get_recursive_refs = [&](const std::vector<std::string> & ks, bool first_is_optional) {
  700. std::string res;
  701. if (ks.empty()) {
  702. return res;
  703. }
  704. std::string k = ks[0];
  705. std::string kv_rule_name = prop_kv_rule_names[k];
  706. std::string comma_ref = "( \",\" space " + kv_rule_name + " )";
  707. if (first_is_optional) {
  708. res = comma_ref + (k == "*" ? "*" : "?");
  709. } else {
  710. res = kv_rule_name + (k == "*" ? " " + comma_ref + "*" : "");
  711. }
  712. if (ks.size() > 1) {
  713. res += " " + _add_rule(
  714. name + (name.empty() ? "" : "-") + k + "-rest",
  715. get_recursive_refs(std::vector<std::string>(ks.begin() + 1, ks.end()), true)
  716. );
  717. }
  718. return res;
  719. };
  720. for (size_t i = 0; i < optional_props.size(); i++) {
  721. if (i > 0) {
  722. rule += " | ";
  723. }
  724. rule += get_recursive_refs(std::vector<std::string>(optional_props.begin() + i, optional_props.end()), false);
  725. }
  726. if (!required_props.empty()) {
  727. rule += " )";
  728. }
  729. rule += " )?";
  730. }
  731. rule += " \"}\" space";
  732. return rule;
  733. }
  734. std::string _add_primitive(const std::string & name, const BuiltinRule & rule) {
  735. auto n = _add_rule(name, rule.content);
  736. for (const auto & dep : rule.deps) {
  737. BuiltinRule dep_rule;
  738. auto it = PRIMITIVE_RULES.find(dep);
  739. if (it == PRIMITIVE_RULES.end()) {
  740. it = STRING_FORMAT_RULES.find(dep);
  741. if (it == STRING_FORMAT_RULES.end()) {
  742. _errors.push_back("Rule " + dep + " not known");
  743. continue;
  744. }
  745. }
  746. if (_rules.find(dep) == _rules.end()) {
  747. _add_primitive(dep, it->second);
  748. }
  749. }
  750. return n;
  751. }
  752. public:
  753. SchemaConverter(
  754. const std::function<json(const std::string &)> & fetch_json,
  755. bool dotall)
  756. : _fetch_json(fetch_json), _dotall(dotall)
  757. {
  758. _rules["space"] = SPACE_RULE;
  759. }
  760. void resolve_refs(json & schema, const std::string & url) {
  761. /*
  762. * Resolves all $ref fields in the given schema, fetching any remote schemas,
  763. * replacing each $ref with absolute reference URL and populates _refs with the
  764. * respective referenced (sub)schema dictionaries.
  765. */
  766. std::function<void(json &)> visit_refs = [&](json & n) {
  767. if (n.is_array()) {
  768. for (auto & x : n) {
  769. visit_refs(x);
  770. }
  771. } else if (n.is_object()) {
  772. if (n.contains("$ref")) {
  773. std::string ref = n["$ref"];
  774. if (_refs.find(ref) == _refs.end()) {
  775. json target;
  776. if (ref.find("https://") == 0) {
  777. std::string base_url = ref.substr(0, ref.find('#'));
  778. auto it = _refs.find(base_url);
  779. if (it != _refs.end()) {
  780. target = it->second;
  781. } else {
  782. // Fetch the referenced schema and resolve its refs
  783. auto referenced = _fetch_json(ref);
  784. resolve_refs(referenced, base_url);
  785. _refs[base_url] = referenced;
  786. }
  787. if (ref.find('#') == std::string::npos || ref.substr(ref.find('#') + 1).empty()) {
  788. return;
  789. }
  790. } else if (ref.find("#/") == 0) {
  791. target = schema;
  792. n["$ref"] = url + ref;
  793. ref = url + ref;
  794. } else {
  795. _errors.push_back("Unsupported ref: " + ref);
  796. return;
  797. }
  798. std::string pointer = ref.substr(ref.find('#') + 1);
  799. std::vector<std::string> tokens = split(pointer, "/");
  800. for (size_t i = 1; i < tokens.size(); ++i) {
  801. std::string sel = tokens[i];
  802. if (target.is_null() || !target.contains(sel)) {
  803. _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
  804. return;
  805. }
  806. target = target[sel];
  807. }
  808. _refs[ref] = target;
  809. }
  810. } else {
  811. for (auto & kv : n.items()) {
  812. visit_refs(kv.value());
  813. }
  814. }
  815. }
  816. };
  817. visit_refs(schema);
  818. }
  819. std::string _generate_constant_rule(const json & value) {
  820. return format_literal(value.dump());
  821. }
  822. std::string visit(const json & schema, const std::string & name) {
  823. json schema_type = schema.contains("type") ? schema["type"] : json();
  824. std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
  825. std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
  826. if (schema.contains("$ref")) {
  827. return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
  828. } else if (schema.contains("oneOf") || schema.contains("anyOf")) {
  829. std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
  830. return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
  831. } else if (schema_type.is_array()) {
  832. std::vector<json> schema_types;
  833. for (const auto & t : schema_type) {
  834. json schema_copy(schema);
  835. schema_copy["type"] = t;
  836. schema_types.push_back(schema_copy);
  837. }
  838. return _add_rule(rule_name, _generate_union_rule(name, schema_types));
  839. } else if (schema.contains("const")) {
  840. return _add_rule(rule_name, _generate_constant_rule(schema["const"]) + " space");
  841. } else if (schema.contains("enum")) {
  842. std::vector<std::string> enum_values;
  843. for (const auto & v : schema["enum"]) {
  844. enum_values.push_back(_generate_constant_rule(v));
  845. }
  846. return _add_rule(rule_name, "(" + join(enum_values.begin(), enum_values.end(), " | ") + ") space");
  847. } else if ((schema_type.is_null() || schema_type == "object")
  848. && (schema.contains("properties") ||
  849. (schema.contains("additionalProperties") && schema["additionalProperties"] != true))) {
  850. std::unordered_set<std::string> required;
  851. if (schema.contains("required") && schema["required"].is_array()) {
  852. for (const auto & item : schema["required"]) {
  853. if (item.is_string()) {
  854. required.insert(item.get<std::string>());
  855. }
  856. }
  857. }
  858. std::vector<std::pair<std::string, json>> properties;
  859. if (schema.contains("properties")) {
  860. for (const auto & prop : schema["properties"].items()) {
  861. properties.emplace_back(prop.key(), prop.value());
  862. }
  863. }
  864. return _add_rule(rule_name,
  865. _build_object_rule(
  866. properties, required, name,
  867. schema.contains("additionalProperties") ? schema["additionalProperties"] : json()));
  868. } else if ((schema_type.is_null() || schema_type == "object") && schema.contains("allOf")) {
  869. std::unordered_set<std::string> required;
  870. std::vector<std::pair<std::string, json>> properties;
  871. std::string hybrid_name = name;
  872. std::function<void(const json &, bool)> add_component = [&](const json & comp_schema, bool is_required) {
  873. if (comp_schema.contains("$ref")) {
  874. add_component(_refs[comp_schema["$ref"]], is_required);
  875. } else if (comp_schema.contains("properties")) {
  876. for (const auto & prop : comp_schema["properties"].items()) {
  877. properties.emplace_back(prop.key(), prop.value());
  878. if (is_required) {
  879. required.insert(prop.key());
  880. }
  881. }
  882. } else {
  883. // todo warning
  884. }
  885. };
  886. for (auto & t : schema["allOf"]) {
  887. if (t.contains("anyOf")) {
  888. for (auto & tt : t["anyOf"]) {
  889. add_component(tt, false);
  890. }
  891. } else {
  892. add_component(t, true);
  893. }
  894. }
  895. return _add_rule(rule_name, _build_object_rule(properties, required, hybrid_name, json()));
  896. } else if ((schema_type.is_null() || schema_type == "array") && (schema.contains("items") || schema.contains("prefixItems"))) {
  897. json items = schema.contains("items") ? schema["items"] : schema["prefixItems"];
  898. if (items.is_array()) {
  899. std::string rule = "\"[\" space ";
  900. for (size_t i = 0; i < items.size(); i++) {
  901. if (i > 0) {
  902. rule += " \",\" space ";
  903. }
  904. rule += visit(items[i], name + (name.empty() ? "" : "-") + "tuple-" + std::to_string(i));
  905. }
  906. rule += " \"]\" space";
  907. return _add_rule(rule_name, rule);
  908. } else {
  909. std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
  910. int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
  911. json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
  912. int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
  913. return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
  914. }
  915. } else if ((schema_type.is_null() || schema_type == "string") && schema.contains("pattern")) {
  916. return _visit_pattern(schema["pattern"], rule_name);
  917. } else if ((schema_type.is_null() || schema_type == "string") && std::regex_match(schema_format, std::regex("^uuid[1-5]?$"))) {
  918. return _add_primitive(rule_name == "root" ? "root" : schema_format, PRIMITIVE_RULES.at("uuid"));
  919. } else if ((schema_type.is_null() || schema_type == "string") && STRING_FORMAT_RULES.find(schema_format + "-string") != STRING_FORMAT_RULES.end()) {
  920. auto prim_name = schema_format + "-string";
  921. return _add_rule(rule_name, _add_primitive(prim_name, STRING_FORMAT_RULES.at(prim_name)));
  922. } else if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
  923. std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
  924. int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
  925. int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
  926. return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
  927. } else if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
  928. int min_value = std::numeric_limits<int>::min();
  929. int max_value = std::numeric_limits<int>::max();
  930. if (schema.contains("minimum")) {
  931. min_value = schema["minimum"].get<int>();
  932. } else if (schema.contains("exclusiveMinimum")) {
  933. min_value = schema["exclusiveMinimum"].get<int>() + 1;
  934. }
  935. if (schema.contains("maximum")) {
  936. max_value = schema["maximum"].get<int>();
  937. } else if (schema.contains("exclusiveMaximum")) {
  938. max_value = schema["exclusiveMaximum"].get<int>() - 1;
  939. }
  940. std::stringstream out;
  941. out << "(";
  942. _build_min_max_int(min_value, max_value, out);
  943. out << ") space";
  944. return _add_rule(rule_name, out.str());
  945. } else if (schema.empty() || schema_type == "object") {
  946. return _add_rule(rule_name, _add_primitive("object", PRIMITIVE_RULES.at("object")));
  947. } else {
  948. if (!schema_type.is_string() || PRIMITIVE_RULES.find(schema_type.get<std::string>()) == PRIMITIVE_RULES.end()) {
  949. _errors.push_back("Unrecognized schema: " + schema.dump());
  950. return "";
  951. }
  952. // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
  953. return _add_primitive(rule_name == "root" ? "root" : schema_type.get<std::string>(), PRIMITIVE_RULES.at(schema_type.get<std::string>()));
  954. }
  955. }
  956. void check_errors() {
  957. if (!_errors.empty()) {
  958. throw std::runtime_error("JSON schema conversion failed:\n" + join(_errors.begin(), _errors.end(), "\n"));
  959. }
  960. if (!_warnings.empty()) {
  961. fprintf(stderr, "WARNING: JSON schema conversion was incomplete: %s\n", join(_warnings.begin(), _warnings.end(), "; ").c_str());
  962. }
  963. }
  964. std::string format_grammar() {
  965. std::stringstream ss;
  966. for (const auto & kv : _rules) {
  967. ss << kv.first << " ::= " << kv.second << std::endl;
  968. }
  969. return ss.str();
  970. }
  971. };
  972. std::string json_schema_to_grammar(const json & schema) {
  973. SchemaConverter converter([](const std::string &) { return json::object(); }, /* dotall= */ false);
  974. auto copy = schema;
  975. converter.resolve_refs(copy, "input");
  976. converter.visit(copy, "");
  977. converter.check_errors();
  978. return converter.format_grammar();
  979. }