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