json-schema-to-grammar.cpp 43 KB

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