Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

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