json-schema-to-grammar.mjs 29 KB

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