json-schema-to-grammar.mjs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. // WARNING: This file was ported from json_schema_to_grammar.py, please fix bugs / add features there first.
  2. const SPACE_RULE = '| " " | "\\n" [ \\t]{0,20}';
  3. function _buildRepetition(itemRule, minItems, maxItems, opts={}) {
  4. if (minItems === 0 && maxItems === 1) {
  5. return `${itemRule}?`;
  6. }
  7. const separatorRule = opts.separatorRule ?? '';
  8. const itemRuleIsLiteral = opts.itemRuleIsLiteral ?? false
  9. if (separatorRule === '') {
  10. if (minItems === 1 && maxItems === undefined) {
  11. return `${itemRule}+`;
  12. } else if (minItems === 0 && maxItems === undefined) {
  13. return `${itemRule}*`;
  14. } else {
  15. return `${itemRule}{${minItems},${maxItems !== undefined ? maxItems : ''}}`;
  16. }
  17. }
  18. const result = itemRule + ' ' + _buildRepetition(`(${separatorRule} ${itemRule})`, minItems > 0 ? minItems - 1 : 0, maxItems !== undefined ? maxItems - 1 : undefined);
  19. return minItems === 0 ? `(${result})?` : result;
  20. }
  21. function _generateMinMaxInt(minValue, maxValue, out, decimalsLeft = 16, topLevel = true) {
  22. const hasMin = minValue !== null;
  23. const hasMax = maxValue !== null;
  24. function digitRange(fromChar, toChar) {
  25. out.push("[");
  26. if (fromChar === toChar) {
  27. out.push(fromChar);
  28. } else {
  29. out.push(fromChar);
  30. out.push("-");
  31. out.push(toChar);
  32. }
  33. out.push("]");
  34. }
  35. function moreDigits(minDigits, maxDigits) {
  36. out.push("[0-9]");
  37. if (minDigits === maxDigits && minDigits === 1) {
  38. return;
  39. }
  40. out.push("{");
  41. out.push(minDigits.toString());
  42. if (maxDigits !== minDigits) {
  43. out.push(",");
  44. if (maxDigits !== Number.MAX_SAFE_INTEGER) {
  45. out.push(maxDigits.toString());
  46. }
  47. }
  48. out.push("}");
  49. }
  50. function uniformRange(fromStr, toStr) {
  51. let i = 0;
  52. while (i < fromStr.length && fromStr[i] === toStr[i]) {
  53. i++;
  54. }
  55. if (i > 0) {
  56. out.push("\"");
  57. out.push(fromStr.slice(0, i));
  58. out.push("\"");
  59. }
  60. if (i < fromStr.length) {
  61. if (i > 0) {
  62. out.push(" ");
  63. }
  64. const subLen = fromStr.length - i - 1;
  65. if (subLen > 0) {
  66. const fromSub = fromStr.slice(i + 1);
  67. const toSub = toStr.slice(i + 1);
  68. const subZeros = "0".repeat(subLen);
  69. const subNines = "9".repeat(subLen);
  70. let toReached = false;
  71. out.push("(");
  72. if (fromSub === subZeros) {
  73. digitRange(fromStr[i], String.fromCharCode(toStr.charCodeAt(i) - 1));
  74. out.push(" ");
  75. moreDigits(subLen, subLen);
  76. } else {
  77. out.push("[");
  78. out.push(fromStr[i]);
  79. out.push("] ");
  80. out.push("(");
  81. uniformRange(fromSub, subNines);
  82. out.push(")");
  83. if (fromStr.charCodeAt(i) < toStr.charCodeAt(i) - 1) {
  84. out.push(" | ");
  85. if (toSub === subNines) {
  86. digitRange(String.fromCharCode(fromStr.charCodeAt(i) + 1), toStr[i]);
  87. toReached = true;
  88. } else {
  89. digitRange(String.fromCharCode(fromStr.charCodeAt(i) + 1), String.fromCharCode(toStr.charCodeAt(i) - 1));
  90. }
  91. out.push(" ");
  92. moreDigits(subLen, subLen);
  93. }
  94. }
  95. if (!toReached) {
  96. out.push(" | ");
  97. digitRange(toStr[i], toStr[i]);
  98. out.push(" ");
  99. uniformRange(subZeros, toSub);
  100. }
  101. out.push(")");
  102. } else {
  103. out.push("[");
  104. out.push(fromStr[i]);
  105. out.push("-");
  106. out.push(toStr[i]);
  107. out.push("]");
  108. }
  109. }
  110. }
  111. if (hasMin && hasMax) {
  112. if (minValue < 0 && maxValue < 0) {
  113. out.push("\"-\" (");
  114. _generateMinMaxInt(-maxValue, -minValue, out, decimalsLeft, true);
  115. out.push(")");
  116. return;
  117. }
  118. if (minValue < 0) {
  119. out.push("\"-\" (");
  120. _generateMinMaxInt(0, -minValue, out, decimalsLeft, true);
  121. out.push(") | ");
  122. minValue = 0;
  123. }
  124. let minS = minValue.toString();
  125. const maxS = maxValue.toString();
  126. const minDigits = minS.length;
  127. const maxDigits = maxS.length;
  128. for (let digits = minDigits; digits < maxDigits; digits++) {
  129. uniformRange(minS, "9".repeat(digits));
  130. minS = "1" + "0".repeat(digits);
  131. out.push(" | ");
  132. }
  133. uniformRange(minS, maxS);
  134. return;
  135. }
  136. const lessDecimals = Math.max(decimalsLeft - 1, 1);
  137. if (hasMin) {
  138. if (minValue < 0) {
  139. out.push("\"-\" (");
  140. _generateMinMaxInt(null, -minValue, out, decimalsLeft, false);
  141. out.push(") | [0] | [1-9] ");
  142. moreDigits(0, decimalsLeft - 1);
  143. } else if (minValue === 0) {
  144. if (topLevel) {
  145. out.push("[0] | [1-9] ");
  146. moreDigits(0, lessDecimals);
  147. } else {
  148. moreDigits(1, decimalsLeft);
  149. }
  150. } else if (minValue <= 9) {
  151. const c = minValue.toString();
  152. const range_start = topLevel ? '1' : '0';
  153. if (c > range_start) {
  154. digitRange(range_start, String.fromCharCode(c.charCodeAt(0) - 1));
  155. out.push(" ");
  156. moreDigits(1, lessDecimals);
  157. out.push(" | ");
  158. }
  159. digitRange(c, "9");
  160. out.push(" ");
  161. moreDigits(0, lessDecimals);
  162. } else {
  163. const minS = minValue.toString();
  164. const length = minS.length;
  165. const c = minS[0];
  166. if (c > "1") {
  167. digitRange(topLevel ? "1" : "0", String.fromCharCode(c.charCodeAt(0) - 1));
  168. out.push(" ");
  169. moreDigits(length, lessDecimals);
  170. out.push(" | ");
  171. }
  172. digitRange(c, c);
  173. out.push(" (");
  174. _generateMinMaxInt(parseInt(minS.slice(1)), null, out, lessDecimals, false);
  175. out.push(")");
  176. if (c < "9") {
  177. out.push(" | ");
  178. digitRange(String.fromCharCode(c.charCodeAt(0) + 1), "9");
  179. out.push(" ");
  180. moreDigits(length - 1, lessDecimals);
  181. }
  182. }
  183. return;
  184. }
  185. if (hasMax) {
  186. if (maxValue >= 0) {
  187. if (topLevel) {
  188. out.push("\"-\" [1-9] ");
  189. moreDigits(0, lessDecimals);
  190. out.push(" | ");
  191. }
  192. _generateMinMaxInt(0, maxValue, out, decimalsLeft, true);
  193. } else {
  194. out.push("\"-\" (");
  195. _generateMinMaxInt(-maxValue, null, out, decimalsLeft, false);
  196. out.push(")");
  197. }
  198. return;
  199. }
  200. throw new Error("At least one of minValue or maxValue must be set");
  201. }
  202. class BuiltinRule {
  203. constructor(content, deps) {
  204. this.content = content;
  205. this.deps = deps || [];
  206. }
  207. }
  208. const PRIMITIVE_RULES = {
  209. boolean : new BuiltinRule('("true" | "false") space', []),
  210. 'decimal-part' : new BuiltinRule('[0-9]{1,16}', []),
  211. 'integral-part': new BuiltinRule('[0] | [1-9] [0-9]{0,15}', []),
  212. number : new BuiltinRule('("-"? integral-part) ("." decimal-part)? ([eE] [-+]? integral-part)? space', ['integral-part', 'decimal-part']),
  213. integer : new BuiltinRule('("-"? integral-part) space', ['integral-part']),
  214. value : new BuiltinRule('object | array | string | number | boolean | null', ['object', 'array', 'string', 'number', 'boolean', 'null']),
  215. object : new BuiltinRule('"{" space ( string ":" space value ("," space string ":" space value)* )? "}" space', ['string', 'value']),
  216. array : new BuiltinRule('"[" space ( value ("," space value)* )? "]" space', ['value']),
  217. uuid : new BuiltinRule('"\\"" [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', []),
  218. char : new BuiltinRule(`[^"\\\\\\x7F\\x00-\\x1F] | [\\\\] (["\\\\bfnrt] | "u" [0-9a-fA-F]{4})`, []),
  219. string : new BuiltinRule(`"\\"" char* "\\"" space`, ['char']),
  220. null : new BuiltinRule('"null" space', []),
  221. };
  222. // TODO: support "uri", "email" string formats
  223. const STRING_FORMAT_RULES = {
  224. 'date' : new BuiltinRule('[0-9]{4} "-" ( "0" [1-9] | "1" [0-2] ) "-" ( \"0\" [1-9] | [1-2] [0-9] | "3" [0-1] )', []),
  225. 'time' : new BuiltinRule('([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] )', []),
  226. 'date-time' : new BuiltinRule('date "T" time', ['date', 'time']),
  227. 'date-string' : new BuiltinRule('"\\"" date "\\"" space', ['date']),
  228. 'time-string' : new BuiltinRule('"\\"" time "\\"" space', ['time']),
  229. 'date-time-string': new BuiltinRule('"\\"" date-time "\\"" space', ['date-time']),
  230. }
  231. const RESERVED_NAMES = {'root': true, ...PRIMITIVE_RULES, ...STRING_FORMAT_RULES};
  232. const INVALID_RULE_CHARS_RE = /[^\dA-Za-z-]+/g;
  233. const GRAMMAR_LITERAL_ESCAPE_RE = /[\n\r"]/g;
  234. const GRAMMAR_RANGE_LITERAL_ESCAPE_RE = /[\n\r"\]\-\\]/g;
  235. const GRAMMAR_LITERAL_ESCAPES = { '\r': '\\r', '\n': '\\n', '"': '\\"', '-': '\\-', ']': '\\]' };
  236. const NON_LITERAL_SET = new Set('|.()[]{}*+?');
  237. const ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = new Set('^$.[]()|{}*+?');
  238. export class SchemaConverter {
  239. constructor(options) {
  240. this._propOrder = options.prop_order || {};
  241. this._allowFetch = options.allow_fetch || false;
  242. this._dotall = options.dotall || false;
  243. this._rules = {'space': SPACE_RULE};
  244. this._refs = {};
  245. this._refsBeingResolved = new Set();
  246. }
  247. _formatLiteral(literal) {
  248. const escaped = literal.replace(
  249. GRAMMAR_LITERAL_ESCAPE_RE,
  250. m => GRAMMAR_LITERAL_ESCAPES[m]
  251. );
  252. return `"${escaped}"`;
  253. }
  254. _formatRangeChar(literal) {
  255. return JSON.stringify(literal).slice(1, -1).replace(
  256. GRAMMAR_RANGE_LITERAL_ESCAPE_RE,
  257. m => GRAMMAR_LITERAL_ESCAPES[m]
  258. );
  259. }
  260. _addRule(name, rule) {
  261. let escName = name.replace(INVALID_RULE_CHARS_RE, '-');
  262. let key = escName;
  263. if (escName in this._rules) {
  264. if (this._rules[escName] === rule) {
  265. return key;
  266. }
  267. let i = 0;
  268. while ((`${escName}${i}` in this._rules) && (this._rules[`${escName}${i}`] !== rule)) {
  269. i += 1;
  270. }
  271. key = `${escName}${i}`;
  272. }
  273. this._rules[key] = rule;
  274. return key;
  275. }
  276. async resolveRefs(schema, url) {
  277. const visit = async (n) => {
  278. if (Array.isArray(n)) {
  279. return Promise.all(n.map(visit));
  280. } else if (typeof n === 'object' && n !== null) {
  281. let ref = n.$ref;
  282. let target;
  283. if (ref !== undefined && !this._refs[ref]) {
  284. if (ref.startsWith('https://')) {
  285. if (!this._allowFetch) {
  286. throw new Error('Fetching remote schemas is not allowed (use --allow-fetch for force)');
  287. }
  288. const fetch = (await import('node-fetch')).default;
  289. const fragSplit = ref.split('#');
  290. const baseUrl = fragSplit[0];
  291. target = this._refs[baseUrl];
  292. if (!target) {
  293. target = await this.resolveRefs(await fetch(ref).then(res => res.json()), baseUrl);
  294. this._refs[baseUrl] = target;
  295. }
  296. if (fragSplit.length === 1 || fragSplit[fragSplit.length - 1] === '') {
  297. return target;
  298. }
  299. } else if (ref.startsWith('#/')) {
  300. target = schema;
  301. ref = `${url}${ref}`;
  302. n.$ref = ref;
  303. } else {
  304. throw new Error(`Unsupported ref ${ref}`);
  305. }
  306. const selectors = ref.split('#')[1].split('/').slice(1);
  307. for (const sel of selectors) {
  308. if (!target || !(sel in target)) {
  309. throw new Error(`Error resolving ref ${ref}: ${sel} not in ${JSON.stringify(target)}`);
  310. }
  311. target = target[sel];
  312. }
  313. this._refs[ref] = target;
  314. } else {
  315. await Promise.all(Object.values(n).map(visit));
  316. }
  317. }
  318. return n;
  319. };
  320. return visit(schema);
  321. }
  322. _generateUnionRule(name, altSchemas) {
  323. return altSchemas
  324. .map((altSchema, i) => this.visit(altSchema, `${name ?? ''}${name ? '-' : 'alternative-'}${i}`))
  325. .join(' | ');
  326. }
  327. _visitPattern(pattern, name) {
  328. if (!pattern.startsWith('^') || !pattern.endsWith('$')) {
  329. throw new Error('Pattern must start with "^" and end with "$"');
  330. }
  331. pattern = pattern.slice(1, -1);
  332. const subRuleIds = {};
  333. let i = 0;
  334. const length = pattern.length;
  335. const getDot = () => {
  336. let rule;
  337. if (this._dotall) {
  338. rule = '[\\U00000000-\\U0010FFFF]';
  339. } else {
  340. // Accept any character... except \n and \r line break chars (\x0A and \xOD)
  341. rule = '[^\\x0A\\x0D]';
  342. }
  343. return this._addRule('dot', rule);
  344. };
  345. const toRule = ([s, isLiteral]) => isLiteral ? "\"" + s + "\"" : s;
  346. const transform = () => {
  347. const start = i;
  348. // For each component of this sequence, store its string representation and whether it's a literal.
  349. // We only need a flat structure here to apply repetition operators to the last item, and
  350. // to merge literals at the and (we're parsing grouped ( sequences ) recursively and don't treat '|' specially
  351. // (GBNF's syntax is luckily very close to regular expressions!)
  352. const seq = [];
  353. const joinSeq = () => {
  354. const ret = [];
  355. for (const [isLiteral, g] of groupBy(seq, x => x[1])) {
  356. if (isLiteral) {
  357. ret.push([[...g].map(x => x[0]).join(''), true]);
  358. } else {
  359. ret.push(...g);
  360. }
  361. }
  362. if (ret.length === 1) {
  363. return ret[0];
  364. }
  365. return [ret.map(x => toRule(x)).join(' '), false];
  366. };
  367. while (i < length) {
  368. const c = pattern[i];
  369. if (c === '.') {
  370. seq.push([getDot(), false]);
  371. i += 1;
  372. } else if (c === '(') {
  373. i += 1;
  374. if (i < length) {
  375. if (pattern[i] === '?') {
  376. throw new Error(`Unsupported pattern syntax "${pattern[i]}" at index ${i} of /${pattern}/`);
  377. }
  378. }
  379. seq.push([`(${toRule(transform())})`, false]);
  380. } else if (c === ')') {
  381. i += 1;
  382. if (start <= 0 || pattern[start - 1] !== '(') {
  383. throw new Error(`Unbalanced parentheses; start = ${start}, i = ${i}, pattern = ${pattern}`);
  384. }
  385. return joinSeq();
  386. } else if (c === '[') {
  387. let squareBrackets = c;
  388. i += 1;
  389. while (i < length && pattern[i] !== ']') {
  390. if (pattern[i] === '\\') {
  391. squareBrackets += pattern.slice(i, i + 2);
  392. i += 2;
  393. } else {
  394. squareBrackets += pattern[i];
  395. i += 1;
  396. }
  397. }
  398. if (i >= length) {
  399. throw new Error(`Unbalanced square brackets; start = ${start}, i = ${i}, pattern = ${pattern}`);
  400. }
  401. squareBrackets += ']';
  402. i += 1;
  403. seq.push([squareBrackets, false]);
  404. } else if (c === '|') {
  405. seq.push(['|', false]);
  406. i += 1;
  407. } else if (c === '*' || c === '+' || c === '?') {
  408. seq[seq.length - 1] = [toRule(seq[seq.length - 1]) + c, false];
  409. i += 1;
  410. } else if (c === '{') {
  411. let curlyBrackets = c;
  412. i += 1;
  413. while (i < length && pattern[i] !== '}') {
  414. curlyBrackets += pattern[i];
  415. i += 1;
  416. }
  417. if (i >= length) {
  418. throw new Error(`Unbalanced curly brackets; start = ${start}, i = ${i}, pattern = ${pattern}`);
  419. }
  420. curlyBrackets += '}';
  421. i += 1;
  422. const nums = curlyBrackets.slice(1, -1).split(',').map(s => s.trim());
  423. let minTimes, maxTimes;
  424. if (nums.length === 1) {
  425. minTimes = parseInt(nums[0], 10);
  426. maxTimes = minTimes;
  427. } else {
  428. if (nums.length !== 2) {
  429. throw new Error(`Invalid quantifier ${curlyBrackets}`);
  430. }
  431. minTimes = nums[0] ? parseInt(nums[0], 10) : 0;
  432. maxTimes = nums[1] ? parseInt(nums[1], 10) : Infinity;
  433. }
  434. let [sub, subIsLiteral] = seq[seq.length - 1];
  435. if (!subIsLiteral) {
  436. let id = subRuleIds[sub];
  437. if (id === undefined) {
  438. id = this._addRule(`${name}-${Object.keys(subRuleIds).length + 1}`, sub);
  439. subRuleIds[sub] = id;
  440. }
  441. sub = id;
  442. }
  443. seq[seq.length - 1] = [
  444. _buildRepetition(subIsLiteral ? `"${sub}"` : sub, minTimes, maxTimes, {itemRuleIsLiteral: subIsLiteral}),
  445. false
  446. ];
  447. } else {
  448. let literal = '';
  449. while (i < length) {
  450. if (pattern[i] === '\\' && i < length - 1) {
  451. const next = pattern[i + 1];
  452. if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.has(next)) {
  453. i += 1;
  454. literal += pattern[i];
  455. i += 1;
  456. } else {
  457. literal += pattern.slice(i, i + 2);
  458. i += 2;
  459. }
  460. } else if (pattern[i] === '"') {
  461. literal += '\\"';
  462. i += 1;
  463. } else if (!NON_LITERAL_SET.has(pattern[i]) &&
  464. (i === length - 1 || literal === '' || pattern[i + 1] === '.' || !NON_LITERAL_SET.has(pattern[i+1]))) {
  465. literal += pattern[i];
  466. i += 1;
  467. } else {
  468. break;
  469. }
  470. }
  471. if (literal !== '') {
  472. seq.push([literal, true]);
  473. }
  474. }
  475. }
  476. return joinSeq();
  477. };
  478. return this._addRule(name, "\"\\\"\" " + toRule(transform()) + " \"\\\"\" space")
  479. }
  480. _notStrings(strings) {
  481. class TrieNode {
  482. constructor() {
  483. this.children = {};
  484. this.isEndOfString = false;
  485. }
  486. insert(str) {
  487. let node = this;
  488. for (const c of str) {
  489. node = node.children[c] = node.children[c] || new TrieNode();
  490. }
  491. node.isEndOfString = true;
  492. }
  493. }
  494. const trie = new TrieNode();
  495. for (const s of strings) {
  496. trie.insert(s);
  497. }
  498. const charRuleName = this._addPrimitive('char', PRIMITIVE_RULES['char']);
  499. const out = ['["] ( '];
  500. const visit = (node) => {
  501. const rejects = [];
  502. let first = true;
  503. for (const c of Object.keys(node.children).sort()) {
  504. const child = node.children[c];
  505. rejects.push(c);
  506. if (first) {
  507. first = false;
  508. } else {
  509. out.push(' | ');
  510. }
  511. out.push(`[${c}]`);
  512. if (Object.keys(child.children).length > 0) {
  513. out.push(' (');
  514. visit(child);
  515. out.push(')');
  516. } else if (child.isEndOfString) {
  517. out.push(` ${charRuleName}+`);
  518. }
  519. }
  520. if (Object.keys(node.children).length > 0) {
  521. if (!first) {
  522. out.push(' | ');
  523. }
  524. out.push(`[^"${rejects.join('')}] ${charRuleName}*`);
  525. }
  526. };
  527. visit(trie);
  528. out.push(` )${trie.isEndOfString ? '' : '?'} ["] space`);
  529. return out.join('');
  530. }
  531. _resolveRef(ref) {
  532. let refName = ref.split('/').pop();
  533. if (!(refName in this._rules) && !this._refsBeingResolved.has(ref)) {
  534. this._refsBeingResolved.add(ref);
  535. const resolved = this._refs[ref];
  536. refName = this.visit(resolved, refName);
  537. this._refsBeingResolved.delete(ref);
  538. }
  539. return refName;
  540. }
  541. _generateConstantRule(value) {
  542. return this._formatLiteral(JSON.stringify(value));
  543. }
  544. visit(schema, name) {
  545. const schemaType = schema.type;
  546. const schemaFormat = schema.format;
  547. const ruleName = name in RESERVED_NAMES ? name + '-' : name == '' ? 'root' : name;
  548. const ref = schema.$ref;
  549. if (ref !== undefined) {
  550. return this._addRule(ruleName, this._resolveRef(ref));
  551. } else if (schema.oneOf || schema.anyOf) {
  552. return this._addRule(ruleName, this._generateUnionRule(name, schema.oneOf || schema.anyOf));
  553. } else if (Array.isArray(schemaType)) {
  554. return this._addRule(ruleName, this._generateUnionRule(name, schemaType.map(t => ({...schema, type: t}))));
  555. } else if ('const' in schema) {
  556. return this._addRule(ruleName, this._generateConstantRule(schema.const) + ' space');
  557. } else if ('enum' in schema) {
  558. const rule = '(' + schema.enum.map(v => this._generateConstantRule(v)).join(' | ') + ') space';
  559. return this._addRule(ruleName, rule);
  560. } else if ((schemaType === undefined || schemaType === 'object') &&
  561. ('properties' in schema ||
  562. ('additionalProperties' in schema && schema.additionalProperties !== true))) {
  563. const required = new Set(schema.required || []);
  564. const properties = Object.entries(schema.properties ?? {});
  565. return this._addRule(ruleName, this._buildObjectRule(properties, required, name, schema.additionalProperties));
  566. } else if ((schemaType === undefined || schemaType === 'object') && 'allOf' in schema) {
  567. const required = new Set();
  568. const properties = [];
  569. const addComponent = (compSchema, isRequired) => {
  570. const ref = compSchema.$ref;
  571. if (ref !== undefined) {
  572. compSchema = this._refs[ref];
  573. }
  574. if ('properties' in compSchema) {
  575. for (const [propName, propSchema] of Object.entries(compSchema.properties)) {
  576. properties.push([propName, propSchema]);
  577. if (isRequired) {
  578. required.add(propName);
  579. }
  580. }
  581. }
  582. };
  583. for (const t of schema.allOf) {
  584. if ('anyOf' in t) {
  585. for (const tt of t.anyOf) {
  586. addComponent(tt, false);
  587. }
  588. } else {
  589. addComponent(t, true);
  590. }
  591. }
  592. return this._addRule(ruleName, this._buildObjectRule(properties, required, name, null));
  593. } else if ((schemaType === undefined || schemaType === 'array') && ('items' in schema || 'prefixItems' in schema)) {
  594. const items = schema.items ?? schema.prefixItems;
  595. if (Array.isArray(items)) {
  596. return this._addRule(
  597. ruleName,
  598. '"[" space ' +
  599. items.map((item, i) => this.visit(item, `${name ?? ''}${name ? '-' : ''}tuple-${i}`)).join(' "," space ') +
  600. ' "]" space'
  601. );
  602. } else {
  603. const itemRuleName = this.visit(items, `${name ?? ''}${name ? '-' : ''}item`);
  604. const minItems = schema.minItems || 0;
  605. const maxItems = schema.maxItems;
  606. return this._addRule(ruleName, '"[" space ' + _buildRepetition(itemRuleName, minItems, maxItems, {separatorRule: '"," space'}) + ' "]" space');
  607. }
  608. } else if ((schemaType === undefined || schemaType === 'string') && 'pattern' in schema) {
  609. return this._visitPattern(schema.pattern, ruleName);
  610. } else if ((schemaType === undefined || schemaType === 'string') && /^uuid[1-5]?$/.test(schema.format || '')) {
  611. return this._addPrimitive(
  612. ruleName === 'root' ? 'root' : schemaFormat,
  613. PRIMITIVE_RULES['uuid']
  614. );
  615. } else if ((schemaType === undefined || schemaType === 'string') && `${schema.format}-string` in STRING_FORMAT_RULES) {
  616. const primName = `${schema.format}-string`
  617. return this._addRule(ruleName, this._addPrimitive(primName, STRING_FORMAT_RULES[primName]));
  618. } else if (schemaType === 'string' && ('minLength' in schema || 'maxLength' in schema)) {
  619. const charRuleName = this._addPrimitive('char', PRIMITIVE_RULES['char']);
  620. const minLen = schema.minLength || 0;
  621. const maxLen = schema.maxLength;
  622. return this._addRule(ruleName, '"\\\"" ' + _buildRepetition(charRuleName, minLen, maxLen) + ' "\\\"" space');
  623. } else if (schemaType === 'integer' && ('minimum' in schema || 'exclusiveMinimum' in schema || 'maximum' in schema || 'exclusiveMaximum' in schema)) {
  624. let minValue = null;
  625. let maxValue = null;
  626. if ('minimum' in schema) {
  627. minValue = schema.minimum;
  628. } else if ('exclusiveMinimum' in schema) {
  629. minValue = schema.exclusiveMinimum + 1;
  630. }
  631. if ('maximum' in schema) {
  632. maxValue = schema.maximum;
  633. } else if ('exclusiveMaximum' in schema) {
  634. maxValue = schema.exclusiveMaximum - 1;
  635. }
  636. const out = ["("];
  637. _generateMinMaxInt(minValue, maxValue, out);
  638. out.push(") space");
  639. return this._addRule(ruleName, out.join(''));
  640. } else if ((schemaType === 'object') || (Object.keys(schema).length === 0)) {
  641. return this._addRule(ruleName, this._addPrimitive('object', PRIMITIVE_RULES['object']));
  642. } else {
  643. if (!(schemaType in PRIMITIVE_RULES)) {
  644. throw new Error(`Unrecognized schema: ${JSON.stringify(schema)}`);
  645. }
  646. // TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
  647. return this._addPrimitive(ruleName === 'root' ? 'root' : schemaType, PRIMITIVE_RULES[schemaType]);
  648. }
  649. }
  650. _addPrimitive(name, rule) {
  651. let n = this._addRule(name, rule.content);
  652. for (const dep of rule.deps) {
  653. const depRule = PRIMITIVE_RULES[dep] || STRING_FORMAT_RULES[dep];
  654. if (!depRule) {
  655. throw new Error(`Rule ${dep} not known`);
  656. }
  657. if (!(dep in this._rules)) {
  658. this._addPrimitive(dep, depRule);
  659. }
  660. }
  661. return n;
  662. }
  663. _buildObjectRule(properties, required, name, additionalProperties) {
  664. const propOrder = this._propOrder;
  665. // sort by position in prop_order (if specified) then by original order
  666. const sortedProps = properties.map(([k]) => k).sort((a, b) => {
  667. const orderA = propOrder[a] || Infinity;
  668. const orderB = propOrder[b] || Infinity;
  669. return orderA - orderB || properties.findIndex(([k]) => k === a) - properties.findIndex(([k]) => k === b);
  670. });
  671. const propKvRuleNames = {};
  672. for (const [propName, propSchema] of properties) {
  673. const propRuleName = this.visit(propSchema, `${name ?? ''}${name ? '-' : ''}${propName}`);
  674. propKvRuleNames[propName] = this._addRule(
  675. `${name ?? ''}${name ? '-' : ''}${propName}-kv`,
  676. `${this._formatLiteral(JSON.stringify(propName))} space ":" space ${propRuleName}`
  677. );
  678. }
  679. const requiredProps = sortedProps.filter(k => required.has(k));
  680. const optionalProps = sortedProps.filter(k => !required.has(k));
  681. if (additionalProperties) {
  682. const subName = `${name ?? ''}${name ? '-' : ''}additional`;
  683. const valueRule =
  684. additionalProperties != null && typeof additionalProperties === 'object' ? this.visit(additionalProperties, `${subName}-value`)
  685. : this._addPrimitive('value', PRIMITIVE_RULES['value']);
  686. const key_rule =
  687. sortedProps.length === 0 ? this._addPrimitive('string', PRIMITIVE_RULES['string'])
  688. : this._addRule(`${subName}-k`, this._notStrings(sortedProps));
  689. propKvRuleNames['*'] = this._addRule(
  690. `${subName}-kv`,
  691. `${key_rule} ":" space ${valueRule}`);
  692. optionalProps.push('*');
  693. }
  694. let rule = '"{" space ';
  695. rule += requiredProps.map(k => propKvRuleNames[k]).join(' "," space ');
  696. if (optionalProps.length > 0) {
  697. rule += ' (';
  698. if (requiredProps.length > 0) {
  699. rule += ' "," space ( ';
  700. }
  701. const getRecursiveRefs = (ks, firstIsOptional) => {
  702. const [k, ...rest] = ks;
  703. const kvRuleName = propKvRuleNames[k];
  704. let res;
  705. const commaRef = `( "," space ${kvRuleName} )`;
  706. if (firstIsOptional) {
  707. res = commaRef + (k === '*' ? '*' : '?');
  708. } else {
  709. res = kvRuleName + (k === '*' ? ' ' + commaRef + '*' : '');
  710. }
  711. if (rest.length > 0) {
  712. res += ' ' + this._addRule(
  713. `${name ?? ''}${name ? '-' : ''}${k}-rest`,
  714. getRecursiveRefs(rest, true)
  715. );
  716. }
  717. return res;
  718. };
  719. rule += optionalProps.map((_, i) => getRecursiveRefs(optionalProps.slice(i), false)).join(' | ');
  720. if (requiredProps.length > 0) {
  721. rule += ' )';
  722. }
  723. rule += ' )?';
  724. }
  725. rule += ' "}" space';
  726. return rule;
  727. }
  728. formatGrammar() {
  729. let grammar = '';
  730. for (const [name, rule] of Object.entries(this._rules).sort(([a], [b]) => a.localeCompare(b))) {
  731. grammar += `${name} ::= ${rule}\n`;
  732. }
  733. return grammar;
  734. }
  735. }
  736. // Helper function to group elements by a key function
  737. function* groupBy(iterable, keyFn) {
  738. let lastKey = null;
  739. let group = [];
  740. for (const element of iterable) {
  741. const key = keyFn(element);
  742. if (lastKey !== null && key !== lastKey) {
  743. yield [lastKey, group];
  744. group = [];
  745. }
  746. group.push(element);
  747. lastKey = key;
  748. }
  749. if (group.length > 0) {
  750. yield [lastKey, group];
  751. }
  752. }