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.
 
 
 
 

1469 lines
58 KiB

  1. # Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. import html.entities as htmlentities
  21. from math import log
  22. import re
  23. from . import contexts, tokens
  24. from .errors import ParserError
  25. from ..definitions import (get_html_tag, is_parsable, is_single,
  26. is_single_only, is_scheme)
  27. __all__ = ["Tokenizer"]
  28. class BadRoute(Exception):
  29. """Raised internally when the current tokenization route is invalid."""
  30. def __init__(self, context=0):
  31. super().__init__()
  32. self.context = context
  33. class _TagOpenData:
  34. """Stores data about an HTML open tag, like ``<ref name="foo">``."""
  35. CX_NAME = 1 << 0
  36. CX_ATTR_READY = 1 << 1
  37. CX_ATTR_NAME = 1 << 2
  38. CX_ATTR_VALUE = 1 << 3
  39. CX_QUOTED = 1 << 4
  40. CX_NOTE_SPACE = 1 << 5
  41. CX_NOTE_EQUALS = 1 << 6
  42. CX_NOTE_QUOTE = 1 << 7
  43. def __init__(self):
  44. self.context = self.CX_NAME
  45. self.padding_buffer = {"first": "", "before_eq": "", "after_eq": ""}
  46. self.quoter = None
  47. self.reset = 0
  48. class Tokenizer:
  49. """Creates a list of tokens from a string of wikicode."""
  50. USES_C = False
  51. START = object()
  52. END = object()
  53. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "'", "#", "*", ";",
  54. ":", "/", "-", "!", "\n", START, END]
  55. MAX_DEPTH = 40
  56. regex = re.compile(r"([{}\[\]<>|=&'#*;:/\\\"\-!\n])", flags=re.IGNORECASE)
  57. tag_splitter = re.compile(r"([\s\"\'\\]+)")
  58. def __init__(self):
  59. self._text = None
  60. self._head = 0
  61. self._stacks = []
  62. self._global = 0
  63. self._depth = 0
  64. self._bad_routes = set()
  65. self._skip_style_tags = False
  66. @property
  67. def _stack(self):
  68. """The current token stack."""
  69. return self._stacks[-1][0]
  70. @property
  71. def _context(self):
  72. """The current token context."""
  73. return self._stacks[-1][1]
  74. @_context.setter
  75. def _context(self, value):
  76. self._stacks[-1][1] = value
  77. @property
  78. def _textbuffer(self):
  79. """The current textbuffer."""
  80. return self._stacks[-1][2]
  81. @_textbuffer.setter
  82. def _textbuffer(self, value):
  83. self._stacks[-1][2] = value
  84. @property
  85. def _stack_ident(self):
  86. """An identifier for the current stack.
  87. This is based on the starting head position and context. Stacks with
  88. the same identifier are always parsed in the same way. This can be used
  89. to cache intermediate parsing info.
  90. """
  91. return self._stacks[-1][3]
  92. def _push(self, context=0):
  93. """Add a new token stack, context, and textbuffer to the list."""
  94. new_ident = (self._head, context)
  95. if new_ident in self._bad_routes:
  96. raise BadRoute(context)
  97. self._stacks.append([[], context, [], new_ident])
  98. self._depth += 1
  99. def _push_textbuffer(self):
  100. """Push the textbuffer onto the stack as a Text node and clear it."""
  101. if self._textbuffer:
  102. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  103. self._textbuffer = []
  104. def _pop(self, keep_context=False):
  105. """Pop the current stack/context/textbuffer, returning the stack.
  106. If *keep_context* is ``True``, then we will replace the underlying
  107. stack's context with the current stack's.
  108. """
  109. self._push_textbuffer()
  110. self._depth -= 1
  111. if keep_context:
  112. context = self._context
  113. stack = self._stacks.pop()[0]
  114. self._context = context
  115. return stack
  116. return self._stacks.pop()[0]
  117. def _can_recurse(self):
  118. """Return whether or not our max recursion depth has been exceeded."""
  119. return self._depth < self.MAX_DEPTH
  120. def _memoize_bad_route(self):
  121. """Remember that the current route (head + context at push) is invalid.
  122. This will be noticed when calling _push with the same head and context,
  123. and the route will be failed immediately.
  124. """
  125. self._bad_routes.add(self._stack_ident)
  126. def _fail_route(self):
  127. """Fail the current tokenization route.
  128. Discards the current stack/context/textbuffer and raises
  129. :exc:`.BadRoute`.
  130. """
  131. context = self._context
  132. self._memoize_bad_route()
  133. self._pop()
  134. raise BadRoute(context)
  135. def _emit(self, token):
  136. """Write a token to the end of the current token stack."""
  137. self._push_textbuffer()
  138. self._stack.append(token)
  139. def _emit_first(self, token):
  140. """Write a token to the beginning of the current token stack."""
  141. self._push_textbuffer()
  142. self._stack.insert(0, token)
  143. def _emit_text(self, text):
  144. """Write text to the current textbuffer."""
  145. self._textbuffer.append(text)
  146. def _emit_all(self, tokenlist):
  147. """Write a series of tokens to the current stack at once."""
  148. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  149. self._emit_text(tokenlist.pop(0).text)
  150. self._push_textbuffer()
  151. self._stack.extend(tokenlist)
  152. def _emit_text_then_stack(self, text):
  153. """Pop the current stack, write *text*, and then write the stack."""
  154. stack = self._pop()
  155. self._emit_text(text)
  156. if stack:
  157. self._emit_all(stack)
  158. self._head -= 1
  159. def _read(self, delta=0, wrap=False, strict=False):
  160. """Read the value at a relative point in the wikicode.
  161. The value is read from :attr:`self._head <_head>` plus the value of
  162. *delta* (which can be negative). If *wrap* is ``False``, we will not
  163. allow attempts to read from the end of the string if ``self._head +
  164. delta`` is negative. If *strict* is ``True``, the route will be failed
  165. (with :meth:`_fail_route`) if we try to read from past the end of the
  166. string; otherwise, :attr:`self.END <END>` is returned. If we try to
  167. read from before the start of the string, :attr:`self.START <START>` is
  168. returned.
  169. """
  170. index = self._head + delta
  171. if index < 0 and (not wrap or abs(index) > len(self._text)):
  172. return self.START
  173. try:
  174. return self._text[index]
  175. except IndexError:
  176. if strict:
  177. self._fail_route()
  178. return self.END
  179. def _parse_template(self, has_content):
  180. """Parse a template at the head of the wikicode string."""
  181. reset = self._head
  182. context = contexts.TEMPLATE_NAME
  183. if has_content:
  184. context |= contexts.HAS_TEMPLATE
  185. try:
  186. template = self._parse(context)
  187. except BadRoute:
  188. self._head = reset
  189. raise
  190. self._emit_first(tokens.TemplateOpen())
  191. self._emit_all(template)
  192. self._emit(tokens.TemplateClose())
  193. def _parse_argument(self):
  194. """Parse an argument at the head of the wikicode string."""
  195. reset = self._head
  196. try:
  197. argument = self._parse(contexts.ARGUMENT_NAME)
  198. except BadRoute:
  199. self._head = reset
  200. raise
  201. self._emit_first(tokens.ArgumentOpen())
  202. self._emit_all(argument)
  203. self._emit(tokens.ArgumentClose())
  204. def _parse_template_or_argument(self):
  205. """Parse a template or argument at the head of the wikicode string."""
  206. self._head += 2
  207. braces = 2
  208. while self._read() == "{":
  209. self._head += 1
  210. braces += 1
  211. has_content = False
  212. self._push()
  213. while braces:
  214. if braces == 1:
  215. return self._emit_text_then_stack("{")
  216. if braces == 2:
  217. try:
  218. self._parse_template(has_content)
  219. except BadRoute:
  220. return self._emit_text_then_stack("{{")
  221. break
  222. try:
  223. self._parse_argument()
  224. braces -= 3
  225. except BadRoute:
  226. try:
  227. self._parse_template(has_content)
  228. braces -= 2
  229. except BadRoute:
  230. return self._emit_text_then_stack("{" * braces)
  231. if braces:
  232. has_content = True
  233. self._head += 1
  234. self._emit_all(self._pop())
  235. if self._context & contexts.FAIL_NEXT:
  236. self._context ^= contexts.FAIL_NEXT
  237. def _handle_template_param(self):
  238. """Handle a template parameter at the head of the string."""
  239. if self._context & contexts.TEMPLATE_NAME:
  240. if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
  241. self._fail_route()
  242. self._context ^= contexts.TEMPLATE_NAME
  243. elif self._context & contexts.TEMPLATE_PARAM_VALUE:
  244. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  245. else:
  246. self._emit_all(self._pop())
  247. self._context |= contexts.TEMPLATE_PARAM_KEY
  248. self._emit(tokens.TemplateParamSeparator())
  249. self._push(self._context)
  250. def _handle_template_param_value(self):
  251. """Handle a template parameter's value at the head of the string."""
  252. self._emit_all(self._pop())
  253. self._context ^= contexts.TEMPLATE_PARAM_KEY
  254. self._context |= contexts.TEMPLATE_PARAM_VALUE
  255. self._emit(tokens.TemplateParamEquals())
  256. def _handle_template_end(self):
  257. """Handle the end of a template at the head of the string."""
  258. if self._context & contexts.TEMPLATE_NAME:
  259. if not self._context & (contexts.HAS_TEXT | contexts.HAS_TEMPLATE):
  260. self._fail_route()
  261. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  262. self._emit_all(self._pop())
  263. self._head += 1
  264. return self._pop()
  265. def _handle_argument_separator(self):
  266. """Handle the separator between an argument's name and default."""
  267. self._context ^= contexts.ARGUMENT_NAME
  268. self._context |= contexts.ARGUMENT_DEFAULT
  269. self._emit(tokens.ArgumentSeparator())
  270. def _handle_argument_end(self):
  271. """Handle the end of an argument at the head of the string."""
  272. self._head += 2
  273. return self._pop()
  274. def _parse_wikilink(self):
  275. """Parse an internal wikilink at the head of the wikicode string."""
  276. reset = self._head + 1
  277. self._head += 2
  278. try:
  279. # If the wikilink looks like an external link, parse it as such:
  280. link, _extra, _delta = self._really_parse_external_link(True)
  281. except BadRoute:
  282. self._head = reset + 1
  283. try:
  284. # Otherwise, actually parse it as a wikilink:
  285. wikilink = self._parse(contexts.WIKILINK_TITLE)
  286. except BadRoute:
  287. self._head = reset
  288. self._emit_text("[[")
  289. else:
  290. self._emit(tokens.WikilinkOpen())
  291. self._emit_all(wikilink)
  292. self._emit(tokens.WikilinkClose())
  293. else:
  294. if self._context & contexts.EXT_LINK_TITLE:
  295. # In this exceptional case, an external link that looks like a
  296. # wikilink inside of an external link is parsed as text:
  297. self._head = reset
  298. self._emit_text("[[")
  299. return
  300. self._emit_text("[")
  301. self._emit(tokens.ExternalLinkOpen(brackets=True))
  302. self._emit_all(link)
  303. self._emit(tokens.ExternalLinkClose())
  304. def _handle_wikilink_separator(self):
  305. """Handle the separator between a wikilink's title and its text."""
  306. self._context ^= contexts.WIKILINK_TITLE
  307. self._context |= contexts.WIKILINK_TEXT
  308. self._emit(tokens.WikilinkSeparator())
  309. def _handle_wikilink_end(self):
  310. """Handle the end of a wikilink at the head of the string."""
  311. self._head += 1
  312. return self._pop()
  313. def _parse_bracketed_uri_scheme(self):
  314. """Parse the URI scheme of a bracket-enclosed external link."""
  315. self._push(contexts.EXT_LINK_URI)
  316. if self._read() == self._read(1) == "/":
  317. self._emit_text("//")
  318. self._head += 2
  319. else:
  320. valid = "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, nxt):
  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 == nxt == "'" or
  391. (this == "|" and ctx & contexts.TEMPLATE) or
  392. (this == "=" and ctx & equal_sign_contexts) or
  393. (this == nxt == "}" and ctx & contexts.TEMPLATE) or
  394. (this == nxt == after == "}" and ctx & contexts.ARGUMENT))
  395. def _really_parse_external_link(self, brackets):
  396. """Really parse an external link."""
  397. if brackets:
  398. self._parse_bracketed_uri_scheme()
  399. invalid = ("\n", " ", "]")
  400. 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, nxt = 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 nxt == "!" 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, nxt):
  421. return self._pop(), tail, -1
  422. elif this is self.END or this == "\n":
  423. self._fail_route()
  424. elif this == nxt == "{" 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. nxt = self._read(1)
  636. if not self._can_recurse() or text not in self.MARKERS:
  637. self._emit_text(text)
  638. elif text == nxt == "{":
  639. self._parse_template_or_argument()
  640. elif text == nxt == "[":
  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, nxt = self._read(), self._read(1)
  725. if this is self.END:
  726. self._fail_route()
  727. elif this == "<" and nxt == "/":
  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, nxt = 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 nxt == ">" 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. self._emit_text("''")
  855. return
  856. else:
  857. self._emit_text("''")
  858. return
  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. if 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. return False
  879. def _parse_italics_and_bold(self):
  880. """Parse wiki-style italics and bold together (i.e., five ticks)."""
  881. reset = self._head
  882. try:
  883. stack = self._parse(contexts.STYLE_BOLD)
  884. except BadRoute:
  885. self._head = reset
  886. try:
  887. stack = self._parse(contexts.STYLE_ITALICS)
  888. except BadRoute:
  889. self._head = reset
  890. self._emit_text("'''''")
  891. else:
  892. reset = self._head
  893. try:
  894. stack2 = self._parse(contexts.STYLE_BOLD)
  895. except BadRoute:
  896. self._head = reset
  897. self._emit_text("'''")
  898. self._emit_style_tag("i", "''", stack)
  899. else:
  900. self._push()
  901. self._emit_style_tag("i", "''", stack)
  902. self._emit_all(stack2)
  903. self._emit_style_tag("b", "'''", self._pop())
  904. else:
  905. reset = self._head
  906. try:
  907. stack2 = self._parse(contexts.STYLE_ITALICS)
  908. except BadRoute:
  909. self._head = reset
  910. self._emit_text("''")
  911. self._emit_style_tag("b", "'''", stack)
  912. else:
  913. self._push()
  914. self._emit_style_tag("b", "'''", stack)
  915. self._emit_all(stack2)
  916. self._emit_style_tag("i", "''", self._pop())
  917. def _parse_style(self):
  918. """Parse wiki-style formatting (``''``/``'''`` for italics/bold)."""
  919. self._head += 2
  920. ticks = 2
  921. while self._read() == "'":
  922. self._head += 1
  923. ticks += 1
  924. italics = self._context & contexts.STYLE_ITALICS
  925. bold = self._context & contexts.STYLE_BOLD
  926. if ticks > 5:
  927. self._emit_text("'" * (ticks - 5))
  928. ticks = 5
  929. elif ticks == 4:
  930. self._emit_text("'")
  931. ticks = 3
  932. if (italics and ticks in (2, 5)) or (bold and ticks in (3, 5)):
  933. if ticks == 5:
  934. self._head -= 3 if italics else 2
  935. return self._pop()
  936. if not self._can_recurse():
  937. if ticks == 3:
  938. if self._context & contexts.STYLE_SECOND_PASS:
  939. self._emit_text("'")
  940. return self._pop()
  941. if self._context & contexts.STYLE_ITALICS:
  942. self._context |= contexts.STYLE_PASS_AGAIN
  943. self._emit_text("'" * ticks)
  944. elif ticks == 2:
  945. self._parse_italics()
  946. elif ticks == 3:
  947. if self._parse_bold():
  948. return self._pop()
  949. else: # ticks == 5
  950. self._parse_italics_and_bold()
  951. self._head -= 1
  952. def _handle_list_marker(self):
  953. """Handle a list marker at the head (``#``, ``*``, ``;``, ``:``)."""
  954. markup = self._read()
  955. if markup == ";":
  956. self._context |= contexts.DL_TERM
  957. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  958. self._emit_text(get_html_tag(markup))
  959. self._emit(tokens.TagCloseSelfclose())
  960. def _handle_list(self):
  961. """Handle a wiki-style list (``#``, ``*``, ``;``, ``:``)."""
  962. self._handle_list_marker()
  963. while self._read(1) in ("#", "*", ";", ":"):
  964. self._head += 1
  965. self._handle_list_marker()
  966. def _handle_hr(self):
  967. """Handle a wiki-style horizontal rule (``----``) in the string."""
  968. length = 4
  969. self._head += 3
  970. while self._read(1) == "-":
  971. length += 1
  972. self._head += 1
  973. self._emit(tokens.TagOpenOpen(wiki_markup="-" * length))
  974. self._emit_text("hr")
  975. self._emit(tokens.TagCloseSelfclose())
  976. def _handle_dl_term(self):
  977. """Handle the term in a description list (``foo`` in ``;foo:bar``)."""
  978. self._context ^= contexts.DL_TERM
  979. if self._read() == ":":
  980. self._handle_list_marker()
  981. else:
  982. self._emit_text("\n")
  983. def _emit_table_tag(self, open_open_markup, tag, style, padding,
  984. close_open_markup, contents, open_close_markup):
  985. """Emit a table tag."""
  986. self._emit(tokens.TagOpenOpen(wiki_markup=open_open_markup))
  987. self._emit_text(tag)
  988. if style:
  989. self._emit_all(style)
  990. if close_open_markup:
  991. self._emit(tokens.TagCloseOpen(wiki_markup=close_open_markup,
  992. padding=padding))
  993. else:
  994. self._emit(tokens.TagCloseOpen(padding=padding))
  995. if contents:
  996. self._emit_all(contents)
  997. self._emit(tokens.TagOpenClose(wiki_markup=open_close_markup))
  998. self._emit_text(tag)
  999. self._emit(tokens.TagCloseClose())
  1000. def _handle_table_style(self, end_token):
  1001. """Handle style attributes for a table until ``end_token``."""
  1002. data = _TagOpenData()
  1003. data.context = _TagOpenData.CX_ATTR_READY
  1004. while True:
  1005. this = self._read()
  1006. can_exit = (not data.context & data.CX_QUOTED or
  1007. data.context & data.CX_NOTE_SPACE)
  1008. if this == end_token and can_exit:
  1009. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  1010. self._push_tag_buffer(data)
  1011. if this.isspace():
  1012. data.padding_buffer["first"] += this
  1013. return data.padding_buffer["first"]
  1014. if this is self.END or this == end_token:
  1015. if self._context & contexts.TAG_ATTR:
  1016. if data.context & data.CX_QUOTED:
  1017. # Unclosed attribute quote: reset, don't die
  1018. data.context = data.CX_ATTR_VALUE
  1019. self._memoize_bad_route()
  1020. self._pop()
  1021. self._head = data.reset
  1022. continue
  1023. self._pop()
  1024. self._fail_route()
  1025. else:
  1026. self._handle_tag_data(data, this)
  1027. self._head += 1
  1028. def _parse_table(self):
  1029. """Parse a wikicode table by starting with the first line."""
  1030. reset = self._head
  1031. self._head += 2
  1032. try:
  1033. self._push(contexts.TABLE_OPEN)
  1034. padding = self._handle_table_style("\n")
  1035. except BadRoute:
  1036. self._head = reset
  1037. self._emit_text("{")
  1038. return
  1039. style = self._pop()
  1040. self._head += 1
  1041. restore_point = self._stack_ident
  1042. try:
  1043. table = self._parse(contexts.TABLE_OPEN)
  1044. except BadRoute:
  1045. while self._stack_ident != restore_point:
  1046. self._memoize_bad_route()
  1047. self._pop()
  1048. self._head = reset
  1049. self._emit_text("{")
  1050. return
  1051. self._emit_table_tag("{|", "table", style, padding, None, table, "|}")
  1052. # Offset displacement done by _parse():
  1053. self._head -= 1
  1054. def _handle_table_row(self):
  1055. """Parse as style until end of the line, then continue."""
  1056. self._head += 2
  1057. if not self._can_recurse():
  1058. self._emit_text("|-")
  1059. self._head -= 1
  1060. return
  1061. self._push(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
  1062. padding = self._handle_table_style("\n")
  1063. style = self._pop()
  1064. # Don't parse the style separator:
  1065. self._head += 1
  1066. row = self._parse(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
  1067. self._emit_table_tag("|-", "tr", style, padding, None, row, "")
  1068. # Offset displacement done by parse():
  1069. self._head -= 1
  1070. def _handle_table_cell(self, markup, tag, line_context):
  1071. """Parse as normal syntax unless we hit a style marker, then parse
  1072. style as HTML attributes and the remainder as normal syntax."""
  1073. old_context = self._context
  1074. padding, style = "", None
  1075. self._head += len(markup)
  1076. reset = self._head
  1077. if not self._can_recurse():
  1078. self._emit_text(markup)
  1079. self._head -= 1
  1080. return
  1081. cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1082. line_context | contexts.TABLE_CELL_STYLE)
  1083. cell_context = self._context
  1084. self._context = old_context
  1085. reset_for_style = cell_context & contexts.TABLE_CELL_STYLE
  1086. if reset_for_style:
  1087. self._head = reset
  1088. self._push(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1089. line_context)
  1090. padding = self._handle_table_style("|")
  1091. style = self._pop()
  1092. # Don't parse the style separator:
  1093. self._head += 1
  1094. cell = self._parse(contexts.TABLE_OPEN | contexts.TABLE_CELL_OPEN |
  1095. line_context)
  1096. cell_context = self._context
  1097. self._context = old_context
  1098. close_open_markup = "|" if reset_for_style else None
  1099. self._emit_table_tag(markup, tag, style, padding, close_open_markup,
  1100. cell, "")
  1101. # Keep header/cell line contexts:
  1102. self._context |= cell_context & (contexts.TABLE_TH_LINE |
  1103. contexts.TABLE_TD_LINE)
  1104. # Offset displacement done by parse():
  1105. self._head -= 1
  1106. def _handle_table_cell_end(self, reset_for_style=False):
  1107. """Returns the current context, with the TABLE_CELL_STYLE flag set if
  1108. it is necessary to reset and parse style attributes."""
  1109. if reset_for_style:
  1110. self._context |= contexts.TABLE_CELL_STYLE
  1111. else:
  1112. self._context &= ~contexts.TABLE_CELL_STYLE
  1113. return self._pop(keep_context=True)
  1114. def _handle_table_row_end(self):
  1115. """Return the stack in order to handle the table row end."""
  1116. return self._pop()
  1117. def _handle_table_end(self):
  1118. """Return the stack in order to handle the table end."""
  1119. self._head += 2
  1120. return self._pop()
  1121. def _handle_end(self):
  1122. """Handle the end of the stream of wikitext."""
  1123. if self._context & contexts.FAIL:
  1124. if self._context & contexts.TAG_BODY:
  1125. if is_single(self._stack[1].text):
  1126. return self._handle_single_tag_end()
  1127. if self._context & contexts.TABLE_CELL_OPEN:
  1128. self._pop()
  1129. if self._context & contexts.DOUBLE:
  1130. self._pop()
  1131. self._fail_route()
  1132. return self._pop()
  1133. def _verify_safe(self, this):
  1134. """Make sure we are not trying to write an invalid character."""
  1135. context = self._context
  1136. if context & contexts.FAIL_NEXT:
  1137. return False
  1138. if context & contexts.WIKILINK_TITLE:
  1139. if this in ("]", "{"):
  1140. self._context |= contexts.FAIL_NEXT
  1141. elif this in ("\n", "[", "}", ">"):
  1142. return False
  1143. elif this == "<":
  1144. if self._read(1) == "!":
  1145. self._context |= contexts.FAIL_NEXT
  1146. else:
  1147. return False
  1148. return True
  1149. if context & contexts.EXT_LINK_TITLE:
  1150. return this != "\n"
  1151. if context & contexts.TEMPLATE_NAME:
  1152. if this == "{":
  1153. self._context |= contexts.HAS_TEMPLATE | contexts.FAIL_NEXT
  1154. return True
  1155. if this == "}" or (this == "<" and self._read(1) == "!"):
  1156. self._context |= contexts.FAIL_NEXT
  1157. return True
  1158. if this in ("[", "]", "<", ">"):
  1159. return False
  1160. if this == "|":
  1161. return True
  1162. if context & contexts.HAS_TEXT:
  1163. if context & contexts.FAIL_ON_TEXT:
  1164. if this is self.END or not this.isspace():
  1165. return False
  1166. elif this == "\n":
  1167. self._context |= contexts.FAIL_ON_TEXT
  1168. elif this is self.END or not this.isspace():
  1169. self._context |= contexts.HAS_TEXT
  1170. return True
  1171. if context & contexts.TAG_CLOSE:
  1172. return this != "<"
  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. nxt = self._read(1)
  1212. if this == nxt == "{":
  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 == nxt == "}" 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 == nxt == "}" and self._context & contexts.ARGUMENT:
  1226. if self._read(2) == "}":
  1227. return self._handle_argument_end()
  1228. self._emit_text("}")
  1229. elif this == nxt == "[" and self._can_recurse():
  1230. if not self._context & contexts.NO_WIKILINKS:
  1231. self._parse_wikilink()
  1232. else:
  1233. self._emit_text("[")
  1234. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  1235. self._handle_wikilink_separator()
  1236. elif this == nxt == "]" and self._context & contexts.WIKILINK:
  1237. return self._handle_wikilink_end()
  1238. elif this == "[":
  1239. self._parse_external_link(True)
  1240. elif this == ":" and self._read(-1) not in self.MARKERS:
  1241. self._parse_external_link(False)
  1242. elif this == "]" and self._context & contexts.EXT_LINK_TITLE:
  1243. return self._pop()
  1244. elif this == "=" and not self._global & contexts.GL_HEADING:
  1245. if self._read(-1) in ("\n", self.START):
  1246. self._parse_heading()
  1247. else:
  1248. self._emit_text("=")
  1249. elif this == "=" and self._context & contexts.HEADING:
  1250. return self._handle_heading_end()
  1251. elif this == "\n" and self._context & contexts.HEADING:
  1252. self._fail_route()
  1253. elif this == "&":
  1254. self._parse_entity()
  1255. elif this == "<" and nxt == "!":
  1256. if self._read(2) == self._read(3) == "-":
  1257. self._parse_comment()
  1258. else:
  1259. self._emit_text(this)
  1260. elif this == "<" and nxt == "/" and self._read(2) is not self.END:
  1261. if self._context & contexts.TAG_BODY:
  1262. self._handle_tag_open_close()
  1263. else:
  1264. self._handle_invalid_tag_start()
  1265. elif this == "<" and not self._context & contexts.TAG_CLOSE:
  1266. if self._can_recurse():
  1267. self._parse_tag()
  1268. else:
  1269. self._emit_text("<")
  1270. elif this == ">" and self._context & contexts.TAG_CLOSE:
  1271. return self._handle_tag_close_close()
  1272. elif this == nxt == "'" and not self._skip_style_tags:
  1273. result = self._parse_style()
  1274. if result is not None:
  1275. return result
  1276. elif self._read(-1) in ("\n", self.START) and this in ("#", "*", ";", ":"):
  1277. self._handle_list()
  1278. elif self._read(-1) in ("\n", self.START) and (
  1279. this == nxt == self._read(2) == self._read(3) == "-"):
  1280. self._handle_hr()
  1281. elif this in ("\n", ":") and self._context & contexts.DL_TERM:
  1282. self._handle_dl_term()
  1283. if this == "\n":
  1284. # Kill potential table contexts
  1285. self._context &= ~contexts.TABLE_CELL_LINE_CONTEXTS
  1286. # Start of table parsing
  1287. elif this == "{" and nxt == "|" and (
  1288. self._read(-1) in ("\n", self.START) or
  1289. (self._read(-2) in ("\n", self.START) and self._read(-1).isspace())):
  1290. if self._can_recurse():
  1291. self._parse_table()
  1292. else:
  1293. self._emit_text("{")
  1294. elif self._context & contexts.TABLE_OPEN:
  1295. if this == nxt == "|" and self._context & contexts.TABLE_TD_LINE:
  1296. if self._context & contexts.TABLE_CELL_OPEN:
  1297. return self._handle_table_cell_end()
  1298. self._handle_table_cell("||", "td", contexts.TABLE_TD_LINE)
  1299. elif this == nxt == "|" and self._context & contexts.TABLE_TH_LINE:
  1300. if self._context & contexts.TABLE_CELL_OPEN:
  1301. return self._handle_table_cell_end()
  1302. self._handle_table_cell("||", "th", contexts.TABLE_TH_LINE)
  1303. elif this == nxt == "!" and self._context & contexts.TABLE_TH_LINE:
  1304. if self._context & contexts.TABLE_CELL_OPEN:
  1305. return self._handle_table_cell_end()
  1306. self._handle_table_cell("!!", "th", contexts.TABLE_TH_LINE)
  1307. elif this == "|" and self._context & contexts.TABLE_CELL_STYLE:
  1308. return self._handle_table_cell_end(reset_for_style=True)
  1309. # on newline, clear out cell line contexts
  1310. elif this == "\n" and self._context & contexts.TABLE_CELL_LINE_CONTEXTS:
  1311. self._context &= ~contexts.TABLE_CELL_LINE_CONTEXTS
  1312. self._emit_text(this)
  1313. elif (self._read(-1) in ("\n", self.START) or
  1314. (self._read(-2) in ("\n", self.START) and self._read(-1).isspace())):
  1315. if this == "|" and nxt == "}":
  1316. if self._context & contexts.TABLE_CELL_OPEN:
  1317. return self._handle_table_cell_end()
  1318. if self._context & contexts.TABLE_ROW_OPEN:
  1319. return self._handle_table_row_end()
  1320. return self._handle_table_end()
  1321. if this == "|" and nxt == "-":
  1322. if self._context & contexts.TABLE_CELL_OPEN:
  1323. return self._handle_table_cell_end()
  1324. if self._context & contexts.TABLE_ROW_OPEN:
  1325. return self._handle_table_row_end()
  1326. self._handle_table_row()
  1327. elif this == "|":
  1328. if self._context & contexts.TABLE_CELL_OPEN:
  1329. return self._handle_table_cell_end()
  1330. self._handle_table_cell("|", "td", contexts.TABLE_TD_LINE)
  1331. elif this == "!":
  1332. if self._context & contexts.TABLE_CELL_OPEN:
  1333. return self._handle_table_cell_end()
  1334. self._handle_table_cell("!", "th", contexts.TABLE_TH_LINE)
  1335. else:
  1336. self._emit_text(this)
  1337. else:
  1338. self._emit_text(this)
  1339. else:
  1340. self._emit_text(this)
  1341. self._head += 1
  1342. def tokenize(self, text, context=0, skip_style_tags=False):
  1343. """Build a list of tokens from a string of wikicode and return it."""
  1344. split = self.regex.split(text)
  1345. self._text = [segment for segment in split if segment]
  1346. self._head = self._global = self._depth = 0
  1347. self._bad_routes = set()
  1348. self._skip_style_tags = skip_style_tags
  1349. try:
  1350. result = self._parse(context)
  1351. except BadRoute as exc: # pragma: no cover (untestable/exceptional case)
  1352. raise ParserError("Python tokenizer exited with BadRoute") from exc
  1353. if self._stacks: # pragma: no cover (untestable/exceptional case)
  1354. err = "Python tokenizer exited with non-empty token stack"
  1355. raise ParserError(err)
  1356. return result