compiler.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 unicode_literals
  31. import re
  32. from six.moves import range
  33. from .regex_parser import Any, Sequence, Regex, Variable, Repeat, Lookahead
  34. from .regex_parser import parse_regex, tokenize_regex
  35. __all__ = (
  36. 'compile',
  37. )
  38. # Name of the named group in the regex, matching trailing input.
  39. # (Trailing input is when the input contains characters after the end of the
  40. # expression has been matched.)
  41. _INVALID_TRAILING_INPUT = 'invalid_trailing'
  42. class _CompiledGrammar(object):
  43. """
  44. Compiles a grammar. This will take the parse tree of a regular expression
  45. and compile the grammar.
  46. :param root_node: :class~`.regex_parser.Node` instance.
  47. :param escape_funcs: `dict` mapping variable names to escape callables.
  48. :param unescape_funcs: `dict` mapping variable names to unescape callables.
  49. """
  50. def __init__(self, root_node, escape_funcs=None, unescape_funcs=None):
  51. self.root_node = root_node
  52. self.escape_funcs = escape_funcs or {}
  53. self.unescape_funcs = unescape_funcs or {}
  54. #: Dictionary that will map the redex names to Node instances.
  55. self._group_names_to_nodes = {} # Maps regex group names to varnames.
  56. counter = [0]
  57. def create_group_func(node):
  58. name = 'n%s' % counter[0]
  59. self._group_names_to_nodes[name] = node.varname
  60. counter[0] += 1
  61. return name
  62. # Compile regex strings.
  63. self._re_pattern = '^%s$' % self._transform(root_node, create_group_func)
  64. self._re_prefix_patterns = list(self._transform_prefix(root_node, create_group_func))
  65. # Compile the regex itself.
  66. flags = re.DOTALL # Note that we don't need re.MULTILINE! (^ and $
  67. # still represent the start and end of input text.)
  68. self._re = re.compile(self._re_pattern, flags)
  69. self._re_prefix = [re.compile(t, flags) for t in self._re_prefix_patterns]
  70. # We compile one more set of regexes, similar to `_re_prefix`, but accept any trailing
  71. # input. This will ensure that we can still highlight the input correctly, even when the
  72. # input contains some additional characters at the end that don't match the grammar.)
  73. self._re_prefix_with_trailing_input = [
  74. re.compile(r'(?:%s)(?P<%s>.*?)$' % (t.rstrip('$'), _INVALID_TRAILING_INPUT), flags)
  75. for t in self._re_prefix_patterns]
  76. def escape(self, varname, value):
  77. """
  78. Escape `value` to fit in the place of this variable into the grammar.
  79. """
  80. f = self.escape_funcs.get(varname)
  81. return f(value) if f else value
  82. def unescape(self, varname, value):
  83. """
  84. Unescape `value`.
  85. """
  86. f = self.unescape_funcs.get(varname)
  87. return f(value) if f else value
  88. @classmethod
  89. def _transform(cls, root_node, create_group_func):
  90. """
  91. Turn a :class:`Node` object into a regular expression.
  92. :param root_node: The :class:`Node` instance for which we generate the grammar.
  93. :param create_group_func: A callable which takes a `Node` and returns the next
  94. free name for this node.
  95. """
  96. def transform(node):
  97. # Turn `Any` into an OR.
  98. if isinstance(node, Any):
  99. return '(?:%s)' % '|'.join(transform(c) for c in node.children)
  100. # Concatenate a `Sequence`
  101. elif isinstance(node, Sequence):
  102. return ''.join(transform(c) for c in node.children)
  103. # For Regex and Lookahead nodes, just insert them literally.
  104. elif isinstance(node, Regex):
  105. return node.regex
  106. elif isinstance(node, Lookahead):
  107. before = ('(?!' if node.negative else '(=')
  108. return before + transform(node.childnode) + ')'
  109. # A `Variable` wraps the children into a named group.
  110. elif isinstance(node, Variable):
  111. return '(?P<%s>%s)' % (create_group_func(node), transform(node.childnode))
  112. # `Repeat`.
  113. elif isinstance(node, Repeat):
  114. return '(?:%s){%i,%s}%s' % (
  115. transform(node.childnode), node.min_repeat,
  116. ('' if node.max_repeat is None else str(node.max_repeat)),
  117. ('' if node.greedy else '?')
  118. )
  119. else:
  120. raise TypeError('Got %r' % (node, ))
  121. return transform(root_node)
  122. @classmethod
  123. def _transform_prefix(cls, root_node, create_group_func):
  124. """
  125. Yield all the regular expressions matching a prefix of the grammar
  126. defined by the `Node` instance.
  127. This can yield multiple expressions, because in the case of on OR
  128. operation in the grammar, we can have another outcome depending on
  129. which clause would appear first. E.g. "(A|B)C" is not the same as
  130. "(B|A)C" because the regex engine is lazy and takes the first match.
  131. However, because we the current input is actually a prefix of the
  132. grammar which meight not yet contain the data for "C", we need to know
  133. both intermediate states, in order to call the appropriate
  134. autocompletion for both cases.
  135. :param root_node: The :class:`Node` instance for which we generate the grammar.
  136. :param create_group_func: A callable which takes a `Node` and returns the next
  137. free name for this node.
  138. """
  139. def transform(node):
  140. # Generate regexes for all permutations of this OR. Each node
  141. # should be in front once.
  142. if isinstance(node, Any):
  143. for c in node.children:
  144. for r in transform(c):
  145. yield '(?:%s)?' % r
  146. # For a sequence. We can either have a match for the sequence
  147. # of all the children, or for an exact match of the first X
  148. # children, followed by a partial match of the next children.
  149. elif isinstance(node, Sequence):
  150. for i in range(len(node.children)):
  151. a = [cls._transform(c, create_group_func) for c in node.children[:i]]
  152. for c in transform(node.children[i]):
  153. yield '(?:%s)' % (''.join(a) + c)
  154. elif isinstance(node, Regex):
  155. yield '(?:%s)?' % node.regex
  156. elif isinstance(node, Lookahead):
  157. if node.negative:
  158. yield '(?!%s)' % cls._transform(node.childnode, create_group_func)
  159. else:
  160. # Not sure what the correct semantics are in this case.
  161. # (Probably it's not worth implementing this.)
  162. raise Exception('Positive lookahead not yet supported.')
  163. elif isinstance(node, Variable):
  164. # (Note that we should not append a '?' here. the 'transform'
  165. # method will already recursively do that.)
  166. for c in transform(node.childnode):
  167. yield '(?P<%s>%s)' % (create_group_func(node), c)
  168. elif isinstance(node, Repeat):
  169. # If we have a repetition of 8 times. That would mean that the
  170. # current input could have for instance 7 times a complete
  171. # match, followed by a partial match.
  172. prefix = cls._transform(node.childnode, create_group_func)
  173. for c in transform(node.childnode):
  174. if node.max_repeat:
  175. repeat_sign = '{,%i}' % (node.max_repeat - 1)
  176. else:
  177. repeat_sign = '*'
  178. yield '(?:%s)%s%s(?:%s)?' % (
  179. prefix,
  180. repeat_sign,
  181. ('' if node.greedy else '?'),
  182. c)
  183. else:
  184. raise TypeError('Got %r' % node)
  185. for r in transform(root_node):
  186. yield '^%s$' % r
  187. def match(self, string):
  188. """
  189. Match the string with the grammar.
  190. Returns a :class:`Match` instance or `None` when the input doesn't match the grammar.
  191. :param string: The input string.
  192. """
  193. m = self._re.match(string)
  194. if m:
  195. return Match(string, [(self._re, m)], self._group_names_to_nodes, self.unescape_funcs)
  196. def match_prefix(self, string):
  197. """
  198. Do a partial match of the string with the grammar. The returned
  199. :class:`Match` instance can contain multiple representations of the
  200. match. This will never return `None`. If it doesn't match at all, the "trailing input"
  201. part will capture all of the input.
  202. :param string: The input string.
  203. """
  204. # First try to match using `_re_prefix`. If nothing is found, use the patterns that
  205. # also accept trailing characters.
  206. for patterns in [self._re_prefix, self._re_prefix_with_trailing_input]:
  207. matches = [(r, r.match(string)) for r in patterns]
  208. matches = [(r, m) for r, m in matches if m]
  209. if matches != []:
  210. return Match(string, matches, self._group_names_to_nodes, self.unescape_funcs)
  211. class Match(object):
  212. """
  213. :param string: The input string.
  214. :param re_matches: List of (compiled_re_pattern, re_match) tuples.
  215. :param group_names_to_nodes: Dictionary mapping all the re group names to the matching Node instances.
  216. """
  217. def __init__(self, string, re_matches, group_names_to_nodes, unescape_funcs):
  218. self.string = string
  219. self._re_matches = re_matches
  220. self._group_names_to_nodes = group_names_to_nodes
  221. self._unescape_funcs = unescape_funcs
  222. def _nodes_to_regs(self):
  223. """
  224. Return a list of (varname, reg) tuples.
  225. """
  226. def get_tuples():
  227. for r, re_match in self._re_matches:
  228. for group_name, group_index in r.groupindex.items():
  229. if group_name != _INVALID_TRAILING_INPUT:
  230. reg = re_match.regs[group_index]
  231. node = self._group_names_to_nodes[group_name]
  232. yield (node, reg)
  233. return list(get_tuples())
  234. def _nodes_to_values(self):
  235. """
  236. Returns list of list of (Node, string_value) tuples.
  237. """
  238. def is_none(slice):
  239. return slice[0] == -1 and slice[1] == -1
  240. def get(slice):
  241. return self.string[slice[0]:slice[1]]
  242. return [(varname, get(slice), slice) for varname, slice in self._nodes_to_regs() if not is_none(slice)]
  243. def _unescape(self, varname, value):
  244. unwrapper = self._unescape_funcs.get(varname)
  245. return unwrapper(value) if unwrapper else value
  246. def variables(self):
  247. """
  248. Returns :class:`Variables` instance.
  249. """
  250. return Variables([(k, self._unescape(k, v), sl) for k, v, sl in self._nodes_to_values()])
  251. def trailing_input(self):
  252. """
  253. Get the `MatchVariable` instance, representing trailing input, if there is any.
  254. "Trailing input" is input at the end that does not match the grammar anymore, but
  255. when this is removed from the end of the input, the input would be a valid string.
  256. """
  257. slices = []
  258. # Find all regex group for the name _INVALID_TRAILING_INPUT.
  259. for r, re_match in self._re_matches:
  260. for group_name, group_index in r.groupindex.items():
  261. if group_name == _INVALID_TRAILING_INPUT:
  262. slices.append(re_match.regs[group_index])
  263. # Take the smallest part. (Smaller trailing text means that a larger input has
  264. # been matched, so that is better.)
  265. if slices:
  266. slice = [max(i[0] for i in slices), max(i[1] for i in slices)]
  267. value = self.string[slice[0]:slice[1]]
  268. return MatchVariable('<trailing_input>', value, slice)
  269. def end_nodes(self):
  270. """
  271. Yields `MatchVariable` instances for all the nodes having their end
  272. position at the end of the input string.
  273. """
  274. for varname, reg in self._nodes_to_regs():
  275. # If this part goes until the end of the input string.
  276. if reg[1] == len(self.string):
  277. value = self._unescape(varname, self.string[reg[0]: reg[1]])
  278. yield MatchVariable(varname, value, (reg[0], reg[1]))
  279. class Variables(object):
  280. def __init__(self, tuples):
  281. #: List of (varname, value, slice) tuples.
  282. self._tuples = tuples
  283. def __repr__(self):
  284. return '%s(%s)' % (
  285. self.__class__.__name__, ', '.join('%s=%r' % (k, v) for k, v, _ in self._tuples))
  286. def get(self, key, default=None):
  287. items = self.getall(key)
  288. return items[0] if items else default
  289. def getall(self, key):
  290. return [v for k, v, _ in self._tuples if k == key]
  291. def __getitem__(self, key):
  292. return self.get(key)
  293. def __iter__(self):
  294. """
  295. Yield `MatchVariable` instances.
  296. """
  297. for varname, value, slice in self._tuples:
  298. yield MatchVariable(varname, value, slice)
  299. class MatchVariable(object):
  300. """
  301. Represents a match of a variable in the grammar.
  302. :param varname: (string) Name of the variable.
  303. :param value: (string) Value of this variable.
  304. :param slice: (start, stop) tuple, indicating the position of this variable
  305. in the input string.
  306. """
  307. def __init__(self, varname, value, slice):
  308. self.varname = varname
  309. self.value = value
  310. self.slice = slice
  311. self.start = self.slice[0]
  312. self.stop = self.slice[1]
  313. def __repr__(self):
  314. return '%s(%r, %r)' % (self.__class__.__name__, self.varname, self.value)
  315. def compile(expression, escape_funcs=None, unescape_funcs=None):
  316. """
  317. Compile grammar (given as regex string), returning a `CompiledGrammar`
  318. instance.
  319. """
  320. return _compile_from_parse_tree(
  321. parse_regex(tokenize_regex(expression)),
  322. escape_funcs=escape_funcs,
  323. unescape_funcs=unescape_funcs)
  324. def _compile_from_parse_tree(root_node, *a, **kw):
  325. """
  326. Compile grammar (given as parse tree), returning a `CompiledGrammar`
  327. instance.
  328. """
  329. return _CompiledGrammar(root_node, *a, **kw)