regex_helper.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. """
  2. Functions for reversing a regular expression (used in reverse URL resolving).
  3. Used internally by Django and not intended for external use.
  4. This is not, and is not intended to be, a complete reg-exp decompiler. It
  5. should be good enough for a large class of URLS, however.
  6. """
  7. from __future__ import unicode_literals
  8. from django.utils import six
  9. from django.utils.six.moves import zip
  10. # Mapping of an escape character to a representative of that class. So, e.g.,
  11. # "\w" is replaced by "x" in a reverse URL. A value of None means to ignore
  12. # this sequence. Any missing key is mapped to itself.
  13. ESCAPE_MAPPINGS = {
  14. "A": None,
  15. "b": None,
  16. "B": None,
  17. "d": "0",
  18. "D": "x",
  19. "s": " ",
  20. "S": "x",
  21. "w": "x",
  22. "W": "!",
  23. "Z": None,
  24. }
  25. class Choice(list):
  26. """
  27. Used to represent multiple possibilities at this point in a pattern string.
  28. We use a distinguished type, rather than a list, so that the usage in the
  29. code is clear.
  30. """
  31. class Group(list):
  32. """
  33. Used to represent a capturing group in the pattern string.
  34. """
  35. class NonCapture(list):
  36. """
  37. Used to represent a non-capturing group in the pattern string.
  38. """
  39. def normalize(pattern):
  40. """
  41. Given a reg-exp pattern, normalizes it to an iterable of forms that
  42. suffice for reverse matching. This does the following:
  43. (1) For any repeating sections, keeps the minimum number of occurrences
  44. permitted (this means zero for optional groups).
  45. (2) If an optional group includes parameters, include one occurrence of
  46. that group (along with the zero occurrence case from step (1)).
  47. (3) Select the first (essentially an arbitrary) element from any character
  48. class. Select an arbitrary character for any unordered class (e.g. '.'
  49. or '\w') in the pattern.
  50. (5) Ignore comments and any of the reg-exp flags that won't change
  51. what we construct ("iLmsu"). "(?x)" is an error, however.
  52. (6) Raise an error on all other non-capturing (?...) forms (e.g.
  53. look-ahead and look-behind matches) and any disjunctive ('|')
  54. constructs.
  55. Django's URLs for forward resolving are either all positional arguments or
  56. all keyword arguments. That is assumed here, as well. Although reverse
  57. resolving can be done using positional args when keyword args are
  58. specified, the two cannot be mixed in the same reverse() call.
  59. """
  60. # Do a linear scan to work out the special features of this pattern. The
  61. # idea is that we scan once here and collect all the information we need to
  62. # make future decisions.
  63. result = []
  64. non_capturing_groups = []
  65. consume_next = True
  66. pattern_iter = next_char(iter(pattern))
  67. num_args = 0
  68. # A "while" loop is used here because later on we need to be able to peek
  69. # at the next character and possibly go around without consuming another
  70. # one at the top of the loop.
  71. try:
  72. ch, escaped = next(pattern_iter)
  73. except StopIteration:
  74. return [('', [])]
  75. try:
  76. while True:
  77. if escaped:
  78. result.append(ch)
  79. elif ch == '.':
  80. # Replace "any character" with an arbitrary representative.
  81. result.append(".")
  82. elif ch == '|':
  83. # FIXME: One day we'll should do this, but not in 1.0.
  84. raise NotImplementedError('Awaiting Implementation')
  85. elif ch == "^":
  86. pass
  87. elif ch == '$':
  88. break
  89. elif ch == ')':
  90. # This can only be the end of a non-capturing group, since all
  91. # other unescaped parentheses are handled by the grouping
  92. # section later (and the full group is handled there).
  93. #
  94. # We regroup everything inside the capturing group so that it
  95. # can be quantified, if necessary.
  96. start = non_capturing_groups.pop()
  97. inner = NonCapture(result[start:])
  98. result = result[:start] + [inner]
  99. elif ch == '[':
  100. # Replace ranges with the first character in the range.
  101. ch, escaped = next(pattern_iter)
  102. result.append(ch)
  103. ch, escaped = next(pattern_iter)
  104. while escaped or ch != ']':
  105. ch, escaped = next(pattern_iter)
  106. elif ch == '(':
  107. # Some kind of group.
  108. ch, escaped = next(pattern_iter)
  109. if ch != '?' or escaped:
  110. # A positional group
  111. name = "_%d" % num_args
  112. num_args += 1
  113. result.append(Group((("%%(%s)s" % name), name)))
  114. walk_to_end(ch, pattern_iter)
  115. else:
  116. ch, escaped = next(pattern_iter)
  117. if ch in "iLmsu#":
  118. # All of these are ignorable. Walk to the end of the
  119. # group.
  120. walk_to_end(ch, pattern_iter)
  121. elif ch == ':':
  122. # Non-capturing group
  123. non_capturing_groups.append(len(result))
  124. elif ch != 'P':
  125. # Anything else, other than a named group, is something
  126. # we cannot reverse.
  127. raise ValueError("Non-reversible reg-exp portion: '(?%s'" % ch)
  128. else:
  129. ch, escaped = next(pattern_iter)
  130. if ch not in ('<', '='):
  131. raise ValueError("Non-reversible reg-exp portion: '(?P%s'" % ch)
  132. # We are in a named capturing group. Extra the name and
  133. # then skip to the end.
  134. if ch == '<':
  135. terminal_char = '>'
  136. # We are in a named backreference.
  137. else:
  138. terminal_char = ')'
  139. name = []
  140. ch, escaped = next(pattern_iter)
  141. while ch != terminal_char:
  142. name.append(ch)
  143. ch, escaped = next(pattern_iter)
  144. param = ''.join(name)
  145. # Named backreferences have already consumed the
  146. # parenthesis.
  147. if terminal_char != ')':
  148. result.append(Group((("%%(%s)s" % param), param)))
  149. walk_to_end(ch, pattern_iter)
  150. else:
  151. result.append(Group((("%%(%s)s" % param), None)))
  152. elif ch in "*?+{":
  153. # Quanitifers affect the previous item in the result list.
  154. count, ch = get_quantifier(ch, pattern_iter)
  155. if ch:
  156. # We had to look ahead, but it wasn't need to compute the
  157. # quantifier, so use this character next time around the
  158. # main loop.
  159. consume_next = False
  160. if count == 0:
  161. if contains(result[-1], Group):
  162. # If we are quantifying a capturing group (or
  163. # something containing such a group) and the minimum is
  164. # zero, we must also handle the case of one occurrence
  165. # being present. All the quantifiers (except {0,0},
  166. # which we conveniently ignore) that have a 0 minimum
  167. # also allow a single occurrence.
  168. result[-1] = Choice([None, result[-1]])
  169. else:
  170. result.pop()
  171. elif count > 1:
  172. result.extend([result[-1]] * (count - 1))
  173. else:
  174. # Anything else is a literal.
  175. result.append(ch)
  176. if consume_next:
  177. ch, escaped = next(pattern_iter)
  178. else:
  179. consume_next = True
  180. except StopIteration:
  181. pass
  182. except NotImplementedError:
  183. # A case of using the disjunctive form. No results for you!
  184. return [('', [])]
  185. return list(zip(*flatten_result(result)))
  186. def next_char(input_iter):
  187. """
  188. An iterator that yields the next character from "pattern_iter", respecting
  189. escape sequences. An escaped character is replaced by a representative of
  190. its class (e.g. \w -> "x"). If the escaped character is one that is
  191. skipped, it is not returned (the next character is returned instead).
  192. Yields the next character, along with a boolean indicating whether it is a
  193. raw (unescaped) character or not.
  194. """
  195. for ch in input_iter:
  196. if ch != '\\':
  197. yield ch, False
  198. continue
  199. ch = next(input_iter)
  200. representative = ESCAPE_MAPPINGS.get(ch, ch)
  201. if representative is None:
  202. continue
  203. yield representative, True
  204. def walk_to_end(ch, input_iter):
  205. """
  206. The iterator is currently inside a capturing group. We want to walk to the
  207. close of this group, skipping over any nested groups and handling escaped
  208. parentheses correctly.
  209. """
  210. if ch == '(':
  211. nesting = 1
  212. else:
  213. nesting = 0
  214. for ch, escaped in input_iter:
  215. if escaped:
  216. continue
  217. elif ch == '(':
  218. nesting += 1
  219. elif ch == ')':
  220. if not nesting:
  221. return
  222. nesting -= 1
  223. def get_quantifier(ch, input_iter):
  224. """
  225. Parse a quantifier from the input, where "ch" is the first character in the
  226. quantifier.
  227. Returns the minimum number of occurrences permitted by the quantifier and
  228. either None or the next character from the input_iter if the next character
  229. is not part of the quantifier.
  230. """
  231. if ch in '*?+':
  232. try:
  233. ch2, escaped = next(input_iter)
  234. except StopIteration:
  235. ch2 = None
  236. if ch2 == '?':
  237. ch2 = None
  238. if ch == '+':
  239. return 1, ch2
  240. return 0, ch2
  241. quant = []
  242. while ch != '}':
  243. ch, escaped = next(input_iter)
  244. quant.append(ch)
  245. quant = quant[:-1]
  246. values = ''.join(quant).split(',')
  247. # Consume the trailing '?', if necessary.
  248. try:
  249. ch, escaped = next(input_iter)
  250. except StopIteration:
  251. ch = None
  252. if ch == '?':
  253. ch = None
  254. return int(values[0]), ch
  255. def contains(source, inst):
  256. """
  257. Returns True if the "source" contains an instance of "inst". False,
  258. otherwise.
  259. """
  260. if isinstance(source, inst):
  261. return True
  262. if isinstance(source, NonCapture):
  263. for elt in source:
  264. if contains(elt, inst):
  265. return True
  266. return False
  267. def flatten_result(source):
  268. """
  269. Turns the given source sequence into a list of reg-exp possibilities and
  270. their arguments. Returns a list of strings and a list of argument lists.
  271. Each of the two lists will be of the same length.
  272. """
  273. if source is None:
  274. return [''], [[]]
  275. if isinstance(source, Group):
  276. if source[1] is None:
  277. params = []
  278. else:
  279. params = [source[1]]
  280. return [source[0]], [params]
  281. result = ['']
  282. result_args = [[]]
  283. pos = last = 0
  284. for pos, elt in enumerate(source):
  285. if isinstance(elt, six.string_types):
  286. continue
  287. piece = ''.join(source[last:pos])
  288. if isinstance(elt, Group):
  289. piece += elt[0]
  290. param = elt[1]
  291. else:
  292. param = None
  293. last = pos + 1
  294. for i in range(len(result)):
  295. result[i] += piece
  296. if param:
  297. result_args[i].append(param)
  298. if isinstance(elt, (Choice, NonCapture)):
  299. if isinstance(elt, NonCapture):
  300. elt = [elt]
  301. inner_result, inner_args = [], []
  302. for item in elt:
  303. res, args = flatten_result(item)
  304. inner_result.extend(res)
  305. inner_args.extend(args)
  306. new_result = []
  307. new_args = []
  308. for item, args in zip(result, result_args):
  309. for i_item, i_args in zip(inner_result, inner_args):
  310. new_result.append(item + i_item)
  311. new_args.append(args[:] + i_args)
  312. result = new_result
  313. result_args = new_args
  314. if pos >= last:
  315. piece = ''.join(source[last:])
  316. for i in range(len(result)):
  317. result[i] += piece
  318. return result, result_args