You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

regex_helper.py 12 KiB

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