Development of an internal social media platform with personalised dashboards for students
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 warnings
  8. from django.utils.deprecation import RemovedInDjango21Warning
  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 in 'iLmsu#':
  110. warnings.warn(
  111. 'Using (?%s) in url() patterns is deprecated.' % ch,
  112. RemovedInDjango21Warning
  113. )
  114. walk_to_end(ch, pattern_iter)
  115. elif ch == ':':
  116. # Non-capturing group
  117. non_capturing_groups.append(len(result))
  118. elif ch != 'P':
  119. # Anything else, other than a named group, is something
  120. # we cannot reverse.
  121. raise ValueError("Non-reversible reg-exp portion: '(?%s'" % ch)
  122. else:
  123. ch, escaped = next(pattern_iter)
  124. if ch not in ('<', '='):
  125. raise ValueError("Non-reversible reg-exp portion: '(?P%s'" % ch)
  126. # We are in a named capturing group. Extra the name and
  127. # then skip to the end.
  128. if ch == '<':
  129. terminal_char = '>'
  130. # We are in a named backreference.
  131. else:
  132. terminal_char = ')'
  133. name = []
  134. ch, escaped = next(pattern_iter)
  135. while ch != terminal_char:
  136. name.append(ch)
  137. ch, escaped = next(pattern_iter)
  138. param = ''.join(name)
  139. # Named backreferences have already consumed the
  140. # parenthesis.
  141. if terminal_char != ')':
  142. result.append(Group((("%%(%s)s" % param), param)))
  143. walk_to_end(ch, pattern_iter)
  144. else:
  145. result.append(Group((("%%(%s)s" % param), None)))
  146. elif ch in "*?+{":
  147. # Quantifiers affect the previous item in the result list.
  148. count, ch = get_quantifier(ch, pattern_iter)
  149. if ch:
  150. # We had to look ahead, but it wasn't need to compute the
  151. # quantifier, so use this character next time around the
  152. # main loop.
  153. consume_next = False
  154. if count == 0:
  155. if contains(result[-1], Group):
  156. # If we are quantifying a capturing group (or
  157. # something containing such a group) and the minimum is
  158. # zero, we must also handle the case of one occurrence
  159. # being present. All the quantifiers (except {0,0},
  160. # which we conveniently ignore) that have a 0 minimum
  161. # also allow a single occurrence.
  162. result[-1] = Choice([None, result[-1]])
  163. else:
  164. result.pop()
  165. elif count > 1:
  166. result.extend([result[-1]] * (count - 1))
  167. else:
  168. # Anything else is a literal.
  169. result.append(ch)
  170. if consume_next:
  171. ch, escaped = next(pattern_iter)
  172. else:
  173. consume_next = True
  174. except StopIteration:
  175. pass
  176. except NotImplementedError:
  177. # A case of using the disjunctive form. No results for you!
  178. return [('', [])]
  179. return list(zip(*flatten_result(result)))
  180. def next_char(input_iter):
  181. r"""
  182. An iterator that yields the next character from "pattern_iter", respecting
  183. escape sequences. An escaped character is replaced by a representative of
  184. its class (e.g. \w -> "x"). If the escaped character is one that is
  185. skipped, it is not returned (the next character is returned instead).
  186. Yield the next character, along with a boolean indicating whether it is a
  187. raw (unescaped) character or not.
  188. """
  189. for ch in input_iter:
  190. if ch != '\\':
  191. yield ch, False
  192. continue
  193. ch = next(input_iter)
  194. representative = ESCAPE_MAPPINGS.get(ch, ch)
  195. if representative is None:
  196. continue
  197. yield representative, True
  198. def walk_to_end(ch, input_iter):
  199. """
  200. The iterator is currently inside a capturing group. Walk to the close of
  201. this group, skipping over any nested groups and handling escaped
  202. parentheses correctly.
  203. """
  204. if ch == '(':
  205. nesting = 1
  206. else:
  207. nesting = 0
  208. for ch, escaped in input_iter:
  209. if escaped:
  210. continue
  211. elif ch == '(':
  212. nesting += 1
  213. elif ch == ')':
  214. if not nesting:
  215. return
  216. nesting -= 1
  217. def get_quantifier(ch, input_iter):
  218. """
  219. Parse a quantifier from the input, where "ch" is the first character in the
  220. quantifier.
  221. Return the minimum number of occurrences permitted by the quantifier and
  222. either None or the next character from the input_iter if the next character
  223. is not part of the quantifier.
  224. """
  225. if ch in '*?+':
  226. try:
  227. ch2, escaped = next(input_iter)
  228. except StopIteration:
  229. ch2 = None
  230. if ch2 == '?':
  231. ch2 = None
  232. if ch == '+':
  233. return 1, ch2
  234. return 0, ch2
  235. quant = []
  236. while ch != '}':
  237. ch, escaped = next(input_iter)
  238. quant.append(ch)
  239. quant = quant[:-1]
  240. values = ''.join(quant).split(',')
  241. # Consume the trailing '?', if necessary.
  242. try:
  243. ch, escaped = next(input_iter)
  244. except StopIteration:
  245. ch = None
  246. if ch == '?':
  247. ch = None
  248. return int(values[0]), ch
  249. def contains(source, inst):
  250. """
  251. Return True if the "source" contains an instance of "inst". False,
  252. otherwise.
  253. """
  254. if isinstance(source, inst):
  255. return True
  256. if isinstance(source, NonCapture):
  257. for elt in source:
  258. if contains(elt, inst):
  259. return True
  260. return False
  261. def flatten_result(source):
  262. """
  263. Turn the given source sequence into a list of reg-exp possibilities and
  264. their arguments. Return a list of strings and a list of argument lists.
  265. Each of the two lists will be of the same length.
  266. """
  267. if source is None:
  268. return [''], [[]]
  269. if isinstance(source, Group):
  270. if source[1] is None:
  271. params = []
  272. else:
  273. params = [source[1]]
  274. return [source[0]], [params]
  275. result = ['']
  276. result_args = [[]]
  277. pos = last = 0
  278. for pos, elt in enumerate(source):
  279. if isinstance(elt, str):
  280. continue
  281. piece = ''.join(source[last:pos])
  282. if isinstance(elt, Group):
  283. piece += elt[0]
  284. param = elt[1]
  285. else:
  286. param = None
  287. last = pos + 1
  288. for i in range(len(result)):
  289. result[i] += piece
  290. if param:
  291. result_args[i].append(param)
  292. if isinstance(elt, (Choice, NonCapture)):
  293. if isinstance(elt, NonCapture):
  294. elt = [elt]
  295. inner_result, inner_args = [], []
  296. for item in elt:
  297. res, args = flatten_result(item)
  298. inner_result.extend(res)
  299. inner_args.extend(args)
  300. new_result = []
  301. new_args = []
  302. for item, args in zip(result, result_args):
  303. for i_item, i_args in zip(inner_result, inner_args):
  304. new_result.append(item + i_item)
  305. new_args.append(args[:] + i_args)
  306. result = new_result
  307. result_args = new_args
  308. if pos >= last:
  309. piece = ''.join(source[last:])
  310. for i in range(len(result)):
  311. result[i] += piece
  312. return result, result_args