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.
 
 
 
 

1468 lines
58 KiB

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