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.
 
 
 
 

1151 lines
44 KiB

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