regex_helper.py 12 KB

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