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.
 
 
 
 

1481 lines
58 KiB

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