json_schema_to_grammar.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. #!/usr/bin/env python3
  2. import argparse
  3. import itertools
  4. import json
  5. import re
  6. import sys
  7. from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
  8. def _build_repetition(item_rule, min_items, max_items, separator_rule=None):
  9. if min_items == 0 and max_items == 1:
  10. return f'{item_rule}?'
  11. if not separator_rule:
  12. if min_items == 1 and max_items is None:
  13. return f'{item_rule}+'
  14. elif min_items == 0 and max_items is None:
  15. return f'{item_rule}*'
  16. else:
  17. return f'{item_rule}{{{min_items},{max_items if max_items is not None else ""}}}'
  18. result = item_rule + ' ' + _build_repetition(f'({separator_rule} {item_rule})', min_items - 1 if min_items > 0 else 0, max_items - 1 if max_items is not None else None)
  19. return f'({result})?' if min_items == 0 else result
  20. def _generate_min_max_int(min_value: Optional[int], max_value: Optional[int], out: list, decimals_left: int = 16, top_level: bool = True):
  21. has_min = min_value != None
  22. has_max = max_value != None
  23. def digit_range(from_char: str, to_char: str):
  24. out.append("[")
  25. if from_char == to_char:
  26. out.append(from_char)
  27. else:
  28. out.append(from_char)
  29. out.append("-")
  30. out.append(to_char)
  31. out.append("]")
  32. def more_digits(min_digits: int, max_digits: int):
  33. out.append("[0-9]")
  34. if min_digits == max_digits and min_digits == 1:
  35. return
  36. out.append("{")
  37. out.append(str(min_digits))
  38. if max_digits != min_digits:
  39. out.append(",")
  40. if max_digits != sys.maxsize:
  41. out.append(str(max_digits))
  42. out.append("}")
  43. def uniform_range(from_str: str, to_str: str):
  44. i = 0
  45. while i < len(from_str) and from_str[i] == to_str[i]:
  46. i += 1
  47. if i > 0:
  48. out.append("\"")
  49. out.append(from_str[:i])
  50. out.append("\"")
  51. if i < len(from_str):
  52. if i > 0:
  53. out.append(" ")
  54. sub_len = len(from_str) - i - 1
  55. if sub_len > 0:
  56. from_sub = from_str[i+1:]
  57. to_sub = to_str[i+1:]
  58. sub_zeros = "0" * sub_len
  59. sub_nines = "9" * sub_len
  60. to_reached = False
  61. out.append("(")
  62. if from_sub == sub_zeros:
  63. digit_range(from_str[i], chr(ord(to_str[i]) - 1))
  64. out.append(" ")
  65. more_digits(sub_len, sub_len)
  66. else:
  67. out.append("[")
  68. out.append(from_str[i])
  69. out.append("] ")
  70. out.append("(")
  71. uniform_range(from_sub, sub_nines)
  72. out.append(")")
  73. if ord(from_str[i]) < ord(to_str[i]) - 1:
  74. out.append(" | ")
  75. if to_sub == sub_nines:
  76. digit_range(chr(ord(from_str[i]) + 1), to_str[i])
  77. to_reached = True
  78. else:
  79. digit_range(chr(ord(from_str[i]) + 1), chr(ord(to_str[i]) - 1))
  80. out.append(" ")
  81. more_digits(sub_len, sub_len)
  82. if not to_reached:
  83. out.append(" | ")
  84. digit_range(to_str[i], to_str[i])
  85. out.append(" ")
  86. uniform_range(sub_zeros, to_sub)
  87. out.append(")")
  88. else:
  89. out.append("[")
  90. out.append(from_str[i])
  91. out.append("-")
  92. out.append(to_str[i])
  93. out.append("]")
  94. if has_min and has_max:
  95. if min_value < 0 and max_value < 0:
  96. out.append("\"-\" (")
  97. _generate_min_max_int(-max_value, -min_value, out, decimals_left, top_level=True)
  98. out.append(")")
  99. return
  100. if min_value < 0:
  101. out.append("\"-\" (")
  102. _generate_min_max_int(0, -min_value, out, decimals_left, top_level=True)
  103. out.append(") | ")
  104. min_value = 0
  105. min_s = str(min_value)
  106. max_s = str(max_value)
  107. min_digits = len(min_s)
  108. max_digits = len(max_s)
  109. for digits in range(min_digits, max_digits):
  110. uniform_range(min_s, "9" * digits)
  111. min_s = "1" + "0" * digits
  112. out.append(" | ")
  113. uniform_range(min_s, max_s)
  114. return
  115. less_decimals = max(decimals_left - 1, 1)
  116. if has_min:
  117. if min_value < 0:
  118. out.append("\"-\" (")
  119. _generate_min_max_int(None, -min_value, out, decimals_left, top_level=False)
  120. out.append(") | [0] | [1-9] ")
  121. more_digits(0, decimals_left - 1)
  122. elif min_value == 0:
  123. if top_level:
  124. out.append("[0] | [1-9] ")
  125. more_digits(0, less_decimals)
  126. else:
  127. more_digits(1, decimals_left)
  128. elif min_value <= 9:
  129. c = str(min_value)
  130. range_start = '1' if top_level else '0'
  131. if c > range_start:
  132. digit_range(range_start, chr(ord(c) - 1))
  133. out.append(" ")
  134. more_digits(1, less_decimals)
  135. out.append(" | ")
  136. digit_range(c, "9")
  137. out.append(" ")
  138. more_digits(0, less_decimals)
  139. else:
  140. min_s = str(min_value)
  141. length = len(min_s)
  142. c = min_s[0]
  143. if c > "1":
  144. digit_range("1" if top_level else "0", chr(ord(c) - 1))
  145. out.append(" ")
  146. more_digits(length, less_decimals)
  147. out.append(" | ")
  148. digit_range(c, c)
  149. out.append(" (")
  150. _generate_min_max_int(int(min_s[1:]), None, out, less_decimals, top_level=False)
  151. out.append(")")
  152. if c < "9":
  153. out.append(" | ")
  154. digit_range(chr(ord(c) + 1), "9")
  155. out.append(" ")
  156. more_digits(length - 1, less_decimals)
  157. return
  158. if has_max:
  159. if max_value >= 0:
  160. if top_level:
  161. out.append("\"-\" [1-9] ")
  162. more_digits(0, less_decimals)
  163. out.append(" | ")
  164. _generate_min_max_int(0, max_value, out, decimals_left, top_level=True)
  165. else:
  166. out.append("\"-\" (")
  167. _generate_min_max_int(-max_value, None, out, decimals_left, top_level=False)
  168. out.append(")")
  169. return
  170. raise RuntimeError("At least one of min_value or max_value must be set")
  171. class BuiltinRule:
  172. def __init__(self, content: str, deps: list = None):
  173. self.content = content
  174. self.deps = deps or []
  175. # Constraining spaces to prevent model "running away".
  176. SPACE_RULE = '| " " | "\\n" [ \\t]{0,20}'
  177. PRIMITIVE_RULES = {
  178. 'boolean' : BuiltinRule('("true" | "false") space', []),
  179. 'decimal-part' : BuiltinRule('[0-9]{1,16}', []),
  180. 'integral-part': BuiltinRule('[0] | [1-9] [0-9]{0,15}', []),
  181. 'number' : BuiltinRule('("-"? integral-part) ("." decimal-part)? ([eE] [-+]? integral-part)? space', ['integral-part', 'decimal-part']),
  182. 'integer' : BuiltinRule('("-"? integral-part) space', ['integral-part']),
  183. 'value' : BuiltinRule('object | array | string | number | boolean | null', ['object', 'array', 'string', 'number', 'boolean', 'null']),
  184. 'object' : BuiltinRule('"{" space ( string ":" space value ("," space string ":" space value)* )? "}" space', ['string', 'value']),
  185. 'array' : BuiltinRule('"[" space ( value ("," space value)* )? "]" space', ['value']),
  186. 'uuid' : BuiltinRule(r'"\"" [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', []),
  187. 'char' : BuiltinRule(r'[^"\\\x7F\x00-\x1F] | [\\] (["\\bfnrt] | "u" [0-9a-fA-F]{4})', []),
  188. 'string' : BuiltinRule(r'"\"" char* "\"" space', ['char']),
  189. 'null' : BuiltinRule('"null" space', []),
  190. }
  191. # TODO: support "uri", "email" string formats
  192. STRING_FORMAT_RULES = {
  193. 'date' : BuiltinRule('[0-9]{4} "-" ( "0" [1-9] | "1" [0-2] ) "-" ( \"0\" [1-9] | [1-2] [0-9] | "3" [0-1] )', []),
  194. 'time' : 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] )', []),
  195. 'date-time' : BuiltinRule('date "T" time', ['date', 'time']),
  196. 'date-string' : BuiltinRule('"\\"" date "\\"" space', ['date']),
  197. 'time-string' : BuiltinRule('"\\"" time "\\"" space', ['time']),
  198. 'date-time-string': BuiltinRule('"\\"" date-time "\\"" space', ['date-time']),
  199. }
  200. DOTALL = '[\\U00000000-\\U0010FFFF]'
  201. DOT = '[^\\x0A\\x0D]'
  202. RESERVED_NAMES = set(["root", "dot", *PRIMITIVE_RULES.keys(), *STRING_FORMAT_RULES.keys()])
  203. INVALID_RULE_CHARS_RE = re.compile(r'[^a-zA-Z0-9-]+')
  204. GRAMMAR_LITERAL_ESCAPE_RE = re.compile(r'[\r\n"]')
  205. GRAMMAR_RANGE_LITERAL_ESCAPE_RE = re.compile(r'[\r\n"\]\-\\]')
  206. GRAMMAR_LITERAL_ESCAPES = {'\r': '\\r', '\n': '\\n', '"': '\\"', '-': '\\-', ']': '\\]'}
  207. NON_LITERAL_SET = set('|.()[]{}*+?')
  208. ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = set('[]()|{}*+?')
  209. class SchemaConverter:
  210. def __init__(self, *, prop_order, allow_fetch, dotall, raw_pattern):
  211. self._prop_order = prop_order
  212. self._allow_fetch = allow_fetch
  213. self._dotall = dotall
  214. self._raw_pattern = raw_pattern
  215. self._rules = {
  216. 'space': SPACE_RULE,
  217. }
  218. self._refs = {}
  219. self._refs_being_resolved = set()
  220. def _format_literal(self, literal):
  221. escaped = GRAMMAR_LITERAL_ESCAPE_RE.sub(
  222. lambda m: GRAMMAR_LITERAL_ESCAPES.get(m.group(0)), literal
  223. )
  224. return f'"{escaped}"'
  225. def not_literal(self, literal: str, dotall: bool = True, maybe_escaped_underscores = False) -> str:
  226. '''
  227. not_literal('a') -> '[^a]'
  228. not_literal('abc') -> '([^a] | "a" ([^b] | "b" ([^c])?)?)?'
  229. '''
  230. assert len(literal) > 0, 'Empty literal not supported'
  231. def recurse(i: int):
  232. c = literal[i]
  233. if maybe_escaped_underscores and c == '_':
  234. yield f'[^{c}\\\\]'
  235. yield ' | '
  236. yield f'"\\\\"? "{c}"'
  237. else:
  238. yield f'[^{c}]'
  239. if i < len(literal) - 1:
  240. yield ' | '
  241. yield self._format_literal(c)
  242. yield ' ('
  243. yield from recurse(i + 1)
  244. yield ')?'
  245. return ''.join(('(', *recurse(0), ')'))
  246. def _add_rule(self, name, rule):
  247. esc_name = INVALID_RULE_CHARS_RE.sub('-', name)
  248. if esc_name not in self._rules or self._rules[esc_name] == rule:
  249. key = esc_name
  250. else:
  251. i = 0
  252. while f'{esc_name}{i}' in self._rules and self._rules[f'{esc_name}{i}'] != rule:
  253. i += 1
  254. key = f'{esc_name}{i}'
  255. self._rules[key] = rule
  256. return key
  257. def resolve_refs(self, schema: dict, url: str):
  258. '''
  259. Resolves all $ref fields in the given schema, fetching any remote schemas,
  260. replacing $ref with absolute reference URL and populating self._refs with the
  261. respective referenced (sub)schema dictionaries.
  262. '''
  263. def visit(n: dict):
  264. if isinstance(n, list):
  265. return [visit(x) for x in n]
  266. elif isinstance(n, dict):
  267. ref = n.get('$ref')
  268. if ref is not None and ref not in self._refs:
  269. if ref.startswith('https://'):
  270. assert self._allow_fetch, 'Fetching remote schemas is not allowed (use --allow-fetch for force)'
  271. import requests
  272. frag_split = ref.split('#')
  273. base_url = frag_split[0]
  274. target = self._refs.get(base_url)
  275. if target is None:
  276. target = self.resolve_refs(requests.get(ref).json(), base_url)
  277. self._refs[base_url] = target
  278. if len(frag_split) == 1 or frag_split[-1] == '':
  279. return target
  280. elif ref.startswith('#/'):
  281. target = schema
  282. ref = f'{url}{ref}'
  283. n['$ref'] = ref
  284. else:
  285. raise ValueError(f'Unsupported ref {ref}')
  286. for sel in ref.split('#')[-1].split('/')[1:]:
  287. assert target is not None and sel in target, f'Error resolving ref {ref}: {sel} not in {target}'
  288. target = target[sel]
  289. self._refs[ref] = target
  290. else:
  291. for v in n.values():
  292. visit(v)
  293. return n
  294. return visit(schema)
  295. def _generate_union_rule(self, name, alt_schemas):
  296. return ' | '.join((
  297. self.visit(alt_schema, f'{name}{"-" if name else "alternative-"}{i}')
  298. for i, alt_schema in enumerate(alt_schemas)
  299. ))
  300. def _visit_pattern(self, pattern, name):
  301. '''
  302. Transforms a regular expression pattern into a GBNF rule.
  303. Input: https://json-schema.org/understanding-json-schema/reference/regular_expressions
  304. Output: https://github.com/ggerganov/llama.cpp/blob/master/grammars/README.md
  305. Unsupported features: negative/positive lookaheads, greedy/non-greedy modifiers.
  306. Mostly a 1:1 translation, except for {x} / {x,} / {x,y} quantifiers for which
  307. we define sub-rules to keep the output lean.
  308. '''
  309. assert pattern.startswith('^') and pattern.endswith('$'), 'Pattern must start with "^" and end with "$"'
  310. pattern = pattern[1:-1]
  311. sub_rule_ids = {}
  312. i = 0
  313. length = len(pattern)
  314. def to_rule(s: Tuple[str, bool]) -> str:
  315. (txt, is_literal) = s
  316. return "\"" + txt + "\"" if is_literal else txt
  317. def transform() -> Tuple[str, bool]:
  318. '''
  319. Parse a unit at index i (advancing it), and return its string representation + whether it's a literal.
  320. '''
  321. nonlocal i
  322. nonlocal pattern
  323. nonlocal sub_rule_ids
  324. start = i
  325. # For each component of this sequence, store its string representation and whether it's a literal.
  326. # We only need a flat structure here to apply repetition operators to the last item, and
  327. # to merge literals at the and (we're parsing grouped ( sequences ) recursively and don't treat '|' specially
  328. # (GBNF's syntax is luckily very close to regular expressions!)
  329. seq: list[Tuple[str, bool]] = []
  330. def get_dot():
  331. if self._dotall:
  332. rule = DOTALL
  333. else:
  334. # Accept any character... except \n and \r line break chars (\x0A and \xOD)
  335. rule = DOT
  336. return self._add_rule(f'dot', rule)
  337. def join_seq():
  338. nonlocal seq
  339. ret = []
  340. for is_literal, g in itertools.groupby(seq, lambda x: x[1]):
  341. if is_literal:
  342. ret.append((''.join(x[0] for x in g), True))
  343. else:
  344. ret.extend(g)
  345. if len(ret) == 1:
  346. return ret[0]
  347. return (' '.join(to_rule(x) for x in seq), False)
  348. while i < length:
  349. c = pattern[i]
  350. if c == '.':
  351. seq.append((get_dot(), False))
  352. i += 1
  353. elif c == '(':
  354. i += 1
  355. if i < length:
  356. assert pattern[i] != '?', f'Unsupported pattern syntax "{pattern[i]}" at index {i} of /{pattern}/'
  357. seq.append((f'({to_rule(transform())})', False))
  358. elif c == ')':
  359. i += 1
  360. assert start > 0 and pattern[start-1] == '(', f'Unbalanced parentheses; start = {start}, i = {i}, pattern = {pattern}'
  361. return join_seq()
  362. elif c == '[':
  363. square_brackets = c
  364. i += 1
  365. while i < length and pattern[i] != ']':
  366. if pattern[i] == '\\':
  367. square_brackets += pattern[i:i+2]
  368. i += 2
  369. else:
  370. square_brackets += pattern[i]
  371. i += 1
  372. assert i < length, f'Unbalanced square brackets; start = {start}, i = {i}, pattern = {pattern}'
  373. square_brackets += ']'
  374. i += 1
  375. seq.append((square_brackets, False))
  376. elif c == '|':
  377. seq.append(('|', False))
  378. i += 1
  379. elif c in ('*', '+', '?'):
  380. seq[-1] = (to_rule(seq[-1]) + c, False)
  381. i += 1
  382. elif c == '{':
  383. curly_brackets = c
  384. i += 1
  385. while i < length and pattern[i] != '}':
  386. curly_brackets += pattern[i]
  387. i += 1
  388. assert i < length, f'Unbalanced curly brackets; start = {start}, i = {i}, pattern = {pattern}'
  389. curly_brackets += '}'
  390. i += 1
  391. nums = [s.strip() for s in curly_brackets[1:-1].split(',')]
  392. min_times = 0
  393. max_times = None
  394. try:
  395. if len(nums) == 1:
  396. min_times = int(nums[0])
  397. max_times = min_times
  398. else:
  399. assert len(nums) == 2
  400. min_times = int(nums[0]) if nums[0] else 0
  401. max_times = int(nums[1]) if nums[1] else None
  402. except ValueError:
  403. raise ValueError(f'Invalid quantifier {curly_brackets} in /{pattern}/')
  404. (sub, sub_is_literal) = seq[-1]
  405. if not sub_is_literal:
  406. id = sub_rule_ids.get(sub)
  407. if id is None:
  408. id = self._add_rule(f'{name}-{len(sub_rule_ids) + 1}', sub)
  409. sub_rule_ids[sub] = id
  410. sub = id
  411. seq[-1] = (_build_repetition(f'"{sub}"' if sub_is_literal else sub, min_times, max_times), False)
  412. else:
  413. literal = ''
  414. while i < length:
  415. if pattern[i] == '\\' and i < length - 1:
  416. next = pattern[i + 1]
  417. if next in ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS:
  418. i += 1
  419. literal += pattern[i]
  420. i += 1
  421. else:
  422. literal += pattern[i:i+2]
  423. i += 2
  424. elif pattern[i] == '"' and not self._raw_pattern:
  425. literal += '\\"'
  426. i += 1
  427. elif pattern[i] not in NON_LITERAL_SET and \
  428. (i == length - 1 or literal == '' or pattern[i+1] == '.' or pattern[i+1] not in NON_LITERAL_SET):
  429. literal += pattern[i]
  430. i += 1
  431. else:
  432. break
  433. if literal:
  434. seq.append((literal, True))
  435. return join_seq()
  436. return self._add_rule(
  437. name,
  438. to_rule(transform()) if self._raw_pattern \
  439. else "\"\\\"\" " + to_rule(transform()) + " \"\\\"\" space")
  440. def _resolve_ref(self, ref):
  441. ref_name = ref.split('/')[-1]
  442. if ref_name not in self._rules and ref not in self._refs_being_resolved:
  443. self._refs_being_resolved.add(ref)
  444. resolved = self._refs[ref]
  445. ref_name = self.visit(resolved, ref_name)
  446. self._refs_being_resolved.remove(ref)
  447. return ref_name
  448. def _generate_constant_rule(self, value):
  449. return self._format_literal(json.dumps(value))
  450. def visit(self, schema, name):
  451. schema_type = schema.get('type')
  452. schema_format = schema.get('format')
  453. rule_name = name + '-' if name in RESERVED_NAMES else name or 'root'
  454. if (ref := schema.get('$ref')) is not None:
  455. return self._add_rule(rule_name, self._resolve_ref(ref))
  456. elif 'oneOf' in schema or 'anyOf' in schema:
  457. return self._add_rule(rule_name, self._generate_union_rule(name, schema.get('oneOf') or schema['anyOf']))
  458. elif isinstance(schema_type, list):
  459. return self._add_rule(rule_name, self._generate_union_rule(name, [{'type': t} for t in schema_type]))
  460. elif 'const' in schema:
  461. return self._add_rule(rule_name, self._generate_constant_rule(schema['const']))
  462. elif 'enum' in schema:
  463. rule = ' | '.join((self._generate_constant_rule(v) for v in schema['enum']))
  464. return self._add_rule(rule_name, rule)
  465. elif schema_type in (None, 'object') and \
  466. ('properties' in schema or \
  467. ('additionalProperties' in schema and schema['additionalProperties'] is not True)):
  468. required = set(schema.get('required', []))
  469. properties = list(schema.get('properties', {}).items())
  470. return self._add_rule(rule_name, self._build_object_rule(properties, required, name, schema.get('additionalProperties')))
  471. elif schema_type in (None, 'object') and 'allOf' in schema:
  472. required = set()
  473. properties = []
  474. hybrid_name = name
  475. def add_component(comp_schema, is_required):
  476. if (ref := comp_schema.get('$ref')) is not None:
  477. comp_schema = self._refs[ref]
  478. if 'properties' in comp_schema:
  479. for prop_name, prop_schema in comp_schema['properties'].items():
  480. properties.append((prop_name, prop_schema))
  481. if is_required:
  482. required.add(prop_name)
  483. for t in schema['allOf']:
  484. if 'anyOf' in t:
  485. for tt in t['anyOf']:
  486. add_component(tt, is_required=False)
  487. else:
  488. add_component(t, is_required=True)
  489. return self._add_rule(rule_name, self._build_object_rule(properties, required, hybrid_name, additional_properties=[]))
  490. elif schema_type in (None, 'array') and ('items' in schema or 'prefixItems' in schema):
  491. items = schema.get('items') or schema['prefixItems']
  492. if isinstance(items, list):
  493. return self._add_rule(
  494. rule_name,
  495. '"[" space ' +
  496. ' "," space '.join(
  497. self.visit(item, f'{name}{"-" if name else ""}tuple-{i}')
  498. for i, item in enumerate(items)) +
  499. ' "]" space')
  500. else:
  501. item_rule_name = self.visit(items, f'{name}{"-" if name else ""}item')
  502. min_items = schema.get("minItems", 0)
  503. max_items = schema.get("maxItems")
  504. return self._add_rule(rule_name, '"[" space ' + _build_repetition(item_rule_name, min_items, max_items, separator_rule='"," space') + ' "]" space')
  505. elif schema_type in (None, 'string') and 'pattern' in schema:
  506. return self._visit_pattern(schema['pattern'], rule_name)
  507. elif schema_type in (None, 'string') and re.match(r'^uuid[1-5]?$', schema_format or ''):
  508. return self._add_primitive(
  509. 'root' if rule_name == 'root' else schema_format,
  510. PRIMITIVE_RULES['uuid']
  511. )
  512. elif schema_type in (None, 'string') and f'{schema_format}-string' in STRING_FORMAT_RULES:
  513. prim_name = f'{schema_format}-string'
  514. return self._add_rule(rule_name, self._add_primitive(prim_name, STRING_FORMAT_RULES[prim_name]))
  515. elif schema_type == 'string' and ('minLength' in schema or 'maxLength' in schema):
  516. char_rule = self._add_primitive('char', PRIMITIVE_RULES['char'])
  517. min_len = schema.get('minLength', 0)
  518. max_len = schema.get('maxLength')
  519. return self._add_rule(rule_name, r'"\"" ' + _build_repetition(char_rule, min_len, max_len) + r' "\"" space')
  520. elif schema_type in (None, 'integer') and \
  521. ('minimum' in schema or 'exclusiveMinimum' in schema or 'maximum' in schema or 'exclusiveMaximum' in schema):
  522. min_value = None
  523. max_value = None
  524. if 'minimum' in schema:
  525. min_value = schema['minimum']
  526. elif 'exclusiveMinimum' in schema:
  527. min_value = schema['exclusiveMinimum'] + 1
  528. if 'maximum' in schema:
  529. max_value = schema['maximum']
  530. elif 'exclusiveMaximum' in schema:
  531. max_value = schema['exclusiveMaximum'] - 1
  532. out = ["("]
  533. _generate_min_max_int(min_value, max_value, out)
  534. out.append(") space")
  535. return self._add_rule(rule_name, ''.join(out))
  536. elif (schema_type == 'object') or (len(schema) == 0):
  537. return self._add_rule(rule_name, self._add_primitive('object', PRIMITIVE_RULES['object']))
  538. else:
  539. assert schema_type in PRIMITIVE_RULES, f'Unrecognized schema: {schema}'
  540. # TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
  541. return self._add_primitive('root' if rule_name == 'root' else schema_type, PRIMITIVE_RULES[schema_type])
  542. def _add_primitive(self, name: str, rule: BuiltinRule):
  543. n = self._add_rule(name, rule.content)
  544. for dep in rule.deps:
  545. dep_rule = PRIMITIVE_RULES.get(dep) or STRING_FORMAT_RULES.get(dep)
  546. assert dep_rule, f'Rule {dep} not known'
  547. if dep not in self._rules:
  548. self._add_primitive(dep, dep_rule)
  549. return n
  550. def _build_object_rule(self, properties: List[Tuple[str, Any]], required: Set[str], name: str, additional_properties: Union[bool, Any]):
  551. prop_order = self._prop_order
  552. # sort by position in prop_order (if specified) then by original order
  553. sorted_props = [kv[0] for _, kv in sorted(enumerate(properties), key=lambda ikv: (prop_order.get(ikv[1][0], len(prop_order)), ikv[0]))]
  554. prop_kv_rule_names = {}
  555. for prop_name, prop_schema in properties:
  556. prop_rule_name = self.visit(prop_schema, f'{name}{"-" if name else ""}{prop_name}')
  557. prop_kv_rule_names[prop_name] = self._add_rule(
  558. f'{name}{"-" if name else ""}{prop_name}-kv',
  559. fr'{self._format_literal(json.dumps(prop_name))} space ":" space {prop_rule_name}'
  560. )
  561. required_props = [k for k in sorted_props if k in required]
  562. optional_props = [k for k in sorted_props if k not in required]
  563. if additional_properties == True or isinstance(additional_properties, dict):
  564. sub_name = f'{name}{"-" if name else ""}additional'
  565. value_rule = self.visit({} if additional_properties == True else additional_properties, f'{sub_name}-value')
  566. prop_kv_rule_names["*"] = self._add_rule(
  567. f'{sub_name}-kv',
  568. self._add_primitive('string', PRIMITIVE_RULES['string']) + f' ":" space {value_rule}'
  569. )
  570. optional_props.append("*")
  571. rule = '"{" space '
  572. rule += ' "," space '.join(prop_kv_rule_names[k] for k in required_props)
  573. if optional_props:
  574. rule += ' ('
  575. if required_props:
  576. rule += ' "," space ( '
  577. def get_recursive_refs(ks, first_is_optional):
  578. [k, *rest] = ks
  579. kv_rule_name = prop_kv_rule_names[k]
  580. if k == '*':
  581. res = self._add_rule(
  582. f'{name}{"-" if name else ""}additional-kvs',
  583. f'{kv_rule_name} ( "," space ' + kv_rule_name + ' )*'
  584. )
  585. elif first_is_optional:
  586. res = f'( "," space {kv_rule_name} )?'
  587. else:
  588. res = kv_rule_name
  589. if len(rest) > 0:
  590. res += ' ' + self._add_rule(
  591. f'{name}{"-" if name else ""}{k}-rest',
  592. get_recursive_refs(rest, first_is_optional=True)
  593. )
  594. return res
  595. rule += ' | '.join(
  596. get_recursive_refs(optional_props[i:], first_is_optional=False)
  597. for i in range(len(optional_props))
  598. )
  599. if required_props:
  600. rule += ' )'
  601. rule += ' )?'
  602. rule += ' "}" space'
  603. return rule
  604. def format_grammar(self):
  605. return '\n'.join(
  606. f'{name} ::= {rule}'
  607. for name, rule in sorted(self._rules.items(), key=lambda kv: kv[0])
  608. )
  609. def main(args_in = None):
  610. parser = argparse.ArgumentParser(
  611. description='''
  612. Generates a grammar (suitable for use in ./llama-cli) that produces JSON conforming to a
  613. given JSON schema. Only a subset of JSON schema features are supported; more may be
  614. added in the future.
  615. ''',
  616. )
  617. parser.add_argument(
  618. '--prop-order',
  619. default=[],
  620. type=lambda s: s.split(','),
  621. help='''
  622. comma-separated property names defining the order of precedence for object properties;
  623. properties not specified here are given lower precedence than those that are, and
  624. are kept in their original order from the schema. Required properties are always
  625. given precedence over optional properties.
  626. '''
  627. )
  628. parser.add_argument(
  629. '--allow-fetch',
  630. action='store_true',
  631. default=False,
  632. help='Whether to allow fetching referenced schemas over HTTPS')
  633. parser.add_argument(
  634. '--dotall',
  635. action='store_true',
  636. default=False,
  637. help='Whether to treat dot (".") as matching all chars including line breaks in regular expression patterns')
  638. parser.add_argument(
  639. '--raw-pattern',
  640. action='store_true',
  641. default=False,
  642. help='Treats string patterns as raw patterns w/o quotes (or quote escapes)')
  643. parser.add_argument('schema', help='file containing JSON schema ("-" for stdin)')
  644. args = parser.parse_args(args_in)
  645. if args.schema.startswith('https://'):
  646. url = args.schema
  647. import requests
  648. schema = requests.get(url).json()
  649. elif args.schema == '-':
  650. url = 'stdin'
  651. schema = json.load(sys.stdin)
  652. else:
  653. url = f'file://{args.schema}'
  654. with open(args.schema) as f:
  655. schema = json.load(f)
  656. converter = SchemaConverter(
  657. prop_order={name: idx for idx, name in enumerate(args.prop_order)},
  658. allow_fetch=args.allow_fetch,
  659. dotall=args.dotall,
  660. raw_pattern=args.raw_pattern)
  661. schema = converter.resolve_refs(schema, url)
  662. converter.visit(schema, '')
  663. print(converter.format_grammar())
  664. if __name__ == '__main__':
  665. main()