json-schema-to-grammar.cpp 42 KB

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