1
0

json_schema_to_grammar.py 33 KB

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