compiler.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. r"""
  2. Compiler for a regular grammar.
  3. Example usage::
  4. # Create and compile grammar.
  5. p = compile('add \s+ (?P<var1>[^\s]+) \s+ (?P<var2>[^\s]+)')
  6. # Match input string.
  7. m = p.match('add 23 432')
  8. # Get variables.
  9. m.variables().get('var1') # Returns "23"
  10. m.variables().get('var2') # Returns "432"
  11. Partial matches are possible::
  12. # Create and compile grammar.
  13. p = compile('''
  14. # Operators with two arguments.
  15. ((?P<operator1>[^\s]+) \s+ (?P<var1>[^\s]+) \s+ (?P<var2>[^\s]+)) |
  16. # Operators with only one arguments.
  17. ((?P<operator2>[^\s]+) \s+ (?P<var1>[^\s]+))
  18. ''')
  19. # Match partial input string.
  20. m = p.match_prefix('add 23')
  21. # Get variables. (Notice that both operator1 and operator2 contain the
  22. # value "add".) This is because our input is incomplete, and we don't know
  23. # yet in which rule of the regex we we'll end up. It could also be that
  24. # `operator1` and `operator2` have a different autocompleter and we want to
  25. # call all possible autocompleters that would result in valid input.)
  26. m.variables().get('var1') # Returns "23"
  27. m.variables().get('operator1') # Returns "add"
  28. m.variables().get('operator2') # Returns "add"
  29. """
  30. from __future__ import annotations
  31. import re
  32. from typing import Callable, Dict, Iterable, Iterator, Pattern, TypeVar, overload
  33. from typing import Match as RegexMatch
  34. from .regex_parser import (
  35. AnyNode,
  36. Lookahead,
  37. Node,
  38. NodeSequence,
  39. Regex,
  40. Repeat,
  41. Variable,
  42. parse_regex,
  43. tokenize_regex,
  44. )
  45. __all__ = ["compile", "Match", "Variables"]
  46. # Name of the named group in the regex, matching trailing input.
  47. # (Trailing input is when the input contains characters after the end of the
  48. # expression has been matched.)
  49. _INVALID_TRAILING_INPUT = "invalid_trailing"
  50. EscapeFuncDict = Dict[str, Callable[[str], str]]
  51. class _CompiledGrammar:
  52. """
  53. Compiles a grammar. This will take the parse tree of a regular expression
  54. and compile the grammar.
  55. :param root_node: :class~`.regex_parser.Node` instance.
  56. :param escape_funcs: `dict` mapping variable names to escape callables.
  57. :param unescape_funcs: `dict` mapping variable names to unescape callables.
  58. """
  59. def __init__(
  60. self,
  61. root_node: Node,
  62. escape_funcs: EscapeFuncDict | None = None,
  63. unescape_funcs: EscapeFuncDict | None = None,
  64. ) -> None:
  65. self.root_node = root_node
  66. self.escape_funcs = escape_funcs or {}
  67. self.unescape_funcs = unescape_funcs or {}
  68. #: Dictionary that will map the regex names to Node instances.
  69. self._group_names_to_nodes: dict[
  70. str, str
  71. ] = {} # Maps regex group names to varnames.
  72. counter = [0]
  73. def create_group_func(node: Variable) -> str:
  74. name = f"n{counter[0]}"
  75. self._group_names_to_nodes[name] = node.varname
  76. counter[0] += 1
  77. return name
  78. # Compile regex strings.
  79. self._re_pattern = f"^{self._transform(root_node, create_group_func)}$"
  80. self._re_prefix_patterns = list(
  81. self._transform_prefix(root_node, create_group_func)
  82. )
  83. # Compile the regex itself.
  84. flags = re.DOTALL # Note that we don't need re.MULTILINE! (^ and $
  85. # still represent the start and end of input text.)
  86. self._re = re.compile(self._re_pattern, flags)
  87. self._re_prefix = [re.compile(t, flags) for t in self._re_prefix_patterns]
  88. # We compile one more set of regexes, similar to `_re_prefix`, but accept any trailing
  89. # input. This will ensure that we can still highlight the input correctly, even when the
  90. # input contains some additional characters at the end that don't match the grammar.)
  91. self._re_prefix_with_trailing_input = [
  92. re.compile(
  93. r"(?:{})(?P<{}>.*?)$".format(t.rstrip("$"), _INVALID_TRAILING_INPUT),
  94. flags,
  95. )
  96. for t in self._re_prefix_patterns
  97. ]
  98. def escape(self, varname: str, value: str) -> str:
  99. """
  100. Escape `value` to fit in the place of this variable into the grammar.
  101. """
  102. f = self.escape_funcs.get(varname)
  103. return f(value) if f else value
  104. def unescape(self, varname: str, value: str) -> str:
  105. """
  106. Unescape `value`.
  107. """
  108. f = self.unescape_funcs.get(varname)
  109. return f(value) if f else value
  110. @classmethod
  111. def _transform(
  112. cls, root_node: Node, create_group_func: Callable[[Variable], str]
  113. ) -> str:
  114. """
  115. Turn a :class:`Node` object into a regular expression.
  116. :param root_node: The :class:`Node` instance for which we generate the grammar.
  117. :param create_group_func: A callable which takes a `Node` and returns the next
  118. free name for this node.
  119. """
  120. def transform(node: Node) -> str:
  121. # Turn `AnyNode` into an OR.
  122. if isinstance(node, AnyNode):
  123. return "(?:{})".format("|".join(transform(c) for c in node.children))
  124. # Concatenate a `NodeSequence`
  125. elif isinstance(node, NodeSequence):
  126. return "".join(transform(c) for c in node.children)
  127. # For Regex and Lookahead nodes, just insert them literally.
  128. elif isinstance(node, Regex):
  129. return node.regex
  130. elif isinstance(node, Lookahead):
  131. before = "(?!" if node.negative else "(="
  132. return before + transform(node.childnode) + ")"
  133. # A `Variable` wraps the children into a named group.
  134. elif isinstance(node, Variable):
  135. return f"(?P<{create_group_func(node)}>{transform(node.childnode)})"
  136. # `Repeat`.
  137. elif isinstance(node, Repeat):
  138. if node.max_repeat is None:
  139. if node.min_repeat == 0:
  140. repeat_sign = "*"
  141. elif node.min_repeat == 1:
  142. repeat_sign = "+"
  143. else:
  144. repeat_sign = "{%i,%s}" % (
  145. node.min_repeat,
  146. ("" if node.max_repeat is None else str(node.max_repeat)),
  147. )
  148. return "(?:{}){}{}".format(
  149. transform(node.childnode),
  150. repeat_sign,
  151. ("" if node.greedy else "?"),
  152. )
  153. else:
  154. raise TypeError(f"Got {node!r}")
  155. return transform(root_node)
  156. @classmethod
  157. def _transform_prefix(
  158. cls, root_node: Node, create_group_func: Callable[[Variable], str]
  159. ) -> Iterable[str]:
  160. """
  161. Yield all the regular expressions matching a prefix of the grammar
  162. defined by the `Node` instance.
  163. For each `Variable`, one regex pattern will be generated, with this
  164. named group at the end. This is required because a regex engine will
  165. terminate once a match is found. For autocompletion however, we need
  166. the matches for all possible paths, so that we can provide completions
  167. for each `Variable`.
  168. - So, in the case of an `Any` (`A|B|C)', we generate a pattern for each
  169. clause. This is one for `A`, one for `B` and one for `C`. Unless some
  170. groups don't contain a `Variable`, then these can be merged together.
  171. - In the case of a `NodeSequence` (`ABC`), we generate a pattern for
  172. each prefix that ends with a variable, and one pattern for the whole
  173. sequence. So, that's one for `A`, one for `AB` and one for `ABC`.
  174. :param root_node: The :class:`Node` instance for which we generate the grammar.
  175. :param create_group_func: A callable which takes a `Node` and returns the next
  176. free name for this node.
  177. """
  178. def contains_variable(node: Node) -> bool:
  179. if isinstance(node, Regex):
  180. return False
  181. elif isinstance(node, Variable):
  182. return True
  183. elif isinstance(node, (Lookahead, Repeat)):
  184. return contains_variable(node.childnode)
  185. elif isinstance(node, (NodeSequence, AnyNode)):
  186. return any(contains_variable(child) for child in node.children)
  187. return False
  188. def transform(node: Node) -> Iterable[str]:
  189. # Generate separate pattern for all terms that contain variables
  190. # within this OR. Terms that don't contain a variable can be merged
  191. # together in one pattern.
  192. if isinstance(node, AnyNode):
  193. # If we have a definition like:
  194. # (?P<name> .*) | (?P<city> .*)
  195. # Then we want to be able to generate completions for both the
  196. # name as well as the city. We do this by yielding two
  197. # different regular expressions, because the engine won't
  198. # follow multiple paths, if multiple are possible.
  199. children_with_variable = []
  200. children_without_variable = []
  201. for c in node.children:
  202. if contains_variable(c):
  203. children_with_variable.append(c)
  204. else:
  205. children_without_variable.append(c)
  206. for c in children_with_variable:
  207. yield from transform(c)
  208. # Merge options without variable together.
  209. if children_without_variable:
  210. yield "|".join(
  211. r for c in children_without_variable for r in transform(c)
  212. )
  213. # For a sequence, generate a pattern for each prefix that ends with
  214. # a variable + one pattern of the complete sequence.
  215. # (This is because, for autocompletion, we match the text before
  216. # the cursor, and completions are given for the variable that we
  217. # match right before the cursor.)
  218. elif isinstance(node, NodeSequence):
  219. # For all components in the sequence, compute prefix patterns,
  220. # as well as full patterns.
  221. complete = [cls._transform(c, create_group_func) for c in node.children]
  222. prefixes = [list(transform(c)) for c in node.children]
  223. variable_nodes = [contains_variable(c) for c in node.children]
  224. # If any child is contains a variable, we should yield a
  225. # pattern up to that point, so that we are sure this will be
  226. # matched.
  227. for i in range(len(node.children)):
  228. if variable_nodes[i]:
  229. for c_str in prefixes[i]:
  230. yield "".join(complete[:i]) + c_str
  231. # If there are non-variable nodes, merge all the prefixes into
  232. # one pattern. If the input is: "[part1] [part2] [part3]", then
  233. # this gets compiled into:
  234. # (complete1 + (complete2 + (complete3 | partial3) | partial2) | partial1 )
  235. # For nodes that contain a variable, we skip the "|partial"
  236. # part here, because thees are matched with the previous
  237. # patterns.
  238. if not all(variable_nodes):
  239. result = []
  240. # Start with complete patterns.
  241. for i in range(len(node.children)):
  242. result.append("(?:")
  243. result.append(complete[i])
  244. # Add prefix patterns.
  245. for i in range(len(node.children) - 1, -1, -1):
  246. if variable_nodes[i]:
  247. # No need to yield a prefix for this one, we did
  248. # the variable prefixes earlier.
  249. result.append(")")
  250. else:
  251. result.append("|(?:")
  252. # If this yields multiple, we should yield all combinations.
  253. assert len(prefixes[i]) == 1
  254. result.append(prefixes[i][0])
  255. result.append("))")
  256. yield "".join(result)
  257. elif isinstance(node, Regex):
  258. yield f"(?:{node.regex})?"
  259. elif isinstance(node, Lookahead):
  260. if node.negative:
  261. yield f"(?!{cls._transform(node.childnode, create_group_func)})"
  262. else:
  263. # Not sure what the correct semantics are in this case.
  264. # (Probably it's not worth implementing this.)
  265. raise Exception("Positive lookahead not yet supported.")
  266. elif isinstance(node, Variable):
  267. # (Note that we should not append a '?' here. the 'transform'
  268. # method will already recursively do that.)
  269. for c_str in transform(node.childnode):
  270. yield f"(?P<{create_group_func(node)}>{c_str})"
  271. elif isinstance(node, Repeat):
  272. # If we have a repetition of 8 times. That would mean that the
  273. # current input could have for instance 7 times a complete
  274. # match, followed by a partial match.
  275. prefix = cls._transform(node.childnode, create_group_func)
  276. if node.max_repeat == 1:
  277. yield from transform(node.childnode)
  278. else:
  279. for c_str in transform(node.childnode):
  280. if node.max_repeat:
  281. repeat_sign = "{,%i}" % (node.max_repeat - 1)
  282. else:
  283. repeat_sign = "*"
  284. yield "(?:{}){}{}{}".format(
  285. prefix,
  286. repeat_sign,
  287. ("" if node.greedy else "?"),
  288. c_str,
  289. )
  290. else:
  291. raise TypeError(f"Got {node!r}")
  292. for r in transform(root_node):
  293. yield f"^(?:{r})$"
  294. def match(self, string: str) -> Match | None:
  295. """
  296. Match the string with the grammar.
  297. Returns a :class:`Match` instance or `None` when the input doesn't match the grammar.
  298. :param string: The input string.
  299. """
  300. m = self._re.match(string)
  301. if m:
  302. return Match(
  303. string, [(self._re, m)], self._group_names_to_nodes, self.unescape_funcs
  304. )
  305. return None
  306. def match_prefix(self, string: str) -> Match | None:
  307. """
  308. Do a partial match of the string with the grammar. The returned
  309. :class:`Match` instance can contain multiple representations of the
  310. match. This will never return `None`. If it doesn't match at all, the "trailing input"
  311. part will capture all of the input.
  312. :param string: The input string.
  313. """
  314. # First try to match using `_re_prefix`. If nothing is found, use the patterns that
  315. # also accept trailing characters.
  316. for patterns in [self._re_prefix, self._re_prefix_with_trailing_input]:
  317. matches = [(r, r.match(string)) for r in patterns]
  318. matches2 = [(r, m) for r, m in matches if m]
  319. if matches2 != []:
  320. return Match(
  321. string, matches2, self._group_names_to_nodes, self.unescape_funcs
  322. )
  323. return None
  324. class Match:
  325. """
  326. :param string: The input string.
  327. :param re_matches: List of (compiled_re_pattern, re_match) tuples.
  328. :param group_names_to_nodes: Dictionary mapping all the re group names to the matching Node instances.
  329. """
  330. def __init__(
  331. self,
  332. string: str,
  333. re_matches: list[tuple[Pattern[str], RegexMatch[str]]],
  334. group_names_to_nodes: dict[str, str],
  335. unescape_funcs: dict[str, Callable[[str], str]],
  336. ):
  337. self.string = string
  338. self._re_matches = re_matches
  339. self._group_names_to_nodes = group_names_to_nodes
  340. self._unescape_funcs = unescape_funcs
  341. def _nodes_to_regs(self) -> list[tuple[str, tuple[int, int]]]:
  342. """
  343. Return a list of (varname, reg) tuples.
  344. """
  345. def get_tuples() -> Iterable[tuple[str, tuple[int, int]]]:
  346. for r, re_match in self._re_matches:
  347. for group_name, group_index in r.groupindex.items():
  348. if group_name != _INVALID_TRAILING_INPUT:
  349. regs = re_match.regs
  350. reg = regs[group_index]
  351. node = self._group_names_to_nodes[group_name]
  352. yield (node, reg)
  353. return list(get_tuples())
  354. def _nodes_to_values(self) -> list[tuple[str, str, tuple[int, int]]]:
  355. """
  356. Returns list of (Node, string_value) tuples.
  357. """
  358. def is_none(sl: tuple[int, int]) -> bool:
  359. return sl[0] == -1 and sl[1] == -1
  360. def get(sl: tuple[int, int]) -> str:
  361. return self.string[sl[0] : sl[1]]
  362. return [
  363. (varname, get(slice), slice)
  364. for varname, slice in self._nodes_to_regs()
  365. if not is_none(slice)
  366. ]
  367. def _unescape(self, varname: str, value: str) -> str:
  368. unwrapper = self._unescape_funcs.get(varname)
  369. return unwrapper(value) if unwrapper else value
  370. def variables(self) -> Variables:
  371. """
  372. Returns :class:`Variables` instance.
  373. """
  374. return Variables(
  375. [(k, self._unescape(k, v), sl) for k, v, sl in self._nodes_to_values()]
  376. )
  377. def trailing_input(self) -> MatchVariable | None:
  378. """
  379. Get the `MatchVariable` instance, representing trailing input, if there is any.
  380. "Trailing input" is input at the end that does not match the grammar anymore, but
  381. when this is removed from the end of the input, the input would be a valid string.
  382. """
  383. slices: list[tuple[int, int]] = []
  384. # Find all regex group for the name _INVALID_TRAILING_INPUT.
  385. for r, re_match in self._re_matches:
  386. for group_name, group_index in r.groupindex.items():
  387. if group_name == _INVALID_TRAILING_INPUT:
  388. slices.append(re_match.regs[group_index])
  389. # Take the smallest part. (Smaller trailing text means that a larger input has
  390. # been matched, so that is better.)
  391. if slices:
  392. slice = (max(i[0] for i in slices), max(i[1] for i in slices))
  393. value = self.string[slice[0] : slice[1]]
  394. return MatchVariable("<trailing_input>", value, slice)
  395. return None
  396. def end_nodes(self) -> Iterable[MatchVariable]:
  397. """
  398. Yields `MatchVariable` instances for all the nodes having their end
  399. position at the end of the input string.
  400. """
  401. for varname, reg in self._nodes_to_regs():
  402. # If this part goes until the end of the input string.
  403. if reg[1] == len(self.string):
  404. value = self._unescape(varname, self.string[reg[0] : reg[1]])
  405. yield MatchVariable(varname, value, (reg[0], reg[1]))
  406. _T = TypeVar("_T")
  407. class Variables:
  408. def __init__(self, tuples: list[tuple[str, str, tuple[int, int]]]) -> None:
  409. #: List of (varname, value, slice) tuples.
  410. self._tuples = tuples
  411. def __repr__(self) -> str:
  412. return "{}({})".format(
  413. self.__class__.__name__,
  414. ", ".join(f"{k}={v!r}" for k, v, _ in self._tuples),
  415. )
  416. @overload
  417. def get(self, key: str) -> str | None: ...
  418. @overload
  419. def get(self, key: str, default: str | _T) -> str | _T: ...
  420. def get(self, key: str, default: str | _T | None = None) -> str | _T | None:
  421. items = self.getall(key)
  422. return items[0] if items else default
  423. def getall(self, key: str) -> list[str]:
  424. return [v for k, v, _ in self._tuples if k == key]
  425. def __getitem__(self, key: str) -> str | None:
  426. return self.get(key)
  427. def __iter__(self) -> Iterator[MatchVariable]:
  428. """
  429. Yield `MatchVariable` instances.
  430. """
  431. for varname, value, slice in self._tuples:
  432. yield MatchVariable(varname, value, slice)
  433. class MatchVariable:
  434. """
  435. Represents a match of a variable in the grammar.
  436. :param varname: (string) Name of the variable.
  437. :param value: (string) Value of this variable.
  438. :param slice: (start, stop) tuple, indicating the position of this variable
  439. in the input string.
  440. """
  441. def __init__(self, varname: str, value: str, slice: tuple[int, int]) -> None:
  442. self.varname = varname
  443. self.value = value
  444. self.slice = slice
  445. self.start = self.slice[0]
  446. self.stop = self.slice[1]
  447. def __repr__(self) -> str:
  448. return f"{self.__class__.__name__}({self.varname!r}, {self.value!r})"
  449. def compile(
  450. expression: str,
  451. escape_funcs: EscapeFuncDict | None = None,
  452. unescape_funcs: EscapeFuncDict | None = None,
  453. ) -> _CompiledGrammar:
  454. """
  455. Compile grammar (given as regex string), returning a `CompiledGrammar`
  456. instance.
  457. """
  458. return _compile_from_parse_tree(
  459. parse_regex(tokenize_regex(expression)),
  460. escape_funcs=escape_funcs,
  461. unescape_funcs=unescape_funcs,
  462. )
  463. def _compile_from_parse_tree(
  464. root_node: Node,
  465. escape_funcs: EscapeFuncDict | None = None,
  466. unescape_funcs: EscapeFuncDict | None = None,
  467. ) -> _CompiledGrammar:
  468. """
  469. Compile grammar (given as parse tree), returning a `CompiledGrammar`
  470. instance.
  471. """
  472. return _CompiledGrammar(
  473. root_node, escape_funcs=escape_funcs, unescape_funcs=unescape_funcs
  474. )