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 12KB

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