1
0

json-schema-to-grammar.cpp 48 KB

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