1
0

json-schema-to-grammar.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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. std::string gbnf_format_literal(const std::string & literal) { return format_literal(literal); }
  274. class SchemaConverter {
  275. private:
  276. friend std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options);
  277. std::function<json(const std::string &)> _fetch_json;
  278. bool _dotall;
  279. std::map<std::string, std::string> _rules;
  280. std::unordered_map<std::string, json> _refs;
  281. std::unordered_set<std::string> _refs_being_resolved;
  282. std::vector<std::string> _errors;
  283. std::vector<std::string> _warnings;
  284. std::string _add_rule(const std::string & name, const std::string & rule) {
  285. std::string esc_name = regex_replace(name, INVALID_RULE_CHARS_RE, "-");
  286. if (_rules.find(esc_name) == _rules.end() || _rules[esc_name] == rule) {
  287. _rules[esc_name] = rule;
  288. return esc_name;
  289. } else {
  290. int i = 0;
  291. while (_rules.find(esc_name + std::to_string(i)) != _rules.end() && _rules[esc_name + std::to_string(i)] != rule) {
  292. i++;
  293. }
  294. std::string key = esc_name + std::to_string(i);
  295. _rules[key] = rule;
  296. return key;
  297. }
  298. }
  299. std::string _generate_union_rule(const std::string & name, const std::vector<json> & alt_schemas) {
  300. std::vector<std::string> rules;
  301. for (size_t i = 0; i < alt_schemas.size(); i++) {
  302. rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
  303. }
  304. return string_join(rules, " | ");
  305. }
  306. std::string _visit_pattern(const std::string & pattern, const std::string & name) {
  307. if (!(pattern.front() == '^' && pattern.back() == '$')) {
  308. _errors.push_back("Pattern must start with '^' and end with '$'");
  309. return "";
  310. }
  311. std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
  312. std::unordered_map<std::string, std::string> sub_rule_ids;
  313. size_t i = 0;
  314. size_t length = sub_pattern.length();
  315. using literal_or_rule = std::pair<std::string, bool>;
  316. auto to_rule = [&](const literal_or_rule & ls) {
  317. auto is_literal = ls.second;
  318. auto s = ls.first;
  319. return is_literal ? "\"" + s + "\"" : s;
  320. };
  321. std::function<literal_or_rule()> transform = [&]() -> literal_or_rule {
  322. size_t start = i;
  323. std::vector<literal_or_rule> seq;
  324. auto get_dot = [&]() {
  325. std::string rule;
  326. if (_dotall) {
  327. rule = "[\\U00000000-\\U0010FFFF]";
  328. } else {
  329. rule = "[^\\x0A\\x0D]";
  330. }
  331. return _add_rule("dot", rule);
  332. };
  333. // Joins the sequence, merging consecutive literals together.
  334. auto join_seq = [&]() {
  335. std::vector<literal_or_rule> ret;
  336. std::string literal;
  337. auto flush_literal = [&]() {
  338. if (literal.empty()) {
  339. return false;
  340. }
  341. ret.emplace_back(literal, true);
  342. literal.clear();
  343. return true;
  344. };
  345. for (const auto & item : seq) {
  346. auto is_literal = item.second;
  347. if (is_literal) {
  348. literal += item.first;
  349. } else {
  350. flush_literal();
  351. ret.push_back(item);
  352. }
  353. }
  354. flush_literal();
  355. std::vector<std::string> results;
  356. for (const auto & item : ret) {
  357. results.push_back(to_rule(item));
  358. }
  359. return std::make_pair(string_join(results, " "), false);
  360. };
  361. while (i < length) {
  362. char c = sub_pattern[i];
  363. if (c == '.') {
  364. seq.emplace_back(get_dot(), false);
  365. i++;
  366. } else if (c == '(') {
  367. i++;
  368. if (i < length) {
  369. if (sub_pattern[i] == '?') {
  370. _warnings.push_back("Unsupported pattern syntax");
  371. }
  372. }
  373. seq.emplace_back("(" + to_rule(transform()) + ")", false);
  374. } else if (c == ')') {
  375. i++;
  376. if (start > 0 && sub_pattern[start - 1] != '(') {
  377. _errors.push_back("Unbalanced parentheses");
  378. }
  379. return join_seq();
  380. } else if (c == '[') {
  381. std::string square_brackets = std::string(1, c);
  382. i++;
  383. while (i < length && sub_pattern[i] != ']') {
  384. if (sub_pattern[i] == '\\') {
  385. square_brackets += sub_pattern.substr(i, 2);
  386. i += 2;
  387. } else {
  388. square_brackets += sub_pattern[i];
  389. i++;
  390. }
  391. }
  392. if (i >= length) {
  393. _errors.push_back("Unbalanced square brackets");
  394. }
  395. square_brackets += ']';
  396. i++;
  397. seq.emplace_back(square_brackets, false);
  398. } else if (c == '|') {
  399. seq.emplace_back("|", false);
  400. i++;
  401. } else if (c == '*' || c == '+' || c == '?') {
  402. seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
  403. i++;
  404. } else if (c == '{') {
  405. std::string curly_brackets = std::string(1, c);
  406. i++;
  407. while (i < length && sub_pattern[i] != '}') {
  408. curly_brackets += sub_pattern[i];
  409. i++;
  410. }
  411. if (i >= length) {
  412. _errors.push_back("Unbalanced curly brackets");
  413. }
  414. curly_brackets += '}';
  415. i++;
  416. auto nums = string_split(curly_brackets.substr(1, curly_brackets.length() - 2), ",");
  417. int min_times = 0;
  418. int max_times = std::numeric_limits<int>::max();
  419. try {
  420. if (nums.size() == 1) {
  421. min_times = max_times = std::stoi(nums[0]);
  422. } else if (nums.size() != 2) {
  423. _errors.push_back("Wrong number of values in curly brackets");
  424. } else {
  425. if (!nums[0].empty()) {
  426. min_times = std::stoi(nums[0]);
  427. }
  428. if (!nums[1].empty()) {
  429. max_times = std::stoi(nums[1]);
  430. }
  431. }
  432. } catch (const std::invalid_argument & e) {
  433. _errors.push_back("Invalid number in curly brackets");
  434. return std::make_pair("", false);
  435. }
  436. auto &last = seq.back();
  437. auto &sub = last.first;
  438. auto sub_is_literal = last.second;
  439. if (!sub_is_literal) {
  440. std::string & sub_id = sub_rule_ids[sub];
  441. if (sub_id.empty()) {
  442. sub_id = _add_rule(name + "-" + std::to_string(sub_rule_ids.size()), sub);
  443. }
  444. sub = sub_id;
  445. }
  446. seq.back().first = build_repetition(
  447. sub_is_literal ? "\"" + sub + "\"" : sub,
  448. min_times,
  449. max_times,
  450. ""
  451. );
  452. seq.back().second = false;
  453. } else {
  454. std::string literal;
  455. auto is_non_literal = [&](char c) {
  456. return NON_LITERAL_SET.find(c) != NON_LITERAL_SET.end();
  457. };
  458. while (i < length) {
  459. if (sub_pattern[i] == '\\' && i < length - 1) {
  460. char next = sub_pattern[i + 1];
  461. if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
  462. i++;
  463. literal += sub_pattern[i];
  464. i++;
  465. } else {
  466. literal += sub_pattern.substr(i, 2);
  467. i += 2;
  468. }
  469. } else if (sub_pattern[i] == '"') {
  470. literal += "\\\"";
  471. i++;
  472. } else if (!is_non_literal(sub_pattern[i]) &&
  473. (i == length - 1 || literal.empty() || sub_pattern[i + 1] == '.' || !is_non_literal(sub_pattern[i + 1]))) {
  474. literal += sub_pattern[i];
  475. i++;
  476. } else {
  477. break;
  478. }
  479. }
  480. if (!literal.empty()) {
  481. seq.emplace_back(literal, true);
  482. }
  483. }
  484. }
  485. return join_seq();
  486. };
  487. return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\" space");
  488. }
  489. /*
  490. Returns a rule that matches a JSON string that is none of the provided strings
  491. not_strings({"a"})
  492. -> ["] ( [a] char+ | [^"a] char* )? ["] space
  493. not_strings({"and", "also"})
  494. -> ["] ( [a] ([l] ([s] ([o] char+ | [^"o] char*) | [^"s] char*) | [n] ([d] char+ | [^"d] char*) | [^"ln] char*) | [^"a] char* )? ["] space
  495. */
  496. std::string _not_strings(const std::vector<std::string> & strings) {
  497. struct TrieNode {
  498. std::map<char, TrieNode> children;
  499. bool is_end_of_string;
  500. TrieNode() : is_end_of_string(false) {}
  501. void insert(const std::string & string) {
  502. auto node = this;
  503. for (char c : string) {
  504. node = &node->children[c];
  505. }
  506. node->is_end_of_string = true;
  507. }
  508. };
  509. TrieNode trie;
  510. for (const auto & s : strings) {
  511. trie.insert(s);
  512. }
  513. std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
  514. std::ostringstream out;
  515. out << "[\"] ( ";
  516. std::function<void(const TrieNode &)> visit = [&](const TrieNode & node) {
  517. std::ostringstream rejects;
  518. auto first = true;
  519. for (const auto & kv : node.children) {
  520. rejects << kv.first;
  521. if (first) {
  522. first = false;
  523. } else {
  524. out << " | ";
  525. }
  526. out << "[" << kv.first << "]";
  527. if (!kv.second.children.empty()) {
  528. out << " (";
  529. visit(kv.second);
  530. out << ")";
  531. } else if (kv.second.is_end_of_string) {
  532. out << " " << char_rule << "+";
  533. }
  534. }
  535. if (!node.children.empty()) {
  536. if (!first) {
  537. out << " | ";
  538. }
  539. out << "[^\"" << rejects.str() << "] " << char_rule << "*";
  540. }
  541. };
  542. visit(trie);
  543. out << " )";
  544. if (!trie.is_end_of_string) {
  545. out << "?";
  546. }
  547. out << " [\"] space";
  548. return out.str();
  549. }
  550. std::string _resolve_ref(const std::string & ref) {
  551. auto it = ref.find('#');
  552. std::string ref_fragment = it != std::string::npos ? ref.substr(it + 1) : ref;
  553. static const std::regex nonalphanumeric_regex(R"([^a-zA-Z0-9-]+)");
  554. std::string ref_name = "ref" + std::regex_replace(ref_fragment, nonalphanumeric_regex, "-");
  555. if (_rules.find(ref_name) == _rules.end() && _refs_being_resolved.find(ref) == _refs_being_resolved.end()) {
  556. _refs_being_resolved.insert(ref);
  557. json resolved = _refs[ref];
  558. ref_name = visit(resolved, ref_name);
  559. _refs_being_resolved.erase(ref);
  560. }
  561. return ref_name;
  562. }
  563. std::string _build_object_rule(
  564. const std::vector<std::pair<std::string, json>> & properties,
  565. const std::unordered_set<std::string> & required,
  566. const std::string & name,
  567. const json & additional_properties)
  568. {
  569. std::vector<std::string> required_props;
  570. std::vector<std::string> optional_props;
  571. std::unordered_map<std::string, std::string> prop_kv_rule_names;
  572. std::vector<std::string> prop_names;
  573. for (const auto & kv : properties) {
  574. const auto &prop_name = kv.first;
  575. const auto &prop_schema = kv.second;
  576. std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name);
  577. prop_kv_rule_names[prop_name] = _add_rule(
  578. name + (name.empty() ? "" : "-") + prop_name + "-kv",
  579. format_literal(json(prop_name).dump()) + " space \":\" space " + prop_rule_name
  580. );
  581. if (required.find(prop_name) != required.end()) {
  582. required_props.push_back(prop_name);
  583. } else {
  584. optional_props.push_back(prop_name);
  585. }
  586. prop_names.push_back(prop_name);
  587. }
  588. if ((additional_properties.is_boolean() && additional_properties.get<bool>()) || additional_properties.is_object()) {
  589. std::string sub_name = name + (name.empty() ? "" : "-") + "additional";
  590. std::string value_rule =
  591. additional_properties.is_object() ? visit(additional_properties, sub_name + "-value")
  592. : _add_primitive("value", PRIMITIVE_RULES.at("value"));
  593. auto key_rule =
  594. prop_names.empty() ? _add_primitive("string", PRIMITIVE_RULES.at("string"))
  595. : _add_rule(sub_name + "-k", _not_strings(prop_names));
  596. std::string kv_rule = _add_rule(sub_name + "-kv", key_rule + " \":\" space " + value_rule);
  597. prop_kv_rule_names["*"] = kv_rule;
  598. optional_props.push_back("*");
  599. }
  600. std::string rule = "\"{\" space ";
  601. for (size_t i = 0; i < required_props.size(); i++) {
  602. if (i > 0) {
  603. rule += " \",\" space ";
  604. }
  605. rule += prop_kv_rule_names[required_props[i]];
  606. }
  607. if (!optional_props.empty()) {
  608. rule += " (";
  609. if (!required_props.empty()) {
  610. rule += " \",\" space ( ";
  611. }
  612. std::function<std::string(const std::vector<std::string> &, bool)> get_recursive_refs = [&](const std::vector<std::string> & ks, bool first_is_optional) {
  613. std::string res;
  614. if (ks.empty()) {
  615. return res;
  616. }
  617. std::string k = ks[0];
  618. std::string kv_rule_name = prop_kv_rule_names[k];
  619. std::string comma_ref = "( \",\" space " + kv_rule_name + " )";
  620. if (first_is_optional) {
  621. res = comma_ref + (k == "*" ? "*" : "?");
  622. } else {
  623. res = kv_rule_name + (k == "*" ? " " + comma_ref + "*" : "");
  624. }
  625. if (ks.size() > 1) {
  626. res += " " + _add_rule(
  627. name + (name.empty() ? "" : "-") + k + "-rest",
  628. get_recursive_refs(std::vector<std::string>(ks.begin() + 1, ks.end()), true)
  629. );
  630. }
  631. return res;
  632. };
  633. for (size_t i = 0; i < optional_props.size(); i++) {
  634. if (i > 0) {
  635. rule += " | ";
  636. }
  637. rule += get_recursive_refs(std::vector<std::string>(optional_props.begin() + i, optional_props.end()), false);
  638. }
  639. if (!required_props.empty()) {
  640. rule += " )";
  641. }
  642. rule += " )?";
  643. }
  644. rule += " \"}\" space";
  645. return rule;
  646. }
  647. std::string _add_primitive(const std::string & name, const BuiltinRule & rule) {
  648. auto n = _add_rule(name, rule.content);
  649. for (const auto & dep : rule.deps) {
  650. BuiltinRule dep_rule;
  651. auto it = PRIMITIVE_RULES.find(dep);
  652. if (it == PRIMITIVE_RULES.end()) {
  653. it = STRING_FORMAT_RULES.find(dep);
  654. if (it == STRING_FORMAT_RULES.end()) {
  655. _errors.push_back("Rule " + dep + " not known");
  656. continue;
  657. }
  658. }
  659. if (_rules.find(dep) == _rules.end()) {
  660. _add_primitive(dep, it->second);
  661. }
  662. }
  663. return n;
  664. }
  665. public:
  666. SchemaConverter(
  667. const std::function<json(const std::string &)> & fetch_json,
  668. bool dotall)
  669. : _fetch_json(fetch_json), _dotall(dotall)
  670. {
  671. _rules["space"] = SPACE_RULE;
  672. }
  673. void resolve_refs(json & schema, const std::string & url) {
  674. /*
  675. * Resolves all $ref fields in the given schema, fetching any remote schemas,
  676. * replacing each $ref with absolute reference URL and populates _refs with the
  677. * respective referenced (sub)schema dictionaries.
  678. */
  679. std::function<void(json &)> visit_refs = [&](json & n) {
  680. if (n.is_array()) {
  681. for (auto & x : n) {
  682. visit_refs(x);
  683. }
  684. } else if (n.is_object()) {
  685. if (n.contains("$ref")) {
  686. std::string ref = n["$ref"];
  687. if (_refs.find(ref) == _refs.end()) {
  688. json target;
  689. if (ref.find("https://") == 0) {
  690. std::string base_url = ref.substr(0, ref.find('#'));
  691. auto it = _refs.find(base_url);
  692. if (it != _refs.end()) {
  693. target = it->second;
  694. } else {
  695. // Fetch the referenced schema and resolve its refs
  696. auto referenced = _fetch_json(ref);
  697. resolve_refs(referenced, base_url);
  698. _refs[base_url] = referenced;
  699. }
  700. if (ref.find('#') == std::string::npos || ref.substr(ref.find('#') + 1).empty()) {
  701. return;
  702. }
  703. } else if (ref.find("#/") == 0) {
  704. target = schema;
  705. n["$ref"] = url + ref;
  706. ref = url + ref;
  707. } else {
  708. _errors.push_back("Unsupported ref: " + ref);
  709. return;
  710. }
  711. std::string pointer = ref.substr(ref.find('#') + 1);
  712. std::vector<std::string> tokens = string_split(pointer, "/");
  713. for (size_t i = 1; i < tokens.size(); ++i) {
  714. std::string sel = tokens[i];
  715. if (target.is_object() && target.contains(sel)) {
  716. target = target[sel];
  717. } else if (target.is_array()) {
  718. size_t sel_index;
  719. try {
  720. sel_index = std::stoul(sel);
  721. } catch (const std::invalid_argument & e) {
  722. sel_index = target.size();
  723. }
  724. if (sel_index >= target.size()) {
  725. _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
  726. return;
  727. }
  728. target = target[sel_index];
  729. } else {
  730. _errors.push_back("Error resolving ref " + ref + ": " + sel + " not in " + target.dump());
  731. return;
  732. }
  733. }
  734. _refs[ref] = target;
  735. }
  736. } else {
  737. for (auto & kv : n.items()) {
  738. visit_refs(kv.value());
  739. }
  740. }
  741. }
  742. };
  743. visit_refs(schema);
  744. }
  745. std::string _generate_constant_rule(const json & value) {
  746. return format_literal(value.dump());
  747. }
  748. std::string visit(const json & schema, const std::string & name) {
  749. json schema_type = schema.contains("type") ? schema["type"] : json();
  750. std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
  751. std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
  752. if (schema.contains("$ref")) {
  753. return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
  754. } else if (schema.contains("oneOf") || schema.contains("anyOf")) {
  755. std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
  756. return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
  757. } else if (schema_type.is_array()) {
  758. std::vector<json> schema_types;
  759. for (const auto & t : schema_type) {
  760. json schema_copy(schema);
  761. schema_copy["type"] = t;
  762. schema_types.push_back(schema_copy);
  763. }
  764. return _add_rule(rule_name, _generate_union_rule(name, schema_types));
  765. } else if (schema.contains("const")) {
  766. return _add_rule(rule_name, _generate_constant_rule(schema["const"]) + " space");
  767. } else if (schema.contains("enum")) {
  768. std::vector<std::string> enum_values;
  769. for (const auto & v : schema["enum"]) {
  770. enum_values.push_back(_generate_constant_rule(v));
  771. }
  772. return _add_rule(rule_name, "(" + string_join(enum_values, " | ") + ") space");
  773. } else if ((schema_type.is_null() || schema_type == "object")
  774. && (schema.contains("properties") ||
  775. (schema.contains("additionalProperties") && schema["additionalProperties"] != true))) {
  776. std::unordered_set<std::string> required;
  777. if (schema.contains("required") && schema["required"].is_array()) {
  778. for (const auto & item : schema["required"]) {
  779. if (item.is_string()) {
  780. required.insert(item.get<std::string>());
  781. }
  782. }
  783. }
  784. std::vector<std::pair<std::string, json>> properties;
  785. if (schema.contains("properties")) {
  786. for (const auto & prop : schema["properties"].items()) {
  787. properties.emplace_back(prop.key(), prop.value());
  788. }
  789. }
  790. return _add_rule(rule_name,
  791. _build_object_rule(
  792. properties, required, name,
  793. schema.contains("additionalProperties") ? schema["additionalProperties"] : json()));
  794. } else if ((schema_type.is_null() || schema_type == "object" || schema_type == "string") && schema.contains("allOf")) {
  795. std::unordered_set<std::string> required;
  796. std::vector<std::pair<std::string, json>> properties;
  797. std::map<std::string, size_t> enum_values;
  798. std::string hybrid_name = name;
  799. std::function<void(const json &, bool)> add_component = [&](const json & comp_schema, bool is_required) {
  800. if (comp_schema.contains("$ref")) {
  801. add_component(_refs[comp_schema["$ref"]], is_required);
  802. } else if (comp_schema.contains("properties")) {
  803. for (const auto & prop : comp_schema["properties"].items()) {
  804. properties.emplace_back(prop.key(), prop.value());
  805. if (is_required) {
  806. required.insert(prop.key());
  807. }
  808. }
  809. } else if (comp_schema.contains("enum")) {
  810. for (const auto & v : comp_schema["enum"]) {
  811. const auto rule = _generate_constant_rule(v);
  812. if (enum_values.find(rule) == enum_values.end()) {
  813. enum_values[rule] = 0;
  814. }
  815. enum_values[rule] += 1;
  816. }
  817. } else {
  818. // todo warning
  819. }
  820. };
  821. for (auto & t : schema["allOf"]) {
  822. if (t.contains("anyOf")) {
  823. for (auto & tt : t["anyOf"]) {
  824. add_component(tt, false);
  825. }
  826. } else {
  827. add_component(t, true);
  828. }
  829. }
  830. if (!enum_values.empty()) {
  831. std::vector<std::string> enum_intersection;
  832. for (const auto & p : enum_values) {
  833. if (p.second == schema["allOf"].size()) {
  834. enum_intersection.push_back(p.first);
  835. }
  836. }
  837. if (!enum_intersection.empty()) {
  838. return _add_rule(rule_name, "(" + string_join(enum_intersection, " | ") + ") space");
  839. }
  840. }
  841. return _add_rule(rule_name, _build_object_rule(properties, required, hybrid_name, json()));
  842. } else if ((schema_type.is_null() || schema_type == "array") && (schema.contains("items") || schema.contains("prefixItems"))) {
  843. json items = schema.contains("items") ? schema["items"] : schema["prefixItems"];
  844. if (items.is_array()) {
  845. std::string rule = "\"[\" space ";
  846. for (size_t i = 0; i < items.size(); i++) {
  847. if (i > 0) {
  848. rule += " \",\" space ";
  849. }
  850. rule += visit(items[i], name + (name.empty() ? "" : "-") + "tuple-" + std::to_string(i));
  851. }
  852. rule += " \"]\" space";
  853. return _add_rule(rule_name, rule);
  854. } else {
  855. std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
  856. int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
  857. json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
  858. int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
  859. return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
  860. }
  861. } else if ((schema_type.is_null() || schema_type == "string") && schema.contains("pattern")) {
  862. return _visit_pattern(schema["pattern"], rule_name);
  863. } else if ((schema_type.is_null() || schema_type == "string") && std::regex_match(schema_format, std::regex("^uuid[1-5]?$"))) {
  864. return _add_primitive(rule_name == "root" ? "root" : schema_format, PRIMITIVE_RULES.at("uuid"));
  865. } else if ((schema_type.is_null() || schema_type == "string") && STRING_FORMAT_RULES.find(schema_format + "-string") != STRING_FORMAT_RULES.end()) {
  866. auto prim_name = schema_format + "-string";
  867. return _add_rule(rule_name, _add_primitive(prim_name, STRING_FORMAT_RULES.at(prim_name)));
  868. } else if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
  869. std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
  870. int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
  871. int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
  872. return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
  873. } else if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
  874. int64_t min_value = std::numeric_limits<int64_t>::min();
  875. int64_t max_value = std::numeric_limits<int64_t>::max();
  876. if (schema.contains("minimum")) {
  877. min_value = schema["minimum"].get<int64_t>();
  878. } else if (schema.contains("exclusiveMinimum")) {
  879. min_value = schema["exclusiveMinimum"].get<int64_t>() + 1;
  880. }
  881. if (schema.contains("maximum")) {
  882. max_value = schema["maximum"].get<int64_t>();
  883. } else if (schema.contains("exclusiveMaximum")) {
  884. max_value = schema["exclusiveMaximum"].get<int64_t>() - 1;
  885. }
  886. std::stringstream out;
  887. out << "(";
  888. _build_min_max_int(min_value, max_value, out);
  889. out << ") space";
  890. return _add_rule(rule_name, out.str());
  891. } else if (schema.empty() || schema_type == "object") {
  892. return _add_rule(rule_name, _add_primitive("object", PRIMITIVE_RULES.at("object")));
  893. } else {
  894. if (!schema_type.is_string() || PRIMITIVE_RULES.find(schema_type.get<std::string>()) == PRIMITIVE_RULES.end()) {
  895. _errors.push_back("Unrecognized schema: " + schema.dump());
  896. return "";
  897. }
  898. // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
  899. return _add_primitive(rule_name == "root" ? "root" : schema_type.get<std::string>(), PRIMITIVE_RULES.at(schema_type.get<std::string>()));
  900. }
  901. }
  902. void check_errors() {
  903. if (!_errors.empty()) {
  904. throw std::runtime_error("JSON schema conversion failed:\n" + string_join(_errors, "\n"));
  905. }
  906. if (!_warnings.empty()) {
  907. fprintf(stderr, "WARNING: JSON schema conversion was incomplete: %s\n", string_join(_warnings, "; ").c_str());
  908. }
  909. }
  910. std::string format_grammar() {
  911. std::stringstream ss;
  912. for (const auto & kv : _rules) {
  913. ss << kv.first << " ::= " << kv.second << std::endl;
  914. }
  915. return ss.str();
  916. }
  917. };
  918. std::string json_schema_to_grammar(const json & schema, bool force_gbnf) {
  919. #ifdef LLAMA_USE_LLGUIDANCE
  920. if (!force_gbnf) {
  921. return "%llguidance {}\nstart: %json " + schema.dump();
  922. }
  923. #else
  924. (void)force_gbnf;
  925. #endif // LLAMA_USE_LLGUIDANCE
  926. return build_grammar([&](const common_grammar_builder & callbacks) {
  927. auto copy = schema;
  928. callbacks.resolve_refs(copy);
  929. callbacks.add_schema("", copy);
  930. });
  931. }
  932. std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options) {
  933. SchemaConverter converter([&](const std::string &) { return json(); }, options.dotall);
  934. common_grammar_builder builder {
  935. /* .add_rule = */ [&](const std::string & name, const std::string & rule) {
  936. return converter._add_rule(name, rule);
  937. },
  938. /* .add_schema = */ [&](const std::string & name, const nlohmann::ordered_json & schema) {
  939. return converter.visit(schema, name == "root" ? "" : name);
  940. },
  941. /* .resolve_refs = */ [&](nlohmann::ordered_json & schema) {
  942. converter.resolve_refs(schema, "");
  943. }
  944. };
  945. cb(builder);
  946. converter.check_errors();
  947. return converter.format_grammar();
  948. }