json_schema_to_grammar.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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, 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 _not_strings(self, strings):
  247. class TrieNode:
  248. def __init__(self):
  249. self.children = {}
  250. self.is_end_of_string = False
  251. def insert(self, string):
  252. node = self
  253. for c in string:
  254. node = node.children.setdefault(c, TrieNode())
  255. node.is_end_of_string = True
  256. trie = TrieNode()
  257. for s in strings:
  258. trie.insert(s)
  259. char_rule = self._add_primitive('char', PRIMITIVE_RULES['char'])
  260. out = ['["] ( ']
  261. def visit(node):
  262. rejects = []
  263. first = True
  264. for c in sorted(node.children.keys()):
  265. child = node.children[c]
  266. rejects.append(c)
  267. if first:
  268. first = False
  269. else:
  270. out.append(' | ')
  271. out.append(f'[{c}]')
  272. if child.children:
  273. out.append(f' (')
  274. visit(child)
  275. out.append(')')
  276. elif child.is_end_of_string:
  277. out.append(f' {char_rule}+')
  278. if node.children:
  279. if not first:
  280. out.append(' | ')
  281. out.append(f'[^"{"".join(rejects)}] {char_rule}*')
  282. visit(trie)
  283. out.append(f' ){"" if trie.is_end_of_string else "?"} ["] space')
  284. return ''.join(out)
  285. def _add_rule(self, name, rule):
  286. esc_name = INVALID_RULE_CHARS_RE.sub('-', name)
  287. if esc_name not in self._rules or self._rules[esc_name] == rule:
  288. key = esc_name
  289. else:
  290. i = 0
  291. while f'{esc_name}{i}' in self._rules and self._rules[f'{esc_name}{i}'] != rule:
  292. i += 1
  293. key = f'{esc_name}{i}'
  294. self._rules[key] = rule
  295. return key
  296. def resolve_refs(self, schema: dict, url: str):
  297. '''
  298. Resolves all $ref fields in the given schema, fetching any remote schemas,
  299. replacing $ref with absolute reference URL and populating self._refs with the
  300. respective referenced (sub)schema dictionaries.
  301. '''
  302. def visit(n: dict):
  303. if isinstance(n, list):
  304. return [visit(x) for x in n]
  305. elif isinstance(n, dict):
  306. ref = n.get('$ref')
  307. if ref is not None and ref not in self._refs:
  308. if ref.startswith('https://'):
  309. assert self._allow_fetch, 'Fetching remote schemas is not allowed (use --allow-fetch for force)'
  310. import requests
  311. frag_split = ref.split('#')
  312. base_url = frag_split[0]
  313. target = self._refs.get(base_url)
  314. if target is None:
  315. target = self.resolve_refs(requests.get(ref).json(), base_url)
  316. self._refs[base_url] = target
  317. if len(frag_split) == 1 or frag_split[-1] == '':
  318. return target
  319. elif ref.startswith('#/'):
  320. target = schema
  321. ref = f'{url}{ref}'
  322. n['$ref'] = ref
  323. else:
  324. raise ValueError(f'Unsupported ref {ref}')
  325. for sel in ref.split('#')[-1].split('/')[1:]:
  326. assert target is not None and sel in target, f'Error resolving ref {ref}: {sel} not in {target}'
  327. target = target[sel]
  328. self._refs[ref] = target
  329. else:
  330. for v in n.values():
  331. visit(v)
  332. return n
  333. return visit(schema)
  334. def _generate_union_rule(self, name, alt_schemas):
  335. return ' | '.join((
  336. self.visit(alt_schema, f'{name}{"-" if name else "alternative-"}{i}')
  337. for i, alt_schema in enumerate(alt_schemas)
  338. ))
  339. def _visit_pattern(self, pattern, name):
  340. '''
  341. Transforms a regular expression pattern into a GBNF rule.
  342. Input: https://json-schema.org/understanding-json-schema/reference/regular_expressions
  343. Output: https://github.com/ggerganov/llama.cpp/blob/master/grammars/README.md
  344. Unsupported features: negative/positive lookaheads, greedy/non-greedy modifiers.
  345. Mostly a 1:1 translation, except for {x} / {x,} / {x,y} quantifiers for which
  346. we define sub-rules to keep the output lean.
  347. '''
  348. assert pattern.startswith('^') and pattern.endswith('$'), 'Pattern must start with "^" and end with "$"'
  349. pattern = pattern[1:-1]
  350. sub_rule_ids = {}
  351. i = 0
  352. length = len(pattern)
  353. def to_rule(s: Tuple[str, bool]) -> str:
  354. (txt, is_literal) = s
  355. return "\"" + txt + "\"" if is_literal else txt
  356. def transform() -> Tuple[str, bool]:
  357. '''
  358. Parse a unit at index i (advancing it), and return its string representation + whether it's a literal.
  359. '''
  360. nonlocal i
  361. nonlocal pattern
  362. nonlocal sub_rule_ids
  363. start = i
  364. # For each component of this sequence, store its string representation and whether it's a literal.
  365. # We only need a flat structure here to apply repetition operators to the last item, and
  366. # to merge literals at the and (we're parsing grouped ( sequences ) recursively and don't treat '|' specially
  367. # (GBNF's syntax is luckily very close to regular expressions!)
  368. seq: list[Tuple[str, bool]] = []
  369. def get_dot():
  370. if self._dotall:
  371. rule = DOTALL
  372. else:
  373. # Accept any character... except \n and \r line break chars (\x0A and \xOD)
  374. rule = DOT
  375. return self._add_rule(f'dot', rule)
  376. def join_seq():
  377. nonlocal seq
  378. ret = []
  379. for is_literal, g in itertools.groupby(seq, lambda x: x[1]):
  380. if is_literal:
  381. ret.append((''.join(x[0] for x in g), True))
  382. else:
  383. ret.extend(g)
  384. if len(ret) == 1:
  385. return ret[0]
  386. return (' '.join(to_rule(x) for x in seq), False)
  387. while i < length:
  388. c = pattern[i]
  389. if c == '.':
  390. seq.append((get_dot(), False))
  391. i += 1
  392. elif c == '(':
  393. i += 1
  394. if i < length:
  395. assert pattern[i] != '?', f'Unsupported pattern syntax "{pattern[i]}" at index {i} of /{pattern}/'
  396. seq.append((f'({to_rule(transform())})', False))
  397. elif c == ')':
  398. i += 1
  399. assert start > 0 and pattern[start-1] == '(', f'Unbalanced parentheses; start = {start}, i = {i}, pattern = {pattern}'
  400. return join_seq()
  401. elif c == '[':
  402. square_brackets = c
  403. i += 1
  404. while i < length and pattern[i] != ']':
  405. if pattern[i] == '\\':
  406. square_brackets += pattern[i:i+2]
  407. i += 2
  408. else:
  409. square_brackets += pattern[i]
  410. i += 1
  411. assert i < length, f'Unbalanced square brackets; start = {start}, i = {i}, pattern = {pattern}'
  412. square_brackets += ']'
  413. i += 1
  414. seq.append((square_brackets, False))
  415. elif c == '|':
  416. seq.append(('|', False))
  417. i += 1
  418. elif c in ('*', '+', '?'):
  419. seq[-1] = (to_rule(seq[-1]) + c, False)
  420. i += 1
  421. elif c == '{':
  422. curly_brackets = c
  423. i += 1
  424. while i < length and pattern[i] != '}':
  425. curly_brackets += pattern[i]
  426. i += 1
  427. assert i < length, f'Unbalanced curly brackets; start = {start}, i = {i}, pattern = {pattern}'
  428. curly_brackets += '}'
  429. i += 1
  430. nums = [s.strip() for s in curly_brackets[1:-1].split(',')]
  431. min_times = 0
  432. max_times = None
  433. try:
  434. if len(nums) == 1:
  435. min_times = int(nums[0])
  436. max_times = min_times
  437. else:
  438. assert len(nums) == 2
  439. min_times = int(nums[0]) if nums[0] else 0
  440. max_times = int(nums[1]) if nums[1] else None
  441. except ValueError:
  442. raise ValueError(f'Invalid quantifier {curly_brackets} in /{pattern}/')
  443. (sub, sub_is_literal) = seq[-1]
  444. if not sub_is_literal:
  445. id = sub_rule_ids.get(sub)
  446. if id is None:
  447. id = self._add_rule(f'{name}-{len(sub_rule_ids) + 1}', sub)
  448. sub_rule_ids[sub] = id
  449. sub = id
  450. seq[-1] = (_build_repetition(f'"{sub}"' if sub_is_literal else sub, min_times, max_times), False)
  451. else:
  452. literal = ''
  453. while i < length:
  454. if pattern[i] == '\\' and i < length - 1:
  455. next = pattern[i + 1]
  456. if next in ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS:
  457. i += 1
  458. literal += pattern[i]
  459. i += 1
  460. else:
  461. literal += pattern[i:i+2]
  462. i += 2
  463. elif pattern[i] == '"' and not self._raw_pattern:
  464. literal += '\\"'
  465. i += 1
  466. elif pattern[i] not in NON_LITERAL_SET and \
  467. (i == length - 1 or literal == '' or pattern[i+1] == '.' or pattern[i+1] not in NON_LITERAL_SET):
  468. literal += pattern[i]
  469. i += 1
  470. else:
  471. break
  472. if literal:
  473. seq.append((literal, True))
  474. return join_seq()
  475. return self._add_rule(
  476. name,
  477. to_rule(transform()) if self._raw_pattern \
  478. else "\"\\\"\" " + to_rule(transform()) + " \"\\\"\" space")
  479. def _resolve_ref(self, ref):
  480. ref_name = ref.split('/')[-1]
  481. if ref_name not in self._rules and ref not in self._refs_being_resolved:
  482. self._refs_being_resolved.add(ref)
  483. resolved = self._refs[ref]
  484. ref_name = self.visit(resolved, ref_name)
  485. self._refs_being_resolved.remove(ref)
  486. return ref_name
  487. def _generate_constant_rule(self, value):
  488. return self._format_literal(json.dumps(value))
  489. def visit(self, schema, name):
  490. schema_type = schema.get('type')
  491. schema_format = schema.get('format')
  492. rule_name = name + '-' if name in RESERVED_NAMES else name or 'root'
  493. if (ref := schema.get('$ref')) is not None:
  494. return self._add_rule(rule_name, self._resolve_ref(ref))
  495. elif 'oneOf' in schema or 'anyOf' in schema:
  496. return self._add_rule(rule_name, self._generate_union_rule(name, schema.get('oneOf') or schema['anyOf']))
  497. elif isinstance(schema_type, list):
  498. return self._add_rule(rule_name, self._generate_union_rule(name, [{**schema, 'type': t} for t in schema_type]))
  499. elif 'const' in schema:
  500. return self._add_rule(rule_name, self._generate_constant_rule(schema['const']) + ' space')
  501. elif 'enum' in schema:
  502. rule = '(' + ' | '.join((self._generate_constant_rule(v) for v in schema['enum'])) + ') space'
  503. return self._add_rule(rule_name, rule)
  504. elif schema_type in (None, 'object') and \
  505. ('properties' in schema or \
  506. ('additionalProperties' in schema and schema['additionalProperties'] is not True)):
  507. required = set(schema.get('required', []))
  508. properties = list(schema.get('properties', {}).items())
  509. return self._add_rule(rule_name, self._build_object_rule(properties, required, name, schema.get('additionalProperties')))
  510. elif schema_type in (None, 'object') and 'allOf' in schema:
  511. required = set()
  512. properties = []
  513. hybrid_name = name
  514. def add_component(comp_schema, is_required):
  515. if (ref := comp_schema.get('$ref')) is not None:
  516. comp_schema = self._refs[ref]
  517. if 'properties' in comp_schema:
  518. for prop_name, prop_schema in comp_schema['properties'].items():
  519. properties.append((prop_name, prop_schema))
  520. if is_required:
  521. required.add(prop_name)
  522. for t in schema['allOf']:
  523. if 'anyOf' in t:
  524. for tt in t['anyOf']:
  525. add_component(tt, is_required=False)
  526. else:
  527. add_component(t, is_required=True)
  528. return self._add_rule(rule_name, self._build_object_rule(properties, required, hybrid_name, additional_properties=None))
  529. elif schema_type in (None, 'array') and ('items' in schema or 'prefixItems' in schema):
  530. items = schema.get('items') or schema['prefixItems']
  531. if isinstance(items, list):
  532. return self._add_rule(
  533. rule_name,
  534. '"[" space ' +
  535. ' "," space '.join(
  536. self.visit(item, f'{name}{"-" if name else ""}tuple-{i}')
  537. for i, item in enumerate(items)) +
  538. ' "]" space')
  539. else:
  540. item_rule_name = self.visit(items, f'{name}{"-" if name else ""}item')
  541. min_items = schema.get("minItems", 0)
  542. max_items = schema.get("maxItems")
  543. return self._add_rule(rule_name, '"[" space ' + _build_repetition(item_rule_name, min_items, max_items, separator_rule='"," space') + ' "]" space')
  544. elif schema_type in (None, 'string') and 'pattern' in schema:
  545. return self._visit_pattern(schema['pattern'], rule_name)
  546. elif schema_type in (None, 'string') and re.match(r'^uuid[1-5]?$', schema_format or ''):
  547. return self._add_primitive(
  548. 'root' if rule_name == 'root' else schema_format,
  549. PRIMITIVE_RULES['uuid']
  550. )
  551. elif schema_type in (None, 'string') and f'{schema_format}-string' in STRING_FORMAT_RULES:
  552. prim_name = f'{schema_format}-string'
  553. return self._add_rule(rule_name, self._add_primitive(prim_name, STRING_FORMAT_RULES[prim_name]))
  554. elif schema_type == 'string' and ('minLength' in schema or 'maxLength' in schema):
  555. char_rule = self._add_primitive('char', PRIMITIVE_RULES['char'])
  556. min_len = schema.get('minLength', 0)
  557. max_len = schema.get('maxLength')
  558. return self._add_rule(rule_name, r'"\"" ' + _build_repetition(char_rule, min_len, max_len) + r' "\"" space')
  559. elif schema_type in (None, 'integer') and \
  560. ('minimum' in schema or 'exclusiveMinimum' in schema or 'maximum' in schema or 'exclusiveMaximum' in schema):
  561. min_value = None
  562. max_value = None
  563. if 'minimum' in schema:
  564. min_value = schema['minimum']
  565. elif 'exclusiveMinimum' in schema:
  566. min_value = schema['exclusiveMinimum'] + 1
  567. if 'maximum' in schema:
  568. max_value = schema['maximum']
  569. elif 'exclusiveMaximum' in schema:
  570. max_value = schema['exclusiveMaximum'] - 1
  571. out = ["("]
  572. _generate_min_max_int(min_value, max_value, out)
  573. out.append(") space")
  574. return self._add_rule(rule_name, ''.join(out))
  575. elif (schema_type == 'object') or (len(schema) == 0):
  576. return self._add_rule(rule_name, self._add_primitive('object', PRIMITIVE_RULES['object']))
  577. else:
  578. assert schema_type in PRIMITIVE_RULES, f'Unrecognized schema: {schema}'
  579. # TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero
  580. return self._add_primitive('root' if rule_name == 'root' else schema_type, PRIMITIVE_RULES[schema_type])
  581. def _add_primitive(self, name: str, rule: BuiltinRule):
  582. n = self._add_rule(name, rule.content)
  583. for dep in rule.deps:
  584. dep_rule = PRIMITIVE_RULES.get(dep) or STRING_FORMAT_RULES.get(dep)
  585. assert dep_rule, f'Rule {dep} not known'
  586. if dep not in self._rules:
  587. self._add_primitive(dep, dep_rule)
  588. return n
  589. def _build_object_rule(self, properties: List[Tuple[str, Any]], required: Set[str], name: str, additional_properties: Optional[Union[bool, Any]]):
  590. prop_order = self._prop_order
  591. # sort by position in prop_order (if specified) then by original order
  592. sorted_props = [kv[0] for _, kv in sorted(enumerate(properties), key=lambda ikv: (prop_order.get(ikv[1][0], len(prop_order)), ikv[0]))]
  593. prop_kv_rule_names = {}
  594. for prop_name, prop_schema in properties:
  595. prop_rule_name = self.visit(prop_schema, f'{name}{"-" if name else ""}{prop_name}')
  596. prop_kv_rule_names[prop_name] = self._add_rule(
  597. f'{name}{"-" if name else ""}{prop_name}-kv',
  598. fr'{self._format_literal(json.dumps(prop_name))} space ":" space {prop_rule_name}'
  599. )
  600. required_props = [k for k in sorted_props if k in required]
  601. optional_props = [k for k in sorted_props if k not in required]
  602. if additional_properties is not None and additional_properties != False:
  603. sub_name = f'{name}{"-" if name else ""}additional'
  604. value_rule = self.visit(additional_properties, f'{sub_name}-value') if isinstance(additional_properties, dict) else \
  605. self._add_primitive('value', PRIMITIVE_RULES['value'])
  606. key_rule = self._add_primitive('string', PRIMITIVE_RULES['string']) if not sorted_props \
  607. else self._add_rule(f'{sub_name}-k', self._not_strings(sorted_props))
  608. prop_kv_rule_names["*"] = self._add_rule(
  609. f'{sub_name}-kv',
  610. f'{key_rule} ":" space {value_rule}'
  611. )
  612. optional_props.append("*")
  613. rule = '"{" space '
  614. rule += ' "," space '.join(prop_kv_rule_names[k] for k in required_props)
  615. if optional_props:
  616. rule += ' ('
  617. if required_props:
  618. rule += ' "," space ( '
  619. def get_recursive_refs(ks, first_is_optional):
  620. [k, *rest] = ks
  621. kv_rule_name = prop_kv_rule_names[k]
  622. comma_ref = f'( "," space {kv_rule_name} )'
  623. if first_is_optional:
  624. res = comma_ref + ('*' if k == '*' else '?')
  625. else:
  626. res = kv_rule_name + (' ' + comma_ref + "*" if k == '*' else '')
  627. if len(rest) > 0:
  628. res += ' ' + self._add_rule(
  629. f'{name}{"-" if name else ""}{k}-rest',
  630. get_recursive_refs(rest, first_is_optional=True)
  631. )
  632. return res
  633. rule += ' | '.join(
  634. get_recursive_refs(optional_props[i:], first_is_optional=False)
  635. for i in range(len(optional_props))
  636. )
  637. if required_props:
  638. rule += ' )'
  639. rule += ' )?'
  640. rule += ' "}" space'
  641. return rule
  642. def format_grammar(self):
  643. return '\n'.join(
  644. f'{name} ::= {rule}'
  645. for name, rule in sorted(self._rules.items(), key=lambda kv: kv[0])
  646. )
  647. def main(args_in = None):
  648. parser = argparse.ArgumentParser(
  649. description='''
  650. Generates a grammar (suitable for use in ./llama-cli) that produces JSON conforming to a
  651. given JSON schema. Only a subset of JSON schema features are supported; more may be
  652. added in the future.
  653. ''',
  654. )
  655. parser.add_argument(
  656. '--prop-order',
  657. default=[],
  658. type=lambda s: s.split(','),
  659. help='''
  660. comma-separated property names defining the order of precedence for object properties;
  661. properties not specified here are given lower precedence than those that are, and
  662. are kept in their original order from the schema. Required properties are always
  663. given precedence over optional properties.
  664. '''
  665. )
  666. parser.add_argument(
  667. '--allow-fetch',
  668. action='store_true',
  669. default=False,
  670. help='Whether to allow fetching referenced schemas over HTTPS')
  671. parser.add_argument(
  672. '--dotall',
  673. action='store_true',
  674. default=False,
  675. help='Whether to treat dot (".") as matching all chars including line breaks in regular expression patterns')
  676. parser.add_argument(
  677. '--raw-pattern',
  678. action='store_true',
  679. default=False,
  680. help='Treats string patterns as raw patterns w/o quotes (or quote escapes)')
  681. parser.add_argument('schema', help='file containing JSON schema ("-" for stdin)')
  682. args = parser.parse_args(args_in)
  683. if args.schema.startswith('https://'):
  684. url = args.schema
  685. import requests
  686. schema = requests.get(url).json()
  687. elif args.schema == '-':
  688. url = 'stdin'
  689. schema = json.load(sys.stdin)
  690. else:
  691. url = f'file://{args.schema}'
  692. with open(args.schema) as f:
  693. schema = json.load(f)
  694. converter = SchemaConverter(
  695. prop_order={name: idx for idx, name in enumerate(args.prop_order)},
  696. allow_fetch=args.allow_fetch,
  697. dotall=args.dotall,
  698. raw_pattern=args.raw_pattern)
  699. schema = converter.resolve_refs(schema, url)
  700. converter.visit(schema, '')
  701. print(converter.format_grammar())
  702. if __name__ == '__main__':
  703. main()