A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
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.
 
 
 
 

1486 lines
59 KiB

  1. # Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. import html.entities as htmlentities
  21. from math import log
  22. import re
  23. from . import contexts, tokens
  24. from .errors import ParserError
  25. from ..definitions import (get_html_tag, is_parsable, is_single,
  26. is_single_only, is_scheme)
  27. __all__ = ["Tokenizer"]
  28. class BadRoute(Exception):
  29. """Raised internally when the current tokenization route is invalid."""
  30. def __init__(self, context=0):
  31. super().__init__()
  32. self.context = context
  33. class _TagOpenData:
  34. """Stores data about an HTML open tag, like ``<ref name="foo">``."""
  35. CX_NAME = 1 << 0
  36. CX_ATTR_READY = 1 << 1
  37. CX_ATTR_NAME = 1 << 2
  38. CX_ATTR_VALUE = 1 << 3
  39. CX_QUOTED = 1 << 4
  40. CX_NOTE_SPACE = 1 << 5
  41. CX_NOTE_EQUALS = 1 << 6
  42. CX_NOTE_QUOTE = 1 << 7
  43. def __init__(self):
  44. self.context = self.CX_NAME
  45. self.padding_buffer = {"first": "", "before_eq": "", "after_eq": ""}
  46. self.quoter = None
  47. self.reset = 0
  48. class Tokenizer:
  49. """Creates a list of tokens from a string of wikicode."""
  50. USES_C = False
  51. START = object()
  52. END = object()
  53. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "'", "#", "*", ";",
  54. ":", "/", "-", "!", "\n", START, END]
  55. MAX_DEPTH = 40
  56. regex = re.compile(r"([{}\[\]<>|=&'#*;:/\\\"\-!\n])", flags=re.IGNORECASE)
  57. tag_splitter = re.compile(r"([\s\"\'\\]+)")
  58. def __init__(self):
  59. self._text = None
  60. self._head = 0
  61. self._stacks = []
  62. self._global = 0
  63. self._depth = 0
  64. self._bad_routes = set()
  65. self._skip_style_tags = False
  66. @property
  67. def _stack(self):
  68. """The current token stack."""
  69. return self._stacks[-1][0]
  70. @property
  71. def _context(self):
  72. """The current token context."""
  73. return self._stacks[-1][1]
  74. @_context.setter
  75. def _context(self, value):
  76. self._stacks[-1][1] = value
  77. @property
  78. def _textbuffer(self):
  79. """The current textbuffer."""
  80. return self._stacks[-1][2]
  81. @_textbuffer.setter
  82. def _textbuffer(self, value):
  83. self._stacks[-1][2] = value
  84. @property
  85. def _stack_ident(self):
  86. """An identifier for the current stack.
  87. This is based on the starting head position and context. Stacks with
  88. the same identifier are always parsed in the same way. This can be used
  89. to cache intermediate parsing info.
  90. """
  91. return self._stacks[-1][3]
  92. def _push(self, context=0):
  93. """Add a new token stack, context, and textbuffer to the list."""
  94. new_ident = (self._head, context)
  95. if new_ident in self._bad_routes:
  96. raise BadRoute(context)
  97. self._stacks.append([[], context, [], new_ident])
  98. self._depth += 1
  99. def _push_textbuffer(self):
  100. """Push the textbuffer onto the stack as a Text node and clear it."""
  101. if self._textbuffer:
  102. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  103. self._textbuffer = []
  104. def _pop(self, keep_context=False):
  105. """Pop the current stack/context/textbuffer, returning the stack.
  106. If *keep_context* is ``True``, then we will replace the underlying
  107. stack's context with the current stack's.
  108. """
  109. self._push_textbuffer()
  110. self._depth -= 1
  111. if keep_context:
  112. context = self._context
  113. stack = self._stacks.pop()[0]
  114. self._context = context
  115. return stack
  116. return self._stacks.pop()[0]
  117. def _can_recurse(self):
  118. """Return whether or not our max recursion depth has been exceeded."""
  119. return self._depth < self.MAX_DEPTH
  120. def _memoize_bad_route(self):
  121. """Remember that the current route (head + context at push) is invalid.
  122. This will be noticed when calling _push with the same head and context,
  123. and the route will be failed immediately.
  124. """
  125. self._bad_routes.add(self._stack_ident)
  126. def _fail_route(self):
  127. """Fail the current tokenization route.
  128. Discards the current stack/context/textbuffer and raises
  129. :exc:`.BadRoute`.
  130. """
  131. context = self._context
  132. self._memoize_bad_route()
  133. self._pop()
  134. raise BadRoute(context)
  135. def _emit(self, token):
  136. """Write a token to the end of the current token stack."""
  137. self._push_textbuffer()
  138. self._stack.append(token)
  139. def _emit_first(self, token):
  140. """Write a token to the beginning of the current token stack."""
  141. self._push_textbuffer()
  142. self._stack.insert(0, token)
  143. def _emit_text(self, text):
  144. """Write text to the current textbuffer."""
  145. self._textbuffer.append(text)
  146. def _emit_all(self, tokenlist):
  147. """Write a series of tokens to the current stack at once."""
  148. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  149. self._emit_text(tokenlist.pop(0).text)
  150. self._push_textbuffer()
  151. self._stack.extend(tokenlist)
  152. def _emit_text_then_stack(self, text):
  153. """Pop the current stack, write *text*, and then write the stack."""
  154. stack = self._pop()
  155. self._emit_text(text)
  156. if stack:
  157. self._emit_all(stack)
  158. self._head -= 1
  159. def _read(self, delta=0, wrap=False, strict=False):
  160. """Read the value at a relative point in the wikicode.
  161. The value is read from :attr:`self._head <_head>` plus the value of
  162. *delta* (which can be negative). If *wrap* is ``False``, we will not
  163. allow attempts to read from the end of the string if ``self._head +
  164. delta`` is negative. If *strict* is ``True``, the route will be failed
  165. (with :meth:`_fail_route`) if we try to read from past the end of the
  166. string; otherwise, :attr:`self.END <END>` is returned. If we try to
  167. read from before the start of the string, :attr:`self.START <START>` is
  168. returned.
  169. """
  170. index = self._head + delta
  171. if index < 0 and (not wrap or abs(index) > len(self._text)):
  172. return self.START
  173. try:
  174. return self._text[index]
  175. except IndexError:
  176. if strict:
  177. self._fail_route()
  178. return self.END
  179. def _parse_template(self, has_content):
  180. """Parse a template at the head of the wikicode string."""
  181. reset = self._head
  182. context = contexts.TEMPLATE_NAME
  183. if has_content:
  184. context |= contexts.HAS_TEMPLATE
  185. try:
  186. template = self._parse(context)
  187. except BadRoute:
  188. self._head = reset
  189. raise
  190. self._emit_first(tokens.TemplateOpen())
  191. self._emit_all(template)
  192. self._emit(tokens.TemplateClose())
  193. def _parse_argument(self):
  194. """Parse an argument at the head of the wikicode string."""
  195. reset = self._head
  196. try:
  197. argument = self._parse(contexts.ARGUMENT_NAME)
  198. except BadRoute:
  199. self._head = reset
  200. raise
  201. self._emit_first(tokens.ArgumentOpen())
  202. self._emit_all(argument)
  203. self._emit(tokens.ArgumentClose())
  204. def _parse_template_or_argument(self):
  205. """Parse a template or argument at the head of the wikicode string."""
  206. self._head += 2
  207. braces = 2
  208. while self._read() == "{":
  209. self._head += 1
  210. braces += 1
  211. has_content = False
  212. self._push()
  213. while braces:
  214. if braces == 1:
  215. return self._emit_text_then_stack("{")
  216. if braces == 2:
  217. try:
  218. self._parse_template(has_content)
  219. except BadRoute:
  220. return self._emit_text_then_stack("{{")
  221. break
  222. try:
  223. self._parse_argument()
  224. braces -= 3
  225. except BadRoute:
  226. try:
  227. self._parse_template(has_content)
  228. braces -= 2
  229. except BadRoute:
  230. return self._emit_text_then_stack("{" * braces)
  231. if braces:
  232. has_content = True
  233. self._head += 1
  234. self._emit_all(self._pop())
  235. if self._context & contexts.FAIL_NEXT:
  236. self._context ^= contexts.FAIL_NEXT
  237. def _handle_template_param(self):
  238. """Handle a template parameter at the head of the string."""
  239. if self._context & contexts.TEMPLATE_NAME:
  240. if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
  241. self._fail_route()
  242. self._context ^= contexts.TEMPLATE_NAME
  243. elif self._context & contexts.TEMPLATE_PARAM_VALUE:
  244. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  245. else:
  246. self._emit_all(self._pop())
  247. self._context |= contexts.TEMPLATE_PARAM_KEY
  248. self._emit(tokens.TemplateParamSeparator())
  249. self._push(self._context)
  250. def _handle_template_param_value(self):
  251. """Handle a template parameter's value at the head of the string."""
  252. self._emit_all(self._pop())
  253. self._context ^= contexts.TEMPLATE_PARAM_KEY
  254. self._context |= contexts.TEMPLATE_PARAM_VALUE
  255. self._emit(tokens.TemplateParamEquals())
  256. def _handle_template_end(self):
  257. """Handle the end of a template at the head of the string."""
  258. if self._context & contexts.TEMPLATE_NAME:
  259. if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
  260. self._fail_route()
  261. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  262. self._emit_all(self._pop())
  263. self._head += 1
  264. return self._pop()
  265. def _handle_argument_separator(self):
  266. """Handle the separator between an argument's name and default."""
  267. self._context ^= contexts.ARGUMENT_NAME
  268. self._context |= contexts.ARGUMENT_DEFAULT
  269. self._emit(tokens.ArgumentSeparator())
  270. def _handle_argument_end(self):
  271. """Handle the end of an argument at the head of the string."""
  272. self._head += 2
  273. return self._pop()
  274. def _parse_wikilink(self):
  275. """Parse an internal wikilink at the head of the wikicode string."""
  276. reset = self._head + 1
  277. self._head += 2
  278. try:
  279. # If the wikilink looks like an external link, parse it as such:
  280. link, _extra, _delta = self._really_parse_external_link(True)
  281. except BadRoute:
  282. self._head = reset + 1
  283. try:
  284. # Otherwise, actually parse it as a wikilink:
  285. wikilink = self._parse(contexts.WIKILINK_TITLE)
  286. except BadRoute:
  287. self._head = reset
  288. self._emit_text("[[")
  289. else:
  290. self._emit(tokens.WikilinkOpen())
  291. self._emit_all(wikilink)
  292. self._emit(tokens.WikilinkClose())
  293. else:
  294. if self._context & contexts.EXT_LINK_TITLE:
  295. # In this exceptional case, an external link that looks like a
  296. # wikilink inside of an external link is parsed as text:
  297. self._head = reset
  298. self._emit_text("[[")
  299. return
  300. self._emit_text("[")
  301. self._emit(tokens.ExternalLinkOpen(brackets=True))
  302. self._emit_all(link)
  303. self._emit(tokens.ExternalLinkClose())
  304. def _handle_wikilink_separator(self):
  305. """Handle the separator between a wikilink's title and its text."""
  306. self._context ^= contexts.WIKILINK_TITLE
  307. self._context |= contexts.WIKILINK_TEXT
  308. self._emit(tokens.WikilinkSeparator())
  309. def _handle_wikilink_end(self):
  310. """Handle the end of a wikilink at the head of the string."""
  311. self._head += 1
  312. return self._pop()
  313. def _parse_bracketed_uri_scheme(self):
  314. """Parse the URI scheme of a bracket-enclosed external link."""
  315. self._push(contexts.EXT_LINK_URI)
  316. if self._read() == self._read(1) == "/":
  317. self._emit_text("//")
  318. self._head += 2
  319. else:
  320. valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+.-"
  321. all_valid = lambda: all(char in valid for char in self._read())
  322. scheme = ""
  323. while self._read() is not self.END and all_valid():
  324. scheme += self._read()
  325. self._emit_text(self._read())
  326. self._head += 1
  327. if self._read() != ":":
  328. self._fail_route()
  329. self._emit_text(":")
  330. self._head += 1
  331. slashes = self._read() == self._read(1) == "/"
  332. if slashes:
  333. self._emit_text("//")
  334. self._head += 2
  335. if not is_scheme(scheme, slashes):
  336. self._fail_route()
  337. def _parse_free_uri_scheme(self):
  338. """Parse the URI scheme of a free (no brackets) external link."""
  339. valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+.-"
  340. scheme = []
  341. try:
  342. # We have to backtrack through the textbuffer looking for our
  343. # scheme since it was just parsed as text:
  344. for chunk in reversed(self._textbuffer):
  345. for char in reversed(chunk):
  346. # stop at the first non-word character
  347. if re.fullmatch(r"\W", char):
  348. raise StopIteration()
  349. if char not in valid:
  350. raise BadRoute()
  351. scheme.append(char)
  352. except StopIteration:
  353. pass
  354. scheme = "".join(reversed(scheme))
  355. slashes = self._read() == self._read(1) == "/"
  356. if not is_scheme(scheme, slashes):
  357. raise BadRoute()
  358. self._push(self._context | contexts.EXT_LINK_URI)
  359. self._emit_text(scheme)
  360. self._emit_text(":")
  361. if slashes:
  362. self._emit_text("//")
  363. self._head += 2
  364. def _handle_free_link_text(self, punct, tail, this):
  365. """Handle text in a free ext link, including trailing punctuation."""
  366. if "(" in this and ")" in punct:
  367. punct = punct[:-1] # ')' is not longer valid punctuation
  368. if this.endswith(punct):
  369. for i in range(len(this) - 1, 0, -1):
  370. if this[i - 1] not in punct:
  371. break
  372. else:
  373. i = 0
  374. stripped = this[:i]
  375. if stripped and tail:
  376. self._emit_text(tail)
  377. tail = ""
  378. tail += this[i:]
  379. this = stripped
  380. elif tail:
  381. self._emit_text(tail)
  382. tail = ""
  383. self._emit_text(this)
  384. return punct, tail
  385. def _is_free_link_end(self, this, nxt):
  386. """Return whether the current head is the end of a free link."""
  387. # Built from _parse()'s end sentinels:
  388. after, ctx = self._read(2), self._context
  389. equal_sign_contexts = contexts.TEMPLATE_PARAM_KEY | contexts.HEADING
  390. return (this in (self.END, "\n", "[", "]", "<", ">", "\"") or
  391. this == nxt == "'" or
  392. (this == "|" and ctx & contexts.TEMPLATE) or
  393. (this == "=" and ctx & equal_sign_contexts) or
  394. (this == nxt == "}" and ctx & contexts.TEMPLATE) or
  395. (this == nxt == after == "}" and ctx & contexts.ARGUMENT))
  396. def _really_parse_external_link(self, brackets):
  397. """Really parse an external link."""
  398. if brackets:
  399. self._parse_bracketed_uri_scheme()
  400. invalid = ("\n", " ", "]")
  401. else:
  402. self._parse_free_uri_scheme()
  403. invalid = ("\n", " ", "[", "]")
  404. punct = tuple(",;\\.:!?)")
  405. if self._read() is self.END or self._read()[0] in invalid:
  406. self._fail_route()
  407. tail = ""
  408. while True:
  409. this, nxt = self._read(), self._read(1)
  410. if this == "&":
  411. if tail:
  412. self._emit_text(tail)
  413. tail = ""
  414. self._parse_entity()
  415. elif (this == "<" and nxt == "!" and self._read(2) ==
  416. self._read(3) == "-"):
  417. if tail:
  418. self._emit_text(tail)
  419. tail = ""
  420. self._parse_comment()
  421. elif not brackets and self._is_free_link_end(this, nxt):
  422. return self._pop(), tail, -1
  423. elif this is self.END or this == "\n":
  424. self._fail_route()
  425. elif this == nxt == "{" and self._can_recurse():
  426. if tail:
  427. self._emit_text(tail)
  428. tail = ""
  429. self._parse_template_or_argument()
  430. elif this == "]":
  431. return self._pop(), tail, 0
  432. elif this == "'" and nxt == "'":
  433. separator = tokens.ExternalLinkSeparator()
  434. separator.suppress_space = True
  435. self._emit(separator)
  436. self._context ^= contexts.EXT_LINK_URI
  437. self._context |= contexts.EXT_LINK_TITLE
  438. return self._parse(push=False), None, 0
  439. elif any(ch in this for ch in (" ", "\n", "[", "]", "<", ">",
  440. "\"")):
  441. before, after = re.split(r"[ \n[\]<>\"]", this, maxsplit=1)
  442. delimiter = this[len(before)]
  443. if brackets:
  444. self._emit_text(before)
  445. separator = tokens.ExternalLinkSeparator()
  446. if delimiter != " ":
  447. separator.suppress_space = True
  448. self._emit(separator)
  449. if after:
  450. self._emit_text(after)
  451. self._context ^= contexts.EXT_LINK_URI
  452. self._context |= contexts.EXT_LINK_TITLE
  453. if delimiter == " ":
  454. self._head += 1
  455. return self._parse(push=False), None, 0
  456. punct, tail = self._handle_free_link_text(punct, tail, before)
  457. return self._pop(), tail + " " + after, 0
  458. elif not brackets:
  459. punct, tail = self._handle_free_link_text(punct, tail, this)
  460. else:
  461. self._emit_text(this)
  462. self._head += 1
  463. def _remove_uri_scheme_from_textbuffer(self, scheme):
  464. """Remove the URI scheme of a new external link from the textbuffer."""
  465. length = len(scheme)
  466. while length:
  467. if length < len(self._textbuffer[-1]):
  468. self._textbuffer[-1] = self._textbuffer[-1][:-length]
  469. break
  470. length -= len(self._textbuffer[-1])
  471. self._textbuffer.pop()
  472. def _parse_external_link(self, brackets):
  473. """Parse an external link at the head of the wikicode string."""
  474. if self._context & contexts.NO_EXT_LINKS or not self._can_recurse():
  475. if not brackets and self._context & contexts.DL_TERM:
  476. self._handle_dl_term()
  477. else:
  478. self._emit_text(self._read())
  479. return
  480. reset = self._head
  481. self._head += 1
  482. try:
  483. link, extra, delta = self._really_parse_external_link(brackets)
  484. except BadRoute:
  485. self._head = reset
  486. if not brackets and self._context & contexts.DL_TERM:
  487. self._handle_dl_term()
  488. else:
  489. self._emit_text(self._read())
  490. else:
  491. if not brackets:
  492. scheme = link[0].text.split(":", 1)[0]
  493. self._remove_uri_scheme_from_textbuffer(scheme)
  494. self._emit(tokens.ExternalLinkOpen(brackets=brackets))
  495. self._emit_all(link)
  496. self._emit(tokens.ExternalLinkClose())
  497. self._head += delta
  498. if extra:
  499. self._emit_text(extra)
  500. def _parse_heading(self):
  501. """Parse a section heading at the head of the wikicode string."""
  502. self._global |= contexts.GL_HEADING
  503. reset = self._head
  504. self._head += 1
  505. best = 1
  506. while self._read() == "=":
  507. best += 1
  508. self._head += 1
  509. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  510. try:
  511. title, level = self._parse(context)
  512. except BadRoute:
  513. self._head = reset + best - 1
  514. self._emit_text("=" * best)
  515. else:
  516. self._emit(tokens.HeadingStart(level=level))
  517. if level < best:
  518. self._emit_text("=" * (best - level))
  519. self._emit_all(title)
  520. self._emit(tokens.HeadingEnd())
  521. finally:
  522. self._global ^= contexts.GL_HEADING
  523. def _handle_heading_end(self):
  524. """Handle the end of a section heading at the head of the string."""
  525. reset = self._head
  526. self._head += 1
  527. best = 1
  528. while self._read() == "=":
  529. best += 1
  530. self._head += 1
  531. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  532. level = min(current, min(best, 6))
  533. try: # Try to check for a heading closure after this one
  534. after, after_level = self._parse(self._context)
  535. except BadRoute:
  536. if level < best:
  537. self._emit_text("=" * (best - level))
  538. self._head = reset + best - 1
  539. return self._pop(), level
  540. else: # Found another closure
  541. self._emit_text("=" * best)
  542. self._emit_all(after)
  543. return self._pop(), after_level
  544. def _really_parse_entity(self):
  545. """Actually parse an HTML entity and ensure that it is valid."""
  546. self._emit(tokens.HTMLEntityStart())
  547. self._head += 1
  548. this = self._read(strict=True)
  549. if this == "#":
  550. numeric = True
  551. self._emit(tokens.HTMLEntityNumeric())
  552. self._head += 1
  553. this = self._read(strict=True)
  554. if this[0].lower() == "x":
  555. hexadecimal = True
  556. self._emit(tokens.HTMLEntityHex(char=this[0]))
  557. this = this[1:]
  558. if not this:
  559. self._fail_route()
  560. else:
  561. hexadecimal = False
  562. else:
  563. numeric = hexadecimal = False
  564. valid = "0123456789abcdefABCDEF" if hexadecimal else "0123456789"
  565. if not numeric and not hexadecimal:
  566. valid += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  567. if not all([char in valid for char in this]):
  568. self._fail_route()
  569. self._head += 1
  570. if self._read() != ";":
  571. self._fail_route()
  572. if numeric:
  573. test = int(this, 16) if hexadecimal else int(this)
  574. if test < 1 or test > 0x10FFFF:
  575. self._fail_route()
  576. else:
  577. if this not in htmlentities.entitydefs:
  578. self._fail_route()
  579. self._emit(tokens.Text(text=this))
  580. self._emit(tokens.HTMLEntityEnd())
  581. def _parse_entity(self):
  582. """Parse an HTML entity at the head of the wikicode string."""
  583. reset = self._head
  584. try:
  585. self._push(contexts.HTML_ENTITY)
  586. self._really_parse_entity()
  587. except BadRoute:
  588. self._head = reset
  589. self._emit_text(self._read())
  590. else:
  591. self._emit_all(self._pop())
  592. def _parse_comment(self):
  593. """Parse an HTML comment at the head of the wikicode string."""
  594. self._head += 4
  595. reset = self._head - 1
  596. self._push()
  597. while True:
  598. this = self._read()
  599. if this == self.END:
  600. self._pop()
  601. self._head = reset
  602. self._emit_text("<!--")
  603. return
  604. if this == self._read(1) == "-" and self._read(2) == ">":
  605. self._emit_first(tokens.CommentStart())
  606. self._emit(tokens.CommentEnd())
  607. self._emit_all(self._pop())
  608. self._head += 2
  609. if self._context & contexts.FAIL_NEXT:
  610. # _verify_safe() sets this flag while parsing a template
  611. # or link when it encounters what might be a comment -- we
  612. # must unset it to let _verify_safe() know it was correct:
  613. self._context ^= contexts.FAIL_NEXT
  614. return
  615. self._emit_text(this)
  616. self._head += 1
  617. def _push_tag_buffer(self, data):
  618. """Write a pending tag attribute from *data* to the stack."""
  619. if data.context & data.CX_QUOTED:
  620. self._emit_first(tokens.TagAttrQuote(char=data.quoter))
  621. self._emit_all(self._pop())
  622. buf = data.padding_buffer
  623. self._emit_first(tokens.TagAttrStart(
  624. pad_first=buf["first"], pad_before_eq=buf["before_eq"],
  625. pad_after_eq=buf["after_eq"]))
  626. self._emit_all(self._pop())
  627. for key in data.padding_buffer:
  628. data.padding_buffer[key] = ""
  629. def _handle_tag_space(self, data, text):
  630. """Handle whitespace (*text*) inside of an HTML open tag."""
  631. ctx = data.context
  632. end_of_value = ctx & data.CX_ATTR_VALUE and not ctx & (data.CX_QUOTED | data.CX_NOTE_QUOTE)
  633. if end_of_value or (ctx & data.CX_QUOTED and ctx & data.CX_NOTE_SPACE):
  634. self._push_tag_buffer(data)
  635. data.context = data.CX_ATTR_READY
  636. elif ctx & data.CX_NOTE_SPACE:
  637. data.context = data.CX_ATTR_READY
  638. elif ctx & data.CX_ATTR_NAME:
  639. data.context |= data.CX_NOTE_EQUALS
  640. data.padding_buffer["before_eq"] += text
  641. if ctx & data.CX_QUOTED and not ctx & data.CX_NOTE_SPACE:
  642. self._emit_text(text)
  643. elif data.context & data.CX_ATTR_READY:
  644. data.padding_buffer["first"] += text
  645. elif data.context & data.CX_ATTR_VALUE:
  646. data.padding_buffer["after_eq"] += text
  647. def _handle_tag_text(self, text):
  648. """Handle regular *text* inside of an HTML open tag."""
  649. nxt = self._read(1)
  650. if not self._can_recurse() or text not in self.MARKERS:
  651. self._emit_text(text)
  652. elif text == nxt == "{":
  653. self._parse_template_or_argument()
  654. elif text == nxt == "[":
  655. self._parse_wikilink()
  656. elif text == "<":
  657. self._parse_tag()
  658. else:
  659. self._emit_text(text)
  660. def _handle_tag_data(self, data, text):
  661. """Handle all sorts of *text* data inside of an HTML open tag."""
  662. for chunk in self.tag_splitter.split(text):
  663. if not chunk:
  664. continue
  665. if data.context & data.CX_NAME:
  666. if chunk in self.MARKERS or chunk.isspace():
  667. self._fail_route() # Tags must start with text, not spaces
  668. data.context = data.CX_NOTE_SPACE
  669. elif chunk.isspace():
  670. self._handle_tag_space(data, chunk)
  671. continue
  672. elif data.context & data.CX_NOTE_SPACE:
  673. if data.context & data.CX_QUOTED:
  674. data.context = data.CX_ATTR_VALUE
  675. self._memoize_bad_route()
  676. self._pop()
  677. self._head = data.reset - 1 # Will be auto-incremented
  678. return # Break early
  679. self._fail_route()
  680. elif data.context & data.CX_ATTR_READY:
  681. data.context = data.CX_ATTR_NAME
  682. self._push(contexts.TAG_ATTR)
  683. elif data.context & data.CX_ATTR_NAME:
  684. if chunk == "=":
  685. data.context = data.CX_ATTR_VALUE | data.CX_NOTE_QUOTE
  686. self._emit(tokens.TagAttrEquals())
  687. continue
  688. if data.context & data.CX_NOTE_EQUALS:
  689. self._push_tag_buffer(data)
  690. data.context = data.CX_ATTR_NAME
  691. self._push(contexts.TAG_ATTR)
  692. else: # data.context & data.CX_ATTR_VALUE assured
  693. escaped = self._read(-1) == "\\" and self._read(-2) != "\\"
  694. if data.context & data.CX_NOTE_QUOTE:
  695. data.context ^= data.CX_NOTE_QUOTE
  696. if chunk in "'\"" and not escaped:
  697. data.context |= data.CX_QUOTED
  698. data.quoter = chunk
  699. data.reset = self._head
  700. try:
  701. self._push(self._context)
  702. except BadRoute:
  703. # Already failed to parse this as a quoted string
  704. data.context = data.CX_ATTR_VALUE
  705. self._head -= 1
  706. return
  707. continue
  708. elif data.context & data.CX_QUOTED:
  709. if chunk == data.quoter and not escaped:
  710. data.context |= data.CX_NOTE_SPACE
  711. continue
  712. self._handle_tag_text(chunk)
  713. def _handle_tag_close_open(self, data, token):
  714. """Handle the closing of a open tag (``<foo>``)."""
  715. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  716. self._push_tag_buffer(data)
  717. self._emit(token(padding=data.padding_buffer["first"]))
  718. self._head += 1
  719. def _handle_tag_open_close(self):
  720. """Handle the opening of a closing tag (``</foo>``)."""
  721. self._emit(tokens.TagOpenClose())
  722. self._push(contexts.TAG_CLOSE)
  723. self._head += 1
  724. def _handle_tag_close_close(self):
  725. """Handle the ending of a closing tag (``</foo>``)."""
  726. strip = lambda tok: tok.text.rstrip().lower()
  727. closing = self._pop()
  728. if len(closing) != 1 or (not isinstance(closing[0], tokens.Text) or
  729. strip(closing[0]) != strip(self._stack[1])):
  730. self._fail_route()
  731. self._emit_all(closing)
  732. self._emit(tokens.TagCloseClose())
  733. return self._pop()
  734. def _handle_blacklisted_tag(self):
  735. """Handle the body of an HTML tag that is parser-blacklisted."""
  736. strip = lambda text: text.rstrip().lower()
  737. while True:
  738. this, nxt = self._read(), self._read(1)
  739. if this is self.END:
  740. self._fail_route()
  741. elif this == "<" and nxt == "/":
  742. self._head += 3
  743. if self._read() != ">" or (strip(self._read(-1)) !=
  744. strip(self._stack[1].text)):
  745. self._head -= 1
  746. self._emit_text("</")
  747. continue
  748. self._emit(tokens.TagOpenClose())
  749. self._emit_text(self._read(-1))
  750. self._emit(tokens.TagCloseClose())
  751. return self._pop()
  752. elif this == "&":
  753. self._parse_entity()
  754. else:
  755. self._emit_text(this)
  756. self._head += 1
  757. def _handle_single_only_tag_end(self):
  758. """Handle the end of an implicitly closing single-only HTML tag."""
  759. padding = self._stack.pop().padding
  760. self._emit(tokens.TagCloseSelfclose(padding=padding, implicit=True))
  761. self._head -= 1 # Offset displacement done by _handle_tag_close_open
  762. return self._pop()
  763. def _handle_single_tag_end(self):
  764. """Handle the stream end when inside a single-supporting HTML tag."""
  765. stack = self._stack
  766. # We need to find the index of the TagCloseOpen token corresponding to
  767. # the TagOpenOpen token located at index 0:
  768. depth = 1
  769. for index, token in enumerate(stack[2:], 2):
  770. if isinstance(token, tokens.TagOpenOpen):
  771. depth += 1
  772. elif isinstance(token, tokens.TagCloseOpen):
  773. depth -= 1
  774. if depth == 0:
  775. break
  776. elif isinstance(token, tokens.TagCloseSelfclose):
  777. depth -= 1
  778. if depth == 0: # pragma: no cover (untestable/exceptional)
  779. raise ParserError(
  780. "_handle_single_tag_end() got an unexpected "
  781. "TagCloseSelfclose")
  782. else: # pragma: no cover (untestable/exceptional case)
  783. raise ParserError("_handle_single_tag_end() missed a TagCloseOpen")
  784. padding = stack[index].padding
  785. stack[index] = tokens.TagCloseSelfclose(padding=padding, implicit=True)
  786. return self._pop()
  787. def _really_parse_tag(self):
  788. """Actually parse an HTML tag, starting with the open (``<foo>``)."""
  789. data = _TagOpenData()
  790. self._push(contexts.TAG_OPEN)
  791. self._emit(tokens.TagOpenOpen())
  792. while True:
  793. this, nxt = self._read(), self._read(1)
  794. can_exit = (not data.context & (data.CX_QUOTED | data.CX_NAME) or
  795. data.context & data.CX_NOTE_SPACE)
  796. if this is self.END:
  797. if self._context & contexts.TAG_ATTR:
  798. if data.context & data.CX_QUOTED:
  799. # Unclosed attribute quote: reset, don't die
  800. data.context = data.CX_ATTR_VALUE
  801. self._memoize_bad_route()
  802. self._pop()
  803. self._head = data.reset
  804. continue
  805. self._pop()
  806. self._fail_route()
  807. elif this == ">" and can_exit:
  808. self._handle_tag_close_open(data, tokens.TagCloseOpen)
  809. self._context = contexts.TAG_BODY
  810. if is_single_only(self._stack[1].text):
  811. return self._handle_single_only_tag_end()
  812. if is_parsable(self._stack[1].text):
  813. return self._parse(push=False)
  814. return self._handle_blacklisted_tag()
  815. elif this == "/" and nxt == ">" and can_exit:
  816. self._handle_tag_close_open(data, tokens.TagCloseSelfclose)
  817. return self._pop()
  818. else:
  819. self._handle_tag_data(data, this)
  820. self._head += 1
  821. def _handle_invalid_tag_start(self):
  822. """Handle the (possible) start of an implicitly closing single tag."""
  823. reset = self._head + 1
  824. self._head += 2
  825. try:
  826. if not is_single_only(self.tag_splitter.split(self._read())[0]):
  827. raise BadRoute()
  828. tag = self._really_parse_tag()
  829. except BadRoute:
  830. self._head = reset
  831. self._emit_text("</")
  832. else:
  833. tag[0].invalid = True # Set flag of TagOpenOpen
  834. self._emit_all(tag)
  835. def _parse_tag(self):
  836. """Parse an HTML tag at the head of the wikicode string."""
  837. reset = self._head
  838. self._head += 1
  839. try:
  840. tag = self._really_parse_tag()
  841. except BadRoute:
  842. self._head = reset
  843. self._emit_text("<")
  844. else:
  845. self._emit_all(tag)
  846. def _emit_style_tag(self, tag, markup, body):
  847. """Write the body of a tag and the tokens that should surround it."""
  848. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  849. self._emit_text(tag)
  850. self._emit(tokens.TagCloseOpen())
  851. self._emit_all(body)
  852. self._emit(tokens.TagOpenClose())
  853. self._emit_text(tag)
  854. self._emit(tokens.TagCloseClose())
  855. def _parse_italics(self):
  856. """Parse wiki-style italics."""
  857. reset = self._head
  858. try:
  859. stack = self._parse(contexts.STYLE_ITALICS)
  860. except BadRoute as route:
  861. self._head = reset
  862. if route.context & contexts.STYLE_PASS_AGAIN:
  863. new_ctx = contexts.STYLE_ITALICS | contexts.STYLE_SECOND_PASS
  864. try:
  865. stack = self._parse(new_ctx)
  866. except BadRoute:
  867. self._head = reset
  868. self._emit_text("''")
  869. return
  870. else:
  871. self._emit_text("''")
  872. return
  873. self._emit_style_tag("i", "''", stack)
  874. def _parse_bold(self):
  875. """Parse wiki-style bold."""
  876. reset = self._head
  877. try:
  878. stack = self._parse(contexts.STYLE_BOLD)
  879. except BadRoute:
  880. self._head = reset
  881. if self._context & contexts.STYLE_SECOND_PASS:
  882. self._emit_text("'")
  883. return True
  884. if self._context & contexts.STYLE_ITALICS:
  885. self._context |= contexts.STYLE_PASS_AGAIN
  886. self._emit_text("'''")
  887. else:
  888. self._emit_text("'")
  889. self._parse_italics()
  890. else:
  891. self._emit_style_tag("b", "'''", stack)
  892. return False
  893. def _parse_italics_and_bold(self):
  894. """Parse wiki-style italics and bold together (i.e., five ticks)."""
  895. reset = self._head
  896. try:
  897. stack = self._parse(contexts.STYLE_BOLD)
  898. except BadRoute:
  899. self._head = reset
  900. try:
  901. stack = self._parse(contexts.STYLE_ITALICS)
  902. except BadRoute:
  903. self._head = reset
  904. self._emit_text("'''''")
  905. else:
  906. reset = self._head
  907. try:
  908. stack2 = self._parse(contexts.STYLE_BOLD)
  909. except BadRoute:
  910. self._head = reset
  911. self._emit_text("'''")
  912. self._emit_style_tag("i", "''", stack)
  913. else:
  914. self._push()
  915. self._emit_style_tag("i", "''", stack)
  916. self._emit_all(stack2)
  917. self._emit_style_tag("b", "'''", self._pop())
  918. else:
  919. reset = self._head
  920. try:
  921. stack2 = self._parse(contexts.STYLE_ITALICS)
  922. except BadRoute:
  923. self._head = reset
  924. self._emit_text("''")
  925. self._emit_style_tag("b", "'''", stack)
  926. else:
  927. self._push()
  928. self._emit_style_tag("b", "'''", stack)
  929. self._emit_all(stack2)
  930. self._emit_style_tag("i", "''", self._pop())
  931. def _parse_style(self):
  932. """Parse wiki-style formatting (``''``/``'''`` for italics/bold)."""
  933. self._head += 2
  934. ticks = 2
  935. while self._read() == "'":
  936. self._head += 1
  937. ticks += 1
  938. italics = self._context & contexts.STYLE_ITALICS
  939. bold = self._context & contexts.STYLE_BOLD
  940. if ticks > 5:
  941. self._emit_text("'" * (ticks - 5))
  942. ticks = 5
  943. elif ticks == 4:
  944. self._emit_text("'")
  945. ticks = 3
  946. if (italics and ticks in (2, 5)) or (bold and ticks in (3, 5)):
  947. if ticks == 5:
  948. self._head -= 3 if italics else 2
  949. return self._pop()
  950. if not self._can_recurse():
  951. if ticks == 3:
  952. if self._context & contexts.STYLE_SECOND_PASS:
  953. self._emit_text("'")
  954. return self._pop()
  955. if self._context & contexts.STYLE_ITALICS:
  956. self._context |= contexts.STYLE_PASS_AGAIN
  957. self._emit_text("'" * ticks)
  958. elif ticks == 2:
  959. self._parse_italics()
  960. elif ticks == 3:
  961. if self._parse_bold():
  962. return self._pop()
  963. else: # ticks == 5
  964. self._parse_italics_and_bold()
  965. self._head -= 1
  966. def _handle_list_marker(self):
  967. """Handle a list marker at the head (``#``, ``*``, ``;``, ``:``)."""
  968. markup = self._read()
  969. if markup == ";":
  970. self._context |= contexts.DL_TERM
  971. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  972. self._emit_text(get_html_tag(markup))
  973. self._emit(tokens.TagCloseSelfclose())
  974. def _handle_list(self):
  975. """Handle a wiki-style list (``#``, ``*``, ``;``, ``:``)."""
  976. self._handle_list_marker()
  977. while self._read(1) in ("#", "*", ";", ":"):
  978. self._head += 1
  979. self._handle_list_marker()
  980. def _handle_hr(self):
  981. """Handle a wiki-style horizontal rule (``----``) in the string."""
  982. length = 4
  983. self._head += 3
  984. while self._read(1) == "-":
  985. length += 1
  986. self._head += 1
  987. self._emit(tokens.TagOpenOpen(wiki_markup="-" * length))
  988. self._emit_text("hr")
  989. self._emit(tokens.TagCloseSelfclose())
  990. def _handle_dl_term(self):
  991. """Handle the term in a description list (``foo`` in ``;foo:bar``)."""
  992. self._context ^= contexts.DL_TERM
  993. if self._read() == ":":
  994. self._handle_list_marker()
  995. else:
  996. self._emit_text("\n")
  997. def _emit_table_tag(self, open_open_markup, tag, style, padding,
  998. close_open_markup, contents, open_close_markup):
  999. """Emit a table tag."""
  1000. self._emit(tokens.TagOpenOpen(wiki_markup=open_open_markup))
  1001. self._emit_text(tag)
  1002. if style:
  1003. self._emit_all(style)
  1004. if close_open_markup:
  1005. self._emit(tokens.TagCloseOpen(wiki_markup=close_open_markup,
  1006. padding=padding))
  1007. else:
  1008. self._emit(tokens.TagCloseOpen(padding=padding))
  1009. if contents:
  1010. self._emit_all(contents)
  1011. self._emit(tokens.TagOpenClose(wiki_markup=open_close_markup))
  1012. self._emit_text(tag)
  1013. self._emit(tokens.TagCloseClose())
  1014. def _handle_table_style(self, end_token):
  1015. """Handle style attributes for a table until ``end_token``."""
  1016. data = _TagOpenData()
  1017. data.context = _TagOpenData.CX_ATTR_READY
  1018. while True:
  1019. this = self._read()
  1020. can_exit = (not data.context & data.CX_QUOTED or
  1021. data.context & data.CX_NOTE_SPACE)
  1022. if this == end_token and can_exit:
  1023. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  1024. self._push_tag_buffer(data)
  1025. if this.isspace():
  1026. data.padding_buffer["first"] += this
  1027. return data.padding_buffer["first"]
  1028. if this is self.END or this == end_token:
  1029. if self._context & contexts.TAG_ATTR:
  1030. if data.context & data.CX_QUOTED:
  1031. # Unclosed attribute quote: reset, don't die
  1032. data.context = data.CX_ATTR_VALUE
  1033. self._memoize_bad_route()
  1034. self._pop()
  1035. self._head = data.reset
  1036. continue
  1037. self._pop()
  1038. self._fail_route()
  1039. else:
  1040. self._handle_tag_data(data, this)
  1041. self._head += 1
  1042. def _parse_table(self):
  1043. """Parse a wikicode table by starting with the first line."""
  1044. reset = self._head
  1045. self._head += 2
  1046. try:
  1047. self._push(contexts.TABLE_OPEN)
  1048. padding = self._handle_table_style("\n")
  1049. except BadRoute:
  1050. self._head = reset
  1051. self._emit_text("{")
  1052. return
  1053. style = self._pop()
  1054. self._head += 1
  1055. restore_point = self._stack_ident
  1056. try:
  1057. table = self._parse(contexts.TABLE_OPEN)
  1058. except BadRoute:
  1059. while self._stack_ident != restore_point:
  1060. self._memoize_bad_route()
  1061. self._pop()
  1062. self._head = reset
  1063. self._emit_text("{")
  1064. return
  1065. self._emit_table_tag("{|", "table", style, padding, None, table, "|}")
  1066. # Offset displacement done by _parse():
  1067. self._head -= 1
  1068. def _handle_table_row(self):
  1069. """Parse as style until end of the line, then continue."""
  1070. self._head += 2
  1071. if not self._can_recurse():
  1072. self._emit_text("|-")
  1073. self._head -= 1
  1074. return
  1075. self._push(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
  1076. padding = self._handle_table_style("\n")
  1077. style = self._pop()
  1078. # Don't parse the style separator:
  1079. self._head += 1
  1080. row = self._parse(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
  1081. self._emit_table_tag("|-", "tr", style, padding, None, row, "")
  1082. # Offset displacement done by parse():
  1083. self._head -= 1
  1084. def _handle_table_cell(self, markup, tag, line_context):
  1085. """Parse as normal syntax unless we hit a style marker, then parse
  1086. style as HTML attributes and the remainder as normal syntax."""
  1087. old_context = self._context
  1088. padding, style = "", None
  1089. self._head += len(markup)
  1090. reset = self._head
  1091. if not self._can_recurse():
  1092. self._emit_text(markup)
  1093. self._head -= 1
  1094. return
  1095. cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1096. line_context | contexts.TABLE_CELL_STYLE)
  1097. cell_context = self._context
  1098. self._context = old_context
  1099. reset_for_style = cell_context & contexts.TABLE_CELL_STYLE
  1100. if reset_for_style:
  1101. self._head = reset
  1102. self._push(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1103. line_context)
  1104. padding = self._handle_table_style("|")
  1105. style = self._pop()
  1106. # Don't parse the style separator:
  1107. self._head += 1
  1108. cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1109. line_context)
  1110. cell_context = self._context
  1111. self._context = old_context
  1112. close_open_markup = "|" if reset_for_style else None
  1113. self._emit_table_tag(markup, tag, style, padding, close_open_markup,
  1114. cell, "")
  1115. # Keep header/cell line contexts:
  1116. self._context |= cell_context & (contexts.TABLE_TH_LINE |
  1117. contexts.TABLE_TD_LINE)
  1118. # Offset displacement done by parse():
  1119. self._head -= 1
  1120. def _handle_table_cell_end(self, reset_for_style=False):
  1121. """Returns the current context, with the TABLE_CELL_STYLE flag set if
  1122. it is necessary to reset and parse style attributes."""
  1123. if reset_for_style:
  1124. self._context |= contexts.TABLE_CELL_STYLE
  1125. else:
  1126. self._context &= ~contexts.TABLE_CELL_STYLE
  1127. return self._pop(keep_context=True)
  1128. def _handle_table_row_end(self):
  1129. """Return the stack in order to handle the table row end."""
  1130. return self._pop()
  1131. def _handle_table_end(self):
  1132. """Return the stack in order to handle the table end."""
  1133. self._head += 2
  1134. return self._pop()
  1135. def _handle_end(self):
  1136. """Handle the end of the stream of wikitext."""
  1137. if self._context & contexts.FAIL:
  1138. if self._context & contexts.TAG_BODY:
  1139. if is_single(self._stack[1].text):
  1140. return self._handle_single_tag_end()
  1141. if self._context & contexts.TABLE_CELL_OPEN:
  1142. self._pop()
  1143. if self._context & contexts.DOUBLE:
  1144. self._pop()
  1145. self._fail_route()
  1146. return self._pop()
  1147. def _verify_safe(self, this):
  1148. """Make sure we are not trying to write an invalid character."""
  1149. context = self._context
  1150. if context & contexts.FAIL_NEXT:
  1151. return False
  1152. if context & contexts.WIKILINK_TITLE:
  1153. if this in ("]", "{"):
  1154. self._context |= contexts.FAIL_NEXT
  1155. elif this in ("\n", "[", "}", ">"):
  1156. return False
  1157. elif this == "<":
  1158. if self._read(1) == "!":
  1159. self._context |= contexts.FAIL_NEXT
  1160. else:
  1161. return False
  1162. return True
  1163. if context & contexts.EXT_LINK_TITLE:
  1164. return this != "\n"
  1165. if context & contexts.TEMPLATE_NAME:
  1166. if this == "{":
  1167. self._context |= contexts.HAS_TEMPLATE | contexts.FAIL_NEXT
  1168. return True
  1169. if this == "}" or (this == "<" and self._read(1) == "!"):
  1170. self._context |= contexts.FAIL_NEXT
  1171. return True
  1172. if this in ("[", "]", "<", ">"):
  1173. return False
  1174. if this == "|":
  1175. return True
  1176. if context & contexts.HAS_TEXT:
  1177. if context & contexts.FAIL_ON_TEXT:
  1178. if this is self.END or not this.isspace():
  1179. return False
  1180. elif this == "\n":
  1181. self._context |= contexts.FAIL_ON_TEXT
  1182. elif this is self.END or not this.isspace():
  1183. self._context |= contexts.HAS_TEXT
  1184. return True
  1185. if context & contexts.TAG_CLOSE:
  1186. return this != "<"
  1187. if context & contexts.FAIL_ON_EQUALS:
  1188. if this == "=":
  1189. return False
  1190. elif context & contexts.FAIL_ON_LBRACE:
  1191. if this == "{" or (self._read(-1) == self._read(-2) == "{"):
  1192. if context & contexts.TEMPLATE:
  1193. self._context |= contexts.FAIL_ON_EQUALS
  1194. else:
  1195. self._context |= contexts.FAIL_NEXT
  1196. return True
  1197. self._context ^= contexts.FAIL_ON_LBRACE
  1198. elif context & contexts.FAIL_ON_RBRACE:
  1199. if this == "}":
  1200. self._context |= contexts.FAIL_NEXT
  1201. return True
  1202. self._context ^= contexts.FAIL_ON_RBRACE
  1203. elif this == "{":
  1204. self._context |= contexts.FAIL_ON_LBRACE
  1205. elif this == "}":
  1206. self._context |= contexts.FAIL_ON_RBRACE
  1207. return True
  1208. def _parse(self, context=0, push=True):
  1209. """Parse the wikicode string, using *context* for when to stop."""
  1210. if push:
  1211. self._push(context)
  1212. while True:
  1213. this = self._read()
  1214. if self._context & contexts.UNSAFE:
  1215. if not self._verify_safe(this):
  1216. if self._context & contexts.DOUBLE:
  1217. self._pop()
  1218. self._fail_route()
  1219. if this not in self.MARKERS:
  1220. self._emit_text(this)
  1221. self._head += 1
  1222. continue
  1223. if this is self.END:
  1224. return self._handle_end()
  1225. nxt = self._read(1)
  1226. if this == nxt == "{":
  1227. if self._can_recurse():
  1228. self._parse_template_or_argument()
  1229. else:
  1230. self._emit_text("{")
  1231. elif this == "|" and self._context & contexts.TEMPLATE:
  1232. self._handle_template_param()
  1233. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  1234. if not self._global & contexts.GL_HEADING and self._read(-1) in ("\n", self.START) and nxt == "=":
  1235. self._parse_heading()
  1236. else:
  1237. self._handle_template_param_value()
  1238. elif this == nxt == "}" and self._context & contexts.TEMPLATE:
  1239. return self._handle_template_end()
  1240. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  1241. self._handle_argument_separator()
  1242. elif this == nxt == "}" and self._context & contexts.ARGUMENT:
  1243. if self._read(2) == "}":
  1244. return self._handle_argument_end()
  1245. self._emit_text("}")
  1246. elif this == nxt == "[" and self._can_recurse():
  1247. if not self._context & contexts.NO_WIKILINKS:
  1248. self._parse_wikilink()
  1249. else:
  1250. self._emit_text("[")
  1251. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  1252. self._handle_wikilink_separator()
  1253. elif this == nxt == "]" and self._context & contexts.WIKILINK:
  1254. return self._handle_wikilink_end()
  1255. elif this == "[":
  1256. self._parse_external_link(True)
  1257. elif this == ":" and self._read(-1) not in self.MARKERS:
  1258. self._parse_external_link(False)
  1259. elif this == "]" and self._context & contexts.EXT_LINK_TITLE:
  1260. return self._pop()
  1261. elif this == "=" and not self._global & contexts.GL_HEADING and not self._context & contexts.TEMPLATE:
  1262. if self._read(-1) in ("\n", self.START):
  1263. self._parse_heading()
  1264. else:
  1265. self._emit_text("=")
  1266. elif this == "=" and self._context & contexts.HEADING:
  1267. return self._handle_heading_end()
  1268. elif this == "\n" and self._context & contexts.HEADING:
  1269. self._fail_route()
  1270. elif this == "&":
  1271. self._parse_entity()
  1272. elif this == "<" and nxt == "!":
  1273. if self._read(2) == self._read(3) == "-":
  1274. self._parse_comment()
  1275. else:
  1276. self._emit_text(this)
  1277. elif this == "<" and nxt == "/" and self._read(2) is not self.END:
  1278. if self._context & contexts.TAG_BODY:
  1279. self._handle_tag_open_close()
  1280. else:
  1281. self._handle_invalid_tag_start()
  1282. elif this == "<" and not self._context & contexts.TAG_CLOSE:
  1283. if self._can_recurse():
  1284. self._parse_tag()
  1285. else:
  1286. self._emit_text("<")
  1287. elif this == ">" and self._context & contexts.TAG_CLOSE:
  1288. return self._handle_tag_close_close()
  1289. elif this == nxt == "'" and not self._skip_style_tags:
  1290. result = self._parse_style()
  1291. if result is not None:
  1292. return result
  1293. elif self._read(-1) in ("\n", self.START) and this in ("#", "*", ";", ":"):
  1294. self._handle_list()
  1295. elif self._read(-1) in ("\n", self.START) and (
  1296. this == nxt == self._read(2) == self._read(3) == "-"):
  1297. self._handle_hr()
  1298. elif this in ("\n", ":") and self._context & contexts.DL_TERM:
  1299. self._handle_dl_term()
  1300. if this == "\n":
  1301. # Kill potential table contexts
  1302. self._context &= ~contexts.TABLE_CELL_LINE_CONTEXTS
  1303. # Start of table parsing
  1304. elif this == "{" and nxt == "|" and (
  1305. self._read(-1) in ("\n", self.START) or
  1306. (self._read(-2) in ("\n", self.START) and self._read(-1).isspace())):
  1307. if self._can_recurse():
  1308. self._parse_table()
  1309. else:
  1310. self._emit_text("{")
  1311. elif self._context & contexts.TABLE_OPEN:
  1312. if this == nxt == "|" and self._context & contexts.TABLE_TD_LINE:
  1313. if self._context & contexts.TABLE_CELL_OPEN:
  1314. return self._handle_table_cell_end()
  1315. self._handle_table_cell("||", "td", contexts.TABLE_TD_LINE)
  1316. elif this == nxt == "|" and self._context & contexts.TABLE_TH_LINE:
  1317. if self._context & contexts.TABLE_CELL_OPEN:
  1318. return self._handle_table_cell_end()
  1319. self._handle_table_cell("||", "th", contexts.TABLE_TH_LINE)
  1320. elif this == nxt == "!" and self._context & contexts.TABLE_TH_LINE:
  1321. if self._context & contexts.TABLE_CELL_OPEN:
  1322. return self._handle_table_cell_end()
  1323. self._handle_table_cell("!!", "th", contexts.TABLE_TH_LINE)
  1324. elif this == "|" and self._context & contexts.TABLE_CELL_STYLE:
  1325. return self._handle_table_cell_end(reset_for_style=True)
  1326. # on newline, clear out cell line contexts
  1327. elif this == "\n" and self._context & contexts.TABLE_CELL_LINE_CONTEXTS:
  1328. self._context &= ~contexts.TABLE_CELL_LINE_CONTEXTS
  1329. self._emit_text(this)
  1330. elif (self._read(-1) in ("\n", self.START) or
  1331. (self._read(-2) in ("\n", self.START) and self._read(-1).isspace())):
  1332. if this == "|" and nxt == "}":
  1333. if self._context & contexts.TABLE_CELL_OPEN:
  1334. return self._handle_table_cell_end()
  1335. if self._context & contexts.TABLE_ROW_OPEN:
  1336. return self._handle_table_row_end()
  1337. return self._handle_table_end()
  1338. if this == "|" and nxt == "-":
  1339. if self._context & contexts.TABLE_CELL_OPEN:
  1340. return self._handle_table_cell_end()
  1341. if self._context & contexts.TABLE_ROW_OPEN:
  1342. return self._handle_table_row_end()
  1343. self._handle_table_row()
  1344. elif this == "|":
  1345. if self._context & contexts.TABLE_CELL_OPEN:
  1346. return self._handle_table_cell_end()
  1347. self._handle_table_cell("|", "td", contexts.TABLE_TD_LINE)
  1348. elif this == "!":
  1349. if self._context & contexts.TABLE_CELL_OPEN:
  1350. return self._handle_table_cell_end()
  1351. self._handle_table_cell("!", "th", contexts.TABLE_TH_LINE)
  1352. else:
  1353. self._emit_text(this)
  1354. else:
  1355. self._emit_text(this)
  1356. else:
  1357. self._emit_text(this)
  1358. self._head += 1
  1359. def tokenize(self, text, context=0, skip_style_tags=False):
  1360. """Build a list of tokens from a string of wikicode and return it."""
  1361. split = self.regex.split(text)
  1362. self._text = [segment for segment in split if segment]
  1363. self._head = self._global = self._depth = 0
  1364. self._bad_routes = set()
  1365. self._skip_style_tags = skip_style_tags
  1366. try:
  1367. result = self._parse(context)
  1368. except BadRoute as exc: # pragma: no cover (untestable/exceptional case)
  1369. raise ParserError("Python tokenizer exited with BadRoute") from exc
  1370. if self._stacks: # pragma: no cover (untestable/exceptional case)
  1371. err = "Python tokenizer exited with non-empty token stack"
  1372. raise ParserError(err)
  1373. return result