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.
 
 
 
 

1470 lines
58 KiB

  1. #
  2. # Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. import html.entities as htmlentities
  22. from math import log
  23. import re
  24. from . import contexts, tokens
  25. from .errors import ParserError
  26. from ..definitions import (get_html_tag, is_parsable, is_single,
  27. is_single_only, is_scheme)
  28. __all__ = ["Tokenizer"]
  29. class BadRoute(Exception):
  30. """Raised internally when the current tokenization route is invalid."""
  31. def __init__(self, context=0):
  32. super().__init__()
  33. self.context = context
  34. class _TagOpenData:
  35. """Stores data about an HTML open tag, like ``<ref name="foo">``."""
  36. CX_NAME = 1 << 0
  37. CX_ATTR_READY = 1 << 1
  38. CX_ATTR_NAME = 1 << 2
  39. CX_ATTR_VALUE = 1 << 3
  40. CX_QUOTED = 1 << 4
  41. CX_NOTE_SPACE = 1 << 5
  42. CX_NOTE_EQUALS = 1 << 6
  43. CX_NOTE_QUOTE = 1 << 7
  44. def __init__(self):
  45. self.context = self.CX_NAME
  46. self.padding_buffer = {"first": "", "before_eq": "", "after_eq": ""}
  47. self.quoter = None
  48. self.reset = 0
  49. class Tokenizer:
  50. """Creates a list of tokens from a string of wikicode."""
  51. USES_C = False
  52. START = object()
  53. END = object()
  54. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "'", "#", "*", ";",
  55. ":", "/", "-", "!", "\n", START, END]
  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, _delta = 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. valid = "abcdefghijklmnopqrstuvwxyz0123456789+.-"
  322. all_valid = lambda: all(char in valid for char in self._read())
  323. scheme = ""
  324. while self._read() is not self.END and all_valid():
  325. scheme += self._read()
  326. self._emit_text(self._read())
  327. self._head += 1
  328. if self._read() != ":":
  329. self._fail_route()
  330. self._emit_text(":")
  331. self._head += 1
  332. slashes = self._read() == self._read(1) == "/"
  333. if slashes:
  334. self._emit_text("//")
  335. self._head += 2
  336. if not is_scheme(scheme, slashes):
  337. self._fail_route()
  338. def _parse_free_uri_scheme(self):
  339. """Parse the URI scheme of a free (no brackets) external link."""
  340. valid = "abcdefghijklmnopqrstuvwxyz0123456789+.-"
  341. scheme = []
  342. try:
  343. # We have to backtrack through the textbuffer looking for our
  344. # scheme since it was just parsed as text:
  345. for chunk in reversed(self._textbuffer):
  346. for char in reversed(chunk):
  347. if char.isspace() or char in self.MARKERS:
  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 " " in this:
  433. before, after = this.split(" ", 1)
  434. if brackets:
  435. self._emit_text(before)
  436. self._emit(tokens.ExternalLinkSeparator())
  437. if after:
  438. self._emit_text(after)
  439. self._context ^= contexts.EXT_LINK_URI
  440. self._context |= contexts.EXT_LINK_TITLE
  441. self._head += 1
  442. return self._parse(push=False), None, 0
  443. punct, tail = self._handle_free_link_text(punct, tail, before)
  444. return self._pop(), tail + " " + after, 0
  445. elif not brackets:
  446. punct, tail = self._handle_free_link_text(punct, tail, this)
  447. else:
  448. self._emit_text(this)
  449. self._head += 1
  450. def _remove_uri_scheme_from_textbuffer(self, scheme):
  451. """Remove the URI scheme of a new external link from the textbuffer."""
  452. length = len(scheme)
  453. while length:
  454. if length < len(self._textbuffer[-1]):
  455. self._textbuffer[-1] = self._textbuffer[-1][:-length]
  456. break
  457. length -= len(self._textbuffer[-1])
  458. self._textbuffer.pop()
  459. def _parse_external_link(self, brackets):
  460. """Parse an external link at the head of the wikicode string."""
  461. if self._context & contexts.NO_EXT_LINKS or not self._can_recurse():
  462. if not brackets and self._context & contexts.DL_TERM:
  463. self._handle_dl_term()
  464. else:
  465. self._emit_text(self._read())
  466. return
  467. reset = self._head
  468. self._head += 1
  469. try:
  470. link, extra, delta = self._really_parse_external_link(brackets)
  471. except BadRoute:
  472. self._head = reset
  473. if not brackets and self._context & contexts.DL_TERM:
  474. self._handle_dl_term()
  475. else:
  476. self._emit_text(self._read())
  477. else:
  478. if not brackets:
  479. scheme = link[0].text.split(":", 1)[0]
  480. self._remove_uri_scheme_from_textbuffer(scheme)
  481. self._emit(tokens.ExternalLinkOpen(brackets=brackets))
  482. self._emit_all(link)
  483. self._emit(tokens.ExternalLinkClose())
  484. self._head += delta
  485. if extra:
  486. self._emit_text(extra)
  487. def _parse_heading(self):
  488. """Parse a section heading at the head of the wikicode string."""
  489. self._global |= contexts.GL_HEADING
  490. reset = self._head
  491. self._head += 1
  492. best = 1
  493. while self._read() == "=":
  494. best += 1
  495. self._head += 1
  496. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  497. try:
  498. title, level = self._parse(context)
  499. except BadRoute:
  500. self._head = reset + best - 1
  501. self._emit_text("=" * best)
  502. else:
  503. self._emit(tokens.HeadingStart(level=level))
  504. if level < best:
  505. self._emit_text("=" * (best - level))
  506. self._emit_all(title)
  507. self._emit(tokens.HeadingEnd())
  508. finally:
  509. self._global ^= contexts.GL_HEADING
  510. def _handle_heading_end(self):
  511. """Handle the end of a section heading at the head of the string."""
  512. reset = self._head
  513. self._head += 1
  514. best = 1
  515. while self._read() == "=":
  516. best += 1
  517. self._head += 1
  518. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  519. level = min(current, min(best, 6))
  520. try: # Try to check for a heading closure after this one
  521. after, after_level = self._parse(self._context)
  522. except BadRoute:
  523. if level < best:
  524. self._emit_text("=" * (best - level))
  525. self._head = reset + best - 1
  526. return self._pop(), level
  527. else: # Found another closure
  528. self._emit_text("=" * best)
  529. self._emit_all(after)
  530. return self._pop(), after_level
  531. def _really_parse_entity(self):
  532. """Actually parse an HTML entity and ensure that it is valid."""
  533. self._emit(tokens.HTMLEntityStart())
  534. self._head += 1
  535. this = self._read(strict=True)
  536. if this == "#":
  537. numeric = True
  538. self._emit(tokens.HTMLEntityNumeric())
  539. self._head += 1
  540. this = self._read(strict=True)
  541. if this[0].lower() == "x":
  542. hexadecimal = True
  543. self._emit(tokens.HTMLEntityHex(char=this[0]))
  544. this = this[1:]
  545. if not this:
  546. self._fail_route()
  547. else:
  548. hexadecimal = False
  549. else:
  550. numeric = hexadecimal = False
  551. valid = "0123456789abcdefABCDEF" if hexadecimal else "0123456789"
  552. if not numeric and not hexadecimal:
  553. valid += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  554. if not all([char in valid for char in this]):
  555. self._fail_route()
  556. self._head += 1
  557. if self._read() != ";":
  558. self._fail_route()
  559. if numeric:
  560. test = int(this, 16) if hexadecimal else int(this)
  561. if test < 1 or test > 0x10FFFF:
  562. self._fail_route()
  563. else:
  564. if this not in htmlentities.entitydefs:
  565. self._fail_route()
  566. self._emit(tokens.Text(text=this))
  567. self._emit(tokens.HTMLEntityEnd())
  568. def _parse_entity(self):
  569. """Parse an HTML entity at the head of the wikicode string."""
  570. reset = self._head
  571. try:
  572. self._push(contexts.HTML_ENTITY)
  573. self._really_parse_entity()
  574. except BadRoute:
  575. self._head = reset
  576. self._emit_text(self._read())
  577. else:
  578. self._emit_all(self._pop())
  579. def _parse_comment(self):
  580. """Parse an HTML comment at the head of the wikicode string."""
  581. self._head += 4
  582. reset = self._head - 1
  583. self._push()
  584. while True:
  585. this = self._read()
  586. if this == self.END:
  587. self._pop()
  588. self._head = reset
  589. self._emit_text("<!--")
  590. return
  591. if this == self._read(1) == "-" and self._read(2) == ">":
  592. self._emit_first(tokens.CommentStart())
  593. self._emit(tokens.CommentEnd())
  594. self._emit_all(self._pop())
  595. self._head += 2
  596. if self._context & contexts.FAIL_NEXT:
  597. # _verify_safe() sets this flag while parsing a template
  598. # or link when it encounters what might be a comment -- we
  599. # must unset it to let _verify_safe() know it was correct:
  600. self._context ^= contexts.FAIL_NEXT
  601. return
  602. self._emit_text(this)
  603. self._head += 1
  604. def _push_tag_buffer(self, data):
  605. """Write a pending tag attribute from *data* to the stack."""
  606. if data.context & data.CX_QUOTED:
  607. self._emit_first(tokens.TagAttrQuote(char=data.quoter))
  608. self._emit_all(self._pop())
  609. buf = data.padding_buffer
  610. self._emit_first(tokens.TagAttrStart(
  611. pad_first=buf["first"], pad_before_eq=buf["before_eq"],
  612. pad_after_eq=buf["after_eq"]))
  613. self._emit_all(self._pop())
  614. for key in data.padding_buffer:
  615. data.padding_buffer[key] = ""
  616. def _handle_tag_space(self, data, text):
  617. """Handle whitespace (*text*) inside of an HTML open tag."""
  618. ctx = data.context
  619. end_of_value = ctx & data.CX_ATTR_VALUE and not ctx & (data.CX_QUOTED | data.CX_NOTE_QUOTE)
  620. if end_of_value or (ctx & data.CX_QUOTED and ctx & data.CX_NOTE_SPACE):
  621. self._push_tag_buffer(data)
  622. data.context = data.CX_ATTR_READY
  623. elif ctx & data.CX_NOTE_SPACE:
  624. data.context = data.CX_ATTR_READY
  625. elif ctx & data.CX_ATTR_NAME:
  626. data.context |= data.CX_NOTE_EQUALS
  627. data.padding_buffer["before_eq"] += text
  628. if ctx & data.CX_QUOTED and not ctx & data.CX_NOTE_SPACE:
  629. self._emit_text(text)
  630. elif data.context & data.CX_ATTR_READY:
  631. data.padding_buffer["first"] += text
  632. elif data.context & data.CX_ATTR_VALUE:
  633. data.padding_buffer["after_eq"] += text
  634. def _handle_tag_text(self, text):
  635. """Handle regular *text* inside of an HTML open tag."""
  636. nxt = self._read(1)
  637. if not self._can_recurse() or text not in self.MARKERS:
  638. self._emit_text(text)
  639. elif text == nxt == "{":
  640. self._parse_template_or_argument()
  641. elif text == nxt == "[":
  642. self._parse_wikilink()
  643. elif text == "<":
  644. self._parse_tag()
  645. else:
  646. self._emit_text(text)
  647. def _handle_tag_data(self, data, text):
  648. """Handle all sorts of *text* data inside of an HTML open tag."""
  649. for chunk in self.tag_splitter.split(text):
  650. if not chunk:
  651. continue
  652. if data.context & data.CX_NAME:
  653. if chunk in self.MARKERS or chunk.isspace():
  654. self._fail_route() # Tags must start with text, not spaces
  655. data.context = data.CX_NOTE_SPACE
  656. elif chunk.isspace():
  657. self._handle_tag_space(data, chunk)
  658. continue
  659. elif data.context & data.CX_NOTE_SPACE:
  660. if data.context & data.CX_QUOTED:
  661. data.context = data.CX_ATTR_VALUE
  662. self._memoize_bad_route()
  663. self._pop()
  664. self._head = data.reset - 1 # Will be auto-incremented
  665. return # Break early
  666. self._fail_route()
  667. elif data.context & data.CX_ATTR_READY:
  668. data.context = data.CX_ATTR_NAME
  669. self._push(contexts.TAG_ATTR)
  670. elif data.context & data.CX_ATTR_NAME:
  671. if chunk == "=":
  672. data.context = data.CX_ATTR_VALUE | data.CX_NOTE_QUOTE
  673. self._emit(tokens.TagAttrEquals())
  674. continue
  675. if data.context & data.CX_NOTE_EQUALS:
  676. self._push_tag_buffer(data)
  677. data.context = data.CX_ATTR_NAME
  678. self._push(contexts.TAG_ATTR)
  679. else: # data.context & data.CX_ATTR_VALUE assured
  680. escaped = self._read(-1) == "\\" and self._read(-2) != "\\"
  681. if data.context & data.CX_NOTE_QUOTE:
  682. data.context ^= data.CX_NOTE_QUOTE
  683. if chunk in "'\"" and not escaped:
  684. data.context |= data.CX_QUOTED
  685. data.quoter = chunk
  686. data.reset = self._head
  687. try:
  688. self._push(self._context)
  689. except BadRoute:
  690. # Already failed to parse this as a quoted string
  691. data.context = data.CX_ATTR_VALUE
  692. self._head -= 1
  693. return
  694. continue
  695. elif data.context & data.CX_QUOTED:
  696. if chunk == data.quoter and not escaped:
  697. data.context |= data.CX_NOTE_SPACE
  698. continue
  699. self._handle_tag_text(chunk)
  700. def _handle_tag_close_open(self, data, token):
  701. """Handle the closing of a open tag (``<foo>``)."""
  702. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  703. self._push_tag_buffer(data)
  704. self._emit(token(padding=data.padding_buffer["first"]))
  705. self._head += 1
  706. def _handle_tag_open_close(self):
  707. """Handle the opening of a closing tag (``</foo>``)."""
  708. self._emit(tokens.TagOpenClose())
  709. self._push(contexts.TAG_CLOSE)
  710. self._head += 1
  711. def _handle_tag_close_close(self):
  712. """Handle the ending of a closing tag (``</foo>``)."""
  713. strip = lambda tok: tok.text.rstrip().lower()
  714. closing = self._pop()
  715. if len(closing) != 1 or (not isinstance(closing[0], tokens.Text) or
  716. strip(closing[0]) != strip(self._stack[1])):
  717. self._fail_route()
  718. self._emit_all(closing)
  719. self._emit(tokens.TagCloseClose())
  720. return self._pop()
  721. def _handle_blacklisted_tag(self):
  722. """Handle the body of an HTML tag that is parser-blacklisted."""
  723. strip = lambda text: text.rstrip().lower()
  724. while True:
  725. this, nxt = self._read(), self._read(1)
  726. if this is self.END:
  727. self._fail_route()
  728. elif this == "<" and nxt == "/":
  729. self._head += 3
  730. if self._read() != ">" or (strip(self._read(-1)) !=
  731. strip(self._stack[1].text)):
  732. self._head -= 1
  733. self._emit_text("</")
  734. continue
  735. self._emit(tokens.TagOpenClose())
  736. self._emit_text(self._read(-1))
  737. self._emit(tokens.TagCloseClose())
  738. return self._pop()
  739. elif this == "&":
  740. self._parse_entity()
  741. else:
  742. self._emit_text(this)
  743. self._head += 1
  744. def _handle_single_only_tag_end(self):
  745. """Handle the end of an implicitly closing single-only HTML tag."""
  746. padding = self._stack.pop().padding
  747. self._emit(tokens.TagCloseSelfclose(padding=padding, implicit=True))
  748. self._head -= 1 # Offset displacement done by _handle_tag_close_open
  749. return self._pop()
  750. def _handle_single_tag_end(self):
  751. """Handle the stream end when inside a single-supporting HTML tag."""
  752. stack = self._stack
  753. # We need to find the index of the TagCloseOpen token corresponding to
  754. # the TagOpenOpen token located at index 0:
  755. depth = 1
  756. for index, token in enumerate(stack[2:], 2):
  757. if isinstance(token, tokens.TagOpenOpen):
  758. depth += 1
  759. elif isinstance(token, tokens.TagCloseOpen):
  760. depth -= 1
  761. if depth == 0:
  762. break
  763. elif isinstance(token, tokens.TagCloseSelfclose):
  764. depth -= 1
  765. if depth == 0: # pragma: no cover (untestable/exceptional)
  766. raise ParserError(
  767. "_handle_single_tag_end() got an unexpected "
  768. "TagCloseSelfclose")
  769. else: # pragma: no cover (untestable/exceptional case)
  770. raise ParserError("_handle_single_tag_end() missed a TagCloseOpen")
  771. padding = stack[index].padding
  772. stack[index] = tokens.TagCloseSelfclose(padding=padding, implicit=True)
  773. return self._pop()
  774. def _really_parse_tag(self):
  775. """Actually parse an HTML tag, starting with the open (``<foo>``)."""
  776. data = _TagOpenData()
  777. self._push(contexts.TAG_OPEN)
  778. self._emit(tokens.TagOpenOpen())
  779. while True:
  780. this, nxt = self._read(), self._read(1)
  781. can_exit = (not data.context & (data.CX_QUOTED | data.CX_NAME) or
  782. data.context & data.CX_NOTE_SPACE)
  783. if this is self.END:
  784. if self._context & contexts.TAG_ATTR:
  785. if data.context & data.CX_QUOTED:
  786. # Unclosed attribute quote: reset, don't die
  787. data.context = data.CX_ATTR_VALUE
  788. self._memoize_bad_route()
  789. self._pop()
  790. self._head = data.reset
  791. continue
  792. self._pop()
  793. self._fail_route()
  794. elif this == ">" and can_exit:
  795. self._handle_tag_close_open(data, tokens.TagCloseOpen)
  796. self._context = contexts.TAG_BODY
  797. if is_single_only(self._stack[1].text):
  798. return self._handle_single_only_tag_end()
  799. if is_parsable(self._stack[1].text):
  800. return self._parse(push=False)
  801. return self._handle_blacklisted_tag()
  802. elif this == "/" and nxt == ">" and can_exit:
  803. self._handle_tag_close_open(data, tokens.TagCloseSelfclose)
  804. return self._pop()
  805. else:
  806. self._handle_tag_data(data, this)
  807. self._head += 1
  808. def _handle_invalid_tag_start(self):
  809. """Handle the (possible) start of an implicitly closing single tag."""
  810. reset = self._head + 1
  811. self._head += 2
  812. try:
  813. if not is_single_only(self.tag_splitter.split(self._read())[0]):
  814. raise BadRoute()
  815. tag = self._really_parse_tag()
  816. except BadRoute:
  817. self._head = reset
  818. self._emit_text("</")
  819. else:
  820. tag[0].invalid = True # Set flag of TagOpenOpen
  821. self._emit_all(tag)
  822. def _parse_tag(self):
  823. """Parse an HTML tag at the head of the wikicode string."""
  824. reset = self._head
  825. self._head += 1
  826. try:
  827. tag = self._really_parse_tag()
  828. except BadRoute:
  829. self._head = reset
  830. self._emit_text("<")
  831. else:
  832. self._emit_all(tag)
  833. def _emit_style_tag(self, tag, markup, body):
  834. """Write the body of a tag and the tokens that should surround it."""
  835. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  836. self._emit_text(tag)
  837. self._emit(tokens.TagCloseOpen())
  838. self._emit_all(body)
  839. self._emit(tokens.TagOpenClose())
  840. self._emit_text(tag)
  841. self._emit(tokens.TagCloseClose())
  842. def _parse_italics(self):
  843. """Parse wiki-style italics."""
  844. reset = self._head
  845. try:
  846. stack = self._parse(contexts.STYLE_ITALICS)
  847. except BadRoute as route:
  848. self._head = reset
  849. if route.context & contexts.STYLE_PASS_AGAIN:
  850. new_ctx = contexts.STYLE_ITALICS | contexts.STYLE_SECOND_PASS
  851. try:
  852. stack = self._parse(new_ctx)
  853. except BadRoute:
  854. self._head = reset
  855. self._emit_text("''")
  856. return
  857. else:
  858. self._emit_text("''")
  859. return
  860. self._emit_style_tag("i", "''", stack)
  861. def _parse_bold(self):
  862. """Parse wiki-style bold."""
  863. reset = self._head
  864. try:
  865. stack = self._parse(contexts.STYLE_BOLD)
  866. except BadRoute:
  867. self._head = reset
  868. if self._context & contexts.STYLE_SECOND_PASS:
  869. self._emit_text("'")
  870. return True
  871. if self._context & contexts.STYLE_ITALICS:
  872. self._context |= contexts.STYLE_PASS_AGAIN
  873. self._emit_text("'''")
  874. else:
  875. self._emit_text("'")
  876. self._parse_italics()
  877. else:
  878. self._emit_style_tag("b", "'''", stack)
  879. return False
  880. def _parse_italics_and_bold(self):
  881. """Parse wiki-style italics and bold together (i.e., five ticks)."""
  882. reset = self._head
  883. try:
  884. stack = self._parse(contexts.STYLE_BOLD)
  885. except BadRoute:
  886. self._head = reset
  887. try:
  888. stack = self._parse(contexts.STYLE_ITALICS)
  889. except BadRoute:
  890. self._head = reset
  891. self._emit_text("'''''")
  892. else:
  893. reset = self._head
  894. try:
  895. stack2 = self._parse(contexts.STYLE_BOLD)
  896. except BadRoute:
  897. self._head = reset
  898. self._emit_text("'''")
  899. self._emit_style_tag("i", "''", stack)
  900. else:
  901. self._push()
  902. self._emit_style_tag("i", "''", stack)
  903. self._emit_all(stack2)
  904. self._emit_style_tag("b", "'''", self._pop())
  905. else:
  906. reset = self._head
  907. try:
  908. stack2 = self._parse(contexts.STYLE_ITALICS)
  909. except BadRoute:
  910. self._head = reset
  911. self._emit_text("''")
  912. self._emit_style_tag("b", "'''", stack)
  913. else:
  914. self._push()
  915. self._emit_style_tag("b", "'''", stack)
  916. self._emit_all(stack2)
  917. self._emit_style_tag("i", "''", self._pop())
  918. def _parse_style(self):
  919. """Parse wiki-style formatting (``''``/``'''`` for italics/bold)."""
  920. self._head += 2
  921. ticks = 2
  922. while self._read() == "'":
  923. self._head += 1
  924. ticks += 1
  925. italics = self._context & contexts.STYLE_ITALICS
  926. bold = self._context & contexts.STYLE_BOLD
  927. if ticks > 5:
  928. self._emit_text("'" * (ticks - 5))
  929. ticks = 5
  930. elif ticks == 4:
  931. self._emit_text("'")
  932. ticks = 3
  933. if (italics and ticks in (2, 5)) or (bold and ticks in (3, 5)):
  934. if ticks == 5:
  935. self._head -= 3 if italics else 2
  936. return self._pop()
  937. if not self._can_recurse():
  938. if ticks == 3:
  939. if self._context & contexts.STYLE_SECOND_PASS:
  940. self._emit_text("'")
  941. return self._pop()
  942. if self._context & contexts.STYLE_ITALICS:
  943. self._context |= contexts.STYLE_PASS_AGAIN
  944. self._emit_text("'" * ticks)
  945. elif ticks == 2:
  946. self._parse_italics()
  947. elif ticks == 3:
  948. if self._parse_bold():
  949. return self._pop()
  950. else: # ticks == 5
  951. self._parse_italics_and_bold()
  952. self._head -= 1
  953. def _handle_list_marker(self):
  954. """Handle a list marker at the head (``#``, ``*``, ``;``, ``:``)."""
  955. markup = self._read()
  956. if markup == ";":
  957. self._context |= contexts.DL_TERM
  958. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  959. self._emit_text(get_html_tag(markup))
  960. self._emit(tokens.TagCloseSelfclose())
  961. def _handle_list(self):
  962. """Handle a wiki-style list (``#``, ``*``, ``;``, ``:``)."""
  963. self._handle_list_marker()
  964. while self._read(1) in ("#", "*", ";", ":"):
  965. self._head += 1
  966. self._handle_list_marker()
  967. def _handle_hr(self):
  968. """Handle a wiki-style horizontal rule (``----``) in the string."""
  969. length = 4
  970. self._head += 3
  971. while self._read(1) == "-":
  972. length += 1
  973. self._head += 1
  974. self._emit(tokens.TagOpenOpen(wiki_markup="-" * length))
  975. self._emit_text("hr")
  976. self._emit(tokens.TagCloseSelfclose())
  977. def _handle_dl_term(self):
  978. """Handle the term in a description list (``foo`` in ``;foo:bar``)."""
  979. self._context ^= contexts.DL_TERM
  980. if self._read() == ":":
  981. self._handle_list_marker()
  982. else:
  983. self._emit_text("\n")
  984. def _emit_table_tag(self, open_open_markup, tag, style, padding,
  985. close_open_markup, contents, open_close_markup):
  986. """Emit a table tag."""
  987. self._emit(tokens.TagOpenOpen(wiki_markup=open_open_markup))
  988. self._emit_text(tag)
  989. if style:
  990. self._emit_all(style)
  991. if close_open_markup:
  992. self._emit(tokens.TagCloseOpen(wiki_markup=close_open_markup,
  993. padding=padding))
  994. else:
  995. self._emit(tokens.TagCloseOpen(padding=padding))
  996. if contents:
  997. self._emit_all(contents)
  998. self._emit(tokens.TagOpenClose(wiki_markup=open_close_markup))
  999. self._emit_text(tag)
  1000. self._emit(tokens.TagCloseClose())
  1001. def _handle_table_style(self, end_token):
  1002. """Handle style attributes for a table until ``end_token``."""
  1003. data = _TagOpenData()
  1004. data.context = _TagOpenData.CX_ATTR_READY
  1005. while True:
  1006. this = self._read()
  1007. can_exit = (not data.context & data.CX_QUOTED or
  1008. data.context & data.CX_NOTE_SPACE)
  1009. if this == end_token and can_exit:
  1010. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  1011. self._push_tag_buffer(data)
  1012. if this.isspace():
  1013. data.padding_buffer["first"] += this
  1014. return data.padding_buffer["first"]
  1015. if this is self.END or this == end_token:
  1016. if self._context & contexts.TAG_ATTR:
  1017. if data.context & data.CX_QUOTED:
  1018. # Unclosed attribute quote: reset, don't die
  1019. data.context = data.CX_ATTR_VALUE
  1020. self._memoize_bad_route()
  1021. self._pop()
  1022. self._head = data.reset
  1023. continue
  1024. self._pop()
  1025. self._fail_route()
  1026. else:
  1027. self._handle_tag_data(data, this)
  1028. self._head += 1
  1029. def _parse_table(self):
  1030. """Parse a wikicode table by starting with the first line."""
  1031. reset = self._head
  1032. self._head += 2
  1033. try:
  1034. self._push(contexts.TABLE_OPEN)
  1035. padding = self._handle_table_style("\n")
  1036. except BadRoute:
  1037. self._head = reset
  1038. self._emit_text("{")
  1039. return
  1040. style = self._pop()
  1041. self._head += 1
  1042. restore_point = self._stack_ident
  1043. try:
  1044. table = self._parse(contexts.TABLE_OPEN)
  1045. except BadRoute:
  1046. while self._stack_ident != restore_point:
  1047. self._memoize_bad_route()
  1048. self._pop()
  1049. self._head = reset
  1050. self._emit_text("{")
  1051. return
  1052. self._emit_table_tag("{|", "table", style, padding, None, table, "|}")
  1053. # Offset displacement done by _parse():
  1054. self._head -= 1
  1055. def _handle_table_row(self):
  1056. """Parse as style until end of the line, then continue."""
  1057. self._head += 2
  1058. if not self._can_recurse():
  1059. self._emit_text("|-")
  1060. self._head -= 1
  1061. return
  1062. self._push(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
  1063. padding = self._handle_table_style("\n")
  1064. style = self._pop()
  1065. # Don't parse the style separator:
  1066. self._head += 1
  1067. row = self._parse(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
  1068. self._emit_table_tag("|-", "tr", style, padding, None, row, "")
  1069. # Offset displacement done by parse():
  1070. self._head -= 1
  1071. def _handle_table_cell(self, markup, tag, line_context):
  1072. """Parse as normal syntax unless we hit a style marker, then parse
  1073. style as HTML attributes and the remainder as normal syntax."""
  1074. old_context = self._context
  1075. padding, style = "", None
  1076. self._head += len(markup)
  1077. reset = self._head
  1078. if not self._can_recurse():
  1079. self._emit_text(markup)
  1080. self._head -= 1
  1081. return
  1082. cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1083. line_context | contexts.TABLE_CELL_STYLE)
  1084. cell_context = self._context
  1085. self._context = old_context
  1086. reset_for_style = cell_context & contexts.TABLE_CELL_STYLE
  1087. if reset_for_style:
  1088. self._head = reset
  1089. self._push(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1090. line_context)
  1091. padding = self._handle_table_style("|")
  1092. style = self._pop()
  1093. # Don't parse the style separator:
  1094. self._head += 1
  1095. cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1096. line_context)
  1097. cell_context = self._context
  1098. self._context = old_context
  1099. close_open_markup = "|" if reset_for_style else None
  1100. self._emit_table_tag(markup, tag, style, padding, close_open_markup,
  1101. cell, "")
  1102. # Keep header/cell line contexts:
  1103. self._context |= cell_context & (contexts.TABLE_TH_LINE |
  1104. contexts.TABLE_TD_LINE)
  1105. # Offset displacement done by parse():
  1106. self._head -= 1
  1107. def _handle_table_cell_end(self, reset_for_style=False):
  1108. """Returns the current context, with the TABLE_CELL_STYLE flag set if
  1109. it is necessary to reset and parse style attributes."""
  1110. if reset_for_style:
  1111. self._context |= contexts.TABLE_CELL_STYLE
  1112. else:
  1113. self._context &= ~contexts.TABLE_CELL_STYLE
  1114. return self._pop(keep_context=True)
  1115. def _handle_table_row_end(self):
  1116. """Return the stack in order to handle the table row end."""
  1117. return self._pop()
  1118. def _handle_table_end(self):
  1119. """Return the stack in order to handle the table end."""
  1120. self._head += 2
  1121. return self._pop()
  1122. def _handle_end(self):
  1123. """Handle the end of the stream of wikitext."""
  1124. if self._context & contexts.FAIL:
  1125. if self._context & contexts.TAG_BODY:
  1126. if is_single(self._stack[1].text):
  1127. return self._handle_single_tag_end()
  1128. if self._context & contexts.TABLE_CELL_OPEN:
  1129. self._pop()
  1130. if self._context & contexts.DOUBLE:
  1131. self._pop()
  1132. self._fail_route()
  1133. return self._pop()
  1134. def _verify_safe(self, this):
  1135. """Make sure we are not trying to write an invalid character."""
  1136. context = self._context
  1137. if context & contexts.FAIL_NEXT:
  1138. return False
  1139. if context & contexts.WIKILINK_TITLE:
  1140. if this in ("]", "{"):
  1141. self._context |= contexts.FAIL_NEXT
  1142. elif this in ("\n", "[", "}", ">"):
  1143. return False
  1144. elif this == "<":
  1145. if self._read(1) == "!":
  1146. self._context |= contexts.FAIL_NEXT
  1147. else:
  1148. return False
  1149. return True
  1150. if context & contexts.EXT_LINK_TITLE:
  1151. return this != "\n"
  1152. if context & contexts.TEMPLATE_NAME:
  1153. if this == "{":
  1154. self._context |= contexts.HAS_TEMPLATE | contexts.FAIL_NEXT
  1155. return True
  1156. if this == "}" or (this == "<" and self._read(1) == "!"):
  1157. self._context |= contexts.FAIL_NEXT
  1158. return True
  1159. if this in ("[", "]", "<", ">"):
  1160. return False
  1161. if this == "|":
  1162. return True
  1163. if context & contexts.HAS_TEXT:
  1164. if context & contexts.FAIL_ON_TEXT:
  1165. if this is self.END or not this.isspace():
  1166. return False
  1167. elif this == "\n":
  1168. self._context |= contexts.FAIL_ON_TEXT
  1169. elif this is self.END or not this.isspace():
  1170. self._context |= contexts.HAS_TEXT
  1171. return True
  1172. if context & contexts.TAG_CLOSE:
  1173. return this != "<"
  1174. if context & contexts.FAIL_ON_EQUALS:
  1175. if this == "=":
  1176. return False
  1177. elif context & contexts.FAIL_ON_LBRACE:
  1178. if this == "{" or (self._read(-1) == self._read(-2) == "{"):
  1179. if context & contexts.TEMPLATE:
  1180. self._context |= contexts.FAIL_ON_EQUALS
  1181. else:
  1182. self._context |= contexts.FAIL_NEXT
  1183. return True
  1184. self._context ^= contexts.FAIL_ON_LBRACE
  1185. elif context & contexts.FAIL_ON_RBRACE:
  1186. if this == "}":
  1187. self._context |= contexts.FAIL_NEXT
  1188. return True
  1189. self._context ^= contexts.FAIL_ON_RBRACE
  1190. elif this == "{":
  1191. self._context |= contexts.FAIL_ON_LBRACE
  1192. elif this == "}":
  1193. self._context |= contexts.FAIL_ON_RBRACE
  1194. return True
  1195. def _parse(self, context=0, push=True):
  1196. """Parse the wikicode string, using *context* for when to stop."""
  1197. if push:
  1198. self._push(context)
  1199. while True:
  1200. this = self._read()
  1201. if self._context & contexts.UNSAFE:
  1202. if not self._verify_safe(this):
  1203. if self._context & contexts.DOUBLE:
  1204. self._pop()
  1205. self._fail_route()
  1206. if this not in self.MARKERS:
  1207. self._emit_text(this)
  1208. self._head += 1
  1209. continue
  1210. if this is self.END:
  1211. return self._handle_end()
  1212. nxt = self._read(1)
  1213. if this == nxt == "{":
  1214. if self._can_recurse():
  1215. self._parse_template_or_argument()
  1216. else:
  1217. self._emit_text("{")
  1218. elif this == "|" and self._context & contexts.TEMPLATE:
  1219. self._handle_template_param()
  1220. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  1221. self._handle_template_param_value()
  1222. elif this == nxt == "}" and self._context & contexts.TEMPLATE:
  1223. return self._handle_template_end()
  1224. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  1225. self._handle_argument_separator()
  1226. elif this == nxt == "}" and self._context & contexts.ARGUMENT:
  1227. if self._read(2) == "}":
  1228. return self._handle_argument_end()
  1229. self._emit_text("}")
  1230. elif this == nxt == "[" and self._can_recurse():
  1231. if not self._context & contexts.NO_WIKILINKS:
  1232. self._parse_wikilink()
  1233. else:
  1234. self._emit_text("[")
  1235. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  1236. self._handle_wikilink_separator()
  1237. elif this == nxt == "]" and self._context & contexts.WIKILINK:
  1238. return self._handle_wikilink_end()
  1239. elif this == "[":
  1240. self._parse_external_link(True)
  1241. elif this == ":" and self._read(-1) not in self.MARKERS:
  1242. self._parse_external_link(False)
  1243. elif this == "]" and self._context & contexts.EXT_LINK_TITLE:
  1244. return self._pop()
  1245. elif this == "=" and not self._global & contexts.GL_HEADING:
  1246. if self._read(-1) in ("\n", self.START):
  1247. self._parse_heading()
  1248. else:
  1249. self._emit_text("=")
  1250. elif this == "=" and self._context & contexts.HEADING:
  1251. return self._handle_heading_end()
  1252. elif this == "\n" and self._context & contexts.HEADING:
  1253. self._fail_route()
  1254. elif this == "&":
  1255. self._parse_entity()
  1256. elif this == "<" and nxt == "!":
  1257. if self._read(2) == self._read(3) == "-":
  1258. self._parse_comment()
  1259. else:
  1260. self._emit_text(this)
  1261. elif this == "<" and nxt == "/" and self._read(2) is not self.END:
  1262. if self._context & contexts.TAG_BODY:
  1263. self._handle_tag_open_close()
  1264. else:
  1265. self._handle_invalid_tag_start()
  1266. elif this == "<" and not self._context & contexts.TAG_CLOSE:
  1267. if self._can_recurse():
  1268. self._parse_tag()
  1269. else:
  1270. self._emit_text("<")
  1271. elif this == ">" and self._context & contexts.TAG_CLOSE:
  1272. return self._handle_tag_close_close()
  1273. elif this == nxt == "'" and not self._skip_style_tags:
  1274. result = self._parse_style()
  1275. if result is not None:
  1276. return result
  1277. elif self._read(-1) in ("\n", self.START) and this in ("#", "*", ";", ":"):
  1278. self._handle_list()
  1279. elif self._read(-1) in ("\n", self.START) and (
  1280. this == nxt == self._read(2) == self._read(3) == "-"):
  1281. self._handle_hr()
  1282. elif this in ("\n", ":") and self._context & contexts.DL_TERM:
  1283. self._handle_dl_term()
  1284. if this == "\n":
  1285. # Kill potential table contexts
  1286. self._context &= ~contexts.TABLE_CELL_LINE_CONTEXTS
  1287. # Start of table parsing
  1288. elif this == "{" and nxt == "|" and (
  1289. self._read(-1) in ("\n", self.START) or
  1290. (self._read(-2) in ("\n", self.START) and self._read(-1).isspace())):
  1291. if self._can_recurse():
  1292. self._parse_table()
  1293. else:
  1294. self._emit_text("{")
  1295. elif self._context & contexts.TABLE_OPEN:
  1296. if this == nxt == "|" and self._context & contexts.TABLE_TD_LINE:
  1297. if self._context & contexts.TABLE_CELL_OPEN:
  1298. return self._handle_table_cell_end()
  1299. self._handle_table_cell("||", "td", contexts.TABLE_TD_LINE)
  1300. elif this == nxt == "|" and self._context & contexts.TABLE_TH_LINE:
  1301. if self._context & contexts.TABLE_CELL_OPEN:
  1302. return self._handle_table_cell_end()
  1303. self._handle_table_cell("||", "th", contexts.TABLE_TH_LINE)
  1304. elif this == nxt == "!" and self._context & contexts.TABLE_TH_LINE:
  1305. if self._context & contexts.TABLE_CELL_OPEN:
  1306. return self._handle_table_cell_end()
  1307. self._handle_table_cell("!!", "th", contexts.TABLE_TH_LINE)
  1308. elif this == "|" and self._context & contexts.TABLE_CELL_STYLE:
  1309. return self._handle_table_cell_end(reset_for_style=True)
  1310. # on newline, clear out cell line contexts
  1311. elif this == "\n" and self._context & contexts.TABLE_CELL_LINE_CONTEXTS:
  1312. self._context &= ~contexts.TABLE_CELL_LINE_CONTEXTS
  1313. self._emit_text(this)
  1314. elif (self._read(-1) in ("\n", self.START) or
  1315. (self._read(-2) in ("\n", self.START) and self._read(-1).isspace())):
  1316. if this == "|" and nxt == "}":
  1317. if self._context & contexts.TABLE_CELL_OPEN:
  1318. return self._handle_table_cell_end()
  1319. if self._context & contexts.TABLE_ROW_OPEN:
  1320. return self._handle_table_row_end()
  1321. return self._handle_table_end()
  1322. if this == "|" and nxt == "-":
  1323. if self._context & contexts.TABLE_CELL_OPEN:
  1324. return self._handle_table_cell_end()
  1325. if self._context & contexts.TABLE_ROW_OPEN:
  1326. return self._handle_table_row_end()
  1327. self._handle_table_row()
  1328. elif this == "|":
  1329. if self._context & contexts.TABLE_CELL_OPEN:
  1330. return self._handle_table_cell_end()
  1331. self._handle_table_cell("|", "td", contexts.TABLE_TD_LINE)
  1332. elif this == "!":
  1333. if self._context & contexts.TABLE_CELL_OPEN:
  1334. return self._handle_table_cell_end()
  1335. self._handle_table_cell("!", "th", contexts.TABLE_TH_LINE)
  1336. else:
  1337. self._emit_text(this)
  1338. else:
  1339. self._emit_text(this)
  1340. else:
  1341. self._emit_text(this)
  1342. self._head += 1
  1343. def tokenize(self, text, context=0, skip_style_tags=False):
  1344. """Build a list of tokens from a string of wikicode and return it."""
  1345. split = self.regex.split(text)
  1346. self._text = [segment for segment in split if segment]
  1347. self._head = self._global = self._depth = 0
  1348. self._bad_routes = set()
  1349. self._skip_style_tags = skip_style_tags
  1350. try:
  1351. result = self._parse(context)
  1352. except BadRoute as exc: # pragma: no cover (untestable/exceptional case)
  1353. raise ParserError("Python tokenizer exited with BadRoute") from exc
  1354. if self._stacks: # pragma: no cover (untestable/exceptional case)
  1355. err = "Python tokenizer exited with non-empty token stack"
  1356. raise ParserError(err)
  1357. return result