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.
 
 
 
 

1153 lines
44 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 Ben Kurtovic <ben.kurtovic@verizon.net>
  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(self._context | 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. return (this is self.END or this in ("\n", "[", "]") or
  346. this == "|" and ctx & contexts.TEMPLATE or
  347. this == "=" and ctx & contexts.TEMPLATE_PARAM_KEY or
  348. this == next == "}" and ctx & contexts.TEMPLATE or
  349. this == next == after == "}" and ctx & contexts.ARGUMENT or
  350. this == "=" and ctx & contexts.HEADING or
  351. this == "<" and next == "/" and after is not self.END or
  352. this == "<" and next != "!" and not ctx & contexts.TAG_CLOSE or
  353. this == ">" and ctx & contexts.TAG_CLOSE or
  354. this == next == "'")
  355. def _really_parse_external_link(self, brackets):
  356. """Really parse an external link."""
  357. if brackets:
  358. self._parse_bracketed_uri_scheme()
  359. invalid = ("\n", " ", "]")
  360. else:
  361. self._parse_free_uri_scheme()
  362. invalid = ("\n", " ", "[", "]")
  363. punct = tuple(",;\.:!?)")
  364. if self._read() is self.END or self._read()[0] in invalid:
  365. self._fail_route()
  366. tail = ""
  367. while True:
  368. this, next = self._read(), self._read(1)
  369. if not brackets and self._is_free_link_end(this, next):
  370. return self._pop(), tail, -1
  371. elif this is self.END or this == "\n":
  372. self._fail_route()
  373. elif this == next == "{" and self._can_recurse():
  374. if tail:
  375. self._emit_text(tail)
  376. tail = ""
  377. self._parse_template_or_argument()
  378. elif this == "]":
  379. return self._pop(), tail, 0
  380. elif this == "&":
  381. if tail:
  382. self._emit_text(tail)
  383. tail = ""
  384. self._parse_entity()
  385. elif (this == "<" and next == "!" and self._read(2) ==
  386. self._read(3) == "-"):
  387. if tail:
  388. self._emit_text(tail)
  389. tail = ""
  390. self._parse_comment()
  391. elif " " in this:
  392. before, after = this.split(" ", 1)
  393. if brackets:
  394. self._emit_text(before)
  395. self._emit(tokens.ExternalLinkSeparator())
  396. if after:
  397. self._emit_text(after)
  398. self._context ^= contexts.EXT_LINK_URI
  399. self._context |= contexts.EXT_LINK_TITLE
  400. self._head += 1
  401. return self._parse(push=False), None, 0
  402. punct, tail = self._handle_free_link_text(punct, tail, before)
  403. return self._pop(), tail + " " + after, 0
  404. elif not brackets:
  405. punct, tail = self._handle_free_link_text(punct, tail, this)
  406. else:
  407. self._emit_text(this)
  408. self._head += 1
  409. def _remove_uri_scheme_from_textbuffer(self, scheme):
  410. """Remove the URI scheme of a new external link from the textbuffer."""
  411. length = len(scheme)
  412. while length:
  413. if length < len(self._textbuffer[-1]):
  414. self._textbuffer[-1] = self._textbuffer[-1][:-length]
  415. break
  416. length -= len(self._textbuffer[-1])
  417. self._textbuffer.pop()
  418. def _parse_external_link(self, brackets):
  419. """Parse an external link at the head of the wikicode string."""
  420. reset = self._head
  421. self._head += 1
  422. try:
  423. bad_context = self._context & contexts.INVALID_LINK
  424. if bad_context or not self._can_recurse():
  425. raise BadRoute()
  426. link, extra, delta = self._really_parse_external_link(brackets)
  427. except BadRoute:
  428. self._head = reset
  429. if not brackets and self._context & contexts.DL_TERM:
  430. self._handle_dl_term()
  431. else:
  432. self._emit_text(self._read())
  433. else:
  434. if not brackets:
  435. scheme = link[0].text.split(":", 1)[0]
  436. self._remove_uri_scheme_from_textbuffer(scheme)
  437. self._emit(tokens.ExternalLinkOpen(brackets=brackets))
  438. self._emit_all(link)
  439. self._emit(tokens.ExternalLinkClose())
  440. self._head += delta
  441. if extra:
  442. self._emit_text(extra)
  443. def _parse_heading(self):
  444. """Parse a section heading at the head of the wikicode string."""
  445. self._global |= contexts.GL_HEADING
  446. reset = self._head
  447. self._head += 1
  448. best = 1
  449. while self._read() == "=":
  450. best += 1
  451. self._head += 1
  452. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  453. try:
  454. title, level = self._parse(context)
  455. except BadRoute:
  456. self._head = reset + best - 1
  457. self._emit_text("=" * best)
  458. else:
  459. self._emit(tokens.HeadingStart(level=level))
  460. if level < best:
  461. self._emit_text("=" * (best - level))
  462. self._emit_all(title)
  463. self._emit(tokens.HeadingEnd())
  464. finally:
  465. self._global ^= contexts.GL_HEADING
  466. def _handle_heading_end(self):
  467. """Handle the end of a section heading at the head of the string."""
  468. reset = self._head
  469. self._head += 1
  470. best = 1
  471. while self._read() == "=":
  472. best += 1
  473. self._head += 1
  474. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  475. level = min(current, min(best, 6))
  476. try: # Try to check for a heading closure after this one
  477. after, after_level = self._parse(self._context)
  478. except BadRoute:
  479. if level < best:
  480. self._emit_text("=" * (best - level))
  481. self._head = reset + best - 1
  482. return self._pop(), level
  483. else: # Found another closure
  484. self._emit_text("=" * best)
  485. self._emit_all(after)
  486. return self._pop(), after_level
  487. def _really_parse_entity(self):
  488. """Actually parse an HTML entity and ensure that it is valid."""
  489. self._emit(tokens.HTMLEntityStart())
  490. self._head += 1
  491. this = self._read(strict=True)
  492. if this == "#":
  493. numeric = True
  494. self._emit(tokens.HTMLEntityNumeric())
  495. self._head += 1
  496. this = self._read(strict=True)
  497. if this[0].lower() == "x":
  498. hexadecimal = True
  499. self._emit(tokens.HTMLEntityHex(char=this[0]))
  500. this = this[1:]
  501. if not this:
  502. self._fail_route()
  503. else:
  504. hexadecimal = False
  505. else:
  506. numeric = hexadecimal = False
  507. valid = "0123456789abcdefABCDEF" if hexadecimal else "0123456789"
  508. if not numeric and not hexadecimal:
  509. valid += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  510. if not all([char in valid for char in this]):
  511. self._fail_route()
  512. self._head += 1
  513. if self._read() != ";":
  514. self._fail_route()
  515. if numeric:
  516. test = int(this, 16) if hexadecimal else int(this)
  517. if test < 1 or test > 0x10FFFF:
  518. self._fail_route()
  519. else:
  520. if this not in htmlentities.entitydefs:
  521. self._fail_route()
  522. self._emit(tokens.Text(text=this))
  523. self._emit(tokens.HTMLEntityEnd())
  524. def _parse_entity(self):
  525. """Parse an HTML entity at the head of the wikicode string."""
  526. reset = self._head
  527. self._push()
  528. try:
  529. self._really_parse_entity()
  530. except BadRoute:
  531. self._head = reset
  532. self._emit_text(self._read())
  533. else:
  534. self._emit_all(self._pop())
  535. def _parse_comment(self):
  536. """Parse an HTML comment at the head of the wikicode string."""
  537. self._head += 4
  538. reset = self._head - 1
  539. self._push()
  540. while True:
  541. this = self._read()
  542. if this == self.END:
  543. self._pop()
  544. self._head = reset
  545. self._emit_text("<!--")
  546. return
  547. if this == self._read(1) == "-" and self._read(2) == ">":
  548. self._emit_first(tokens.CommentStart())
  549. self._emit(tokens.CommentEnd())
  550. self._emit_all(self._pop())
  551. self._head += 2
  552. return
  553. self._emit_text(this)
  554. self._head += 1
  555. def _push_tag_buffer(self, data):
  556. """Write a pending tag attribute from *data* to the stack."""
  557. if data.context & data.CX_QUOTED:
  558. self._emit_first(tokens.TagAttrQuote())
  559. self._emit_all(self._pop())
  560. buf = data.padding_buffer
  561. self._emit_first(tokens.TagAttrStart(pad_first=buf["first"],
  562. pad_before_eq=buf["before_eq"], pad_after_eq=buf["after_eq"]))
  563. self._emit_all(self._pop())
  564. data.padding_buffer = {key: "" for key in data.padding_buffer}
  565. def _handle_tag_space(self, data, text):
  566. """Handle whitespace (*text*) inside of an HTML open tag."""
  567. ctx = data.context
  568. end_of_value = ctx & data.CX_ATTR_VALUE and not ctx & (data.CX_QUOTED | data.CX_NOTE_QUOTE)
  569. if end_of_value or (ctx & data.CX_QUOTED and ctx & data.CX_NOTE_SPACE):
  570. self._push_tag_buffer(data)
  571. data.context = data.CX_ATTR_READY
  572. elif ctx & data.CX_NOTE_SPACE:
  573. data.context = data.CX_ATTR_READY
  574. elif ctx & data.CX_ATTR_NAME:
  575. data.context |= data.CX_NOTE_EQUALS
  576. data.padding_buffer["before_eq"] += text
  577. if ctx & data.CX_QUOTED and not ctx & data.CX_NOTE_SPACE:
  578. self._emit_text(text)
  579. elif data.context & data.CX_ATTR_READY:
  580. data.padding_buffer["first"] += text
  581. elif data.context & data.CX_ATTR_VALUE:
  582. data.padding_buffer["after_eq"] += text
  583. def _handle_tag_text(self, text):
  584. """Handle regular *text* inside of an HTML open tag."""
  585. next = self._read(1)
  586. if not self._can_recurse() or text not in self.MARKERS:
  587. self._emit_text(text)
  588. elif text == next == "{":
  589. self._parse_template_or_argument()
  590. elif text == next == "[":
  591. self._parse_wikilink()
  592. elif text == "<":
  593. self._parse_tag()
  594. else:
  595. self._emit_text(text)
  596. def _handle_tag_data(self, data, text):
  597. """Handle all sorts of *text* data inside of an HTML open tag."""
  598. for chunk in self.tag_splitter.split(text):
  599. if not chunk:
  600. continue
  601. if data.context & data.CX_NAME:
  602. if chunk in self.MARKERS or chunk.isspace():
  603. self._fail_route() # Tags must start with text, not spaces
  604. data.context = data.CX_NOTE_SPACE
  605. elif chunk.isspace():
  606. self._handle_tag_space(data, chunk)
  607. continue
  608. elif data.context & data.CX_NOTE_SPACE:
  609. if data.context & data.CX_QUOTED:
  610. data.context = data.CX_ATTR_VALUE
  611. self._pop()
  612. self._head = data.reset - 1 # Will be auto-incremented
  613. return # Break early
  614. self._fail_route()
  615. elif data.context & data.CX_ATTR_READY:
  616. data.context = data.CX_ATTR_NAME
  617. self._push(contexts.TAG_ATTR)
  618. elif data.context & data.CX_ATTR_NAME:
  619. if chunk == "=":
  620. data.context = data.CX_ATTR_VALUE | data.CX_NOTE_QUOTE
  621. self._emit(tokens.TagAttrEquals())
  622. continue
  623. if data.context & data.CX_NOTE_EQUALS:
  624. self._push_tag_buffer(data)
  625. data.context = data.CX_ATTR_NAME
  626. self._push(contexts.TAG_ATTR)
  627. elif data.context & data.CX_ATTR_VALUE:
  628. escaped = self._read(-1) == "\\" and self._read(-2) != "\\"
  629. if data.context & data.CX_NOTE_QUOTE:
  630. data.context ^= data.CX_NOTE_QUOTE
  631. if chunk == '"' and not escaped:
  632. data.context |= data.CX_QUOTED
  633. self._push(self._context)
  634. data.reset = self._head
  635. continue
  636. elif data.context & data.CX_QUOTED:
  637. if chunk == '"' and not escaped:
  638. data.context |= data.CX_NOTE_SPACE
  639. continue
  640. self._handle_tag_text(chunk)
  641. def _handle_tag_close_open(self, data, token):
  642. """Handle the closing of a open tag (``<foo>``)."""
  643. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  644. self._push_tag_buffer(data)
  645. self._emit(token(padding=data.padding_buffer["first"]))
  646. self._head += 1
  647. def _handle_tag_open_close(self):
  648. """Handle the opening of a closing tag (``</foo>``)."""
  649. self._emit(tokens.TagOpenClose())
  650. self._push(contexts.TAG_CLOSE)
  651. self._head += 1
  652. def _handle_tag_close_close(self):
  653. """Handle the ending of a closing tag (``</foo>``)."""
  654. strip = lambda tok: tok.text.rstrip().lower()
  655. closing = self._pop()
  656. if len(closing) != 1 or (not isinstance(closing[0], tokens.Text) or
  657. strip(closing[0]) != strip(self._stack[1])):
  658. self._fail_route()
  659. self._emit_all(closing)
  660. self._emit(tokens.TagCloseClose())
  661. return self._pop()
  662. def _handle_blacklisted_tag(self):
  663. """Handle the body of an HTML tag that is parser-blacklisted."""
  664. while True:
  665. this, next = self._read(), self._read(1)
  666. if this is self.END:
  667. self._fail_route()
  668. elif this == "<" and next == "/":
  669. self._handle_tag_open_close()
  670. self._head += 1
  671. return self._parse(push=False)
  672. elif this == "&":
  673. self._parse_entity()
  674. else:
  675. self._emit_text(this)
  676. self._head += 1
  677. def _handle_single_only_tag_end(self):
  678. """Handle the end of an implicitly closing single-only HTML tag."""
  679. padding = self._stack.pop().padding
  680. self._emit(tokens.TagCloseSelfclose(padding=padding, implicit=True))
  681. self._head -= 1 # Offset displacement done by _handle_tag_close_open
  682. return self._pop()
  683. def _handle_single_tag_end(self):
  684. """Handle the stream end when inside a single-supporting HTML tag."""
  685. gen = enumerate(self._stack)
  686. index = next(i for i, t in gen if isinstance(t, tokens.TagCloseOpen))
  687. padding = self._stack[index].padding
  688. token = tokens.TagCloseSelfclose(padding=padding, implicit=True)
  689. self._stack[index] = token
  690. return self._pop()
  691. def _really_parse_tag(self):
  692. """Actually parse an HTML tag, starting with the open (``<foo>``)."""
  693. data = _TagOpenData()
  694. self._push(contexts.TAG_OPEN)
  695. self._emit(tokens.TagOpenOpen())
  696. while True:
  697. this, next = self._read(), self._read(1)
  698. can_exit = (not data.context & (data.CX_QUOTED | data.CX_NAME) or
  699. data.context & data.CX_NOTE_SPACE)
  700. if this is self.END:
  701. if self._context & contexts.TAG_ATTR:
  702. if data.context & data.CX_QUOTED:
  703. # Unclosed attribute quote: reset, don't die
  704. data.context = data.CX_ATTR_VALUE
  705. self._pop()
  706. self._head = data.reset
  707. continue
  708. self._pop()
  709. self._fail_route()
  710. elif this == ">" and can_exit:
  711. self._handle_tag_close_open(data, tokens.TagCloseOpen)
  712. self._context = contexts.TAG_BODY
  713. if is_single_only(self._stack[1].text):
  714. return self._handle_single_only_tag_end()
  715. if is_parsable(self._stack[1].text):
  716. return self._parse(push=False)
  717. return self._handle_blacklisted_tag()
  718. elif this == "/" and next == ">" and can_exit:
  719. self._handle_tag_close_open(data, tokens.TagCloseSelfclose)
  720. return self._pop()
  721. else:
  722. self._handle_tag_data(data, this)
  723. self._head += 1
  724. def _handle_invalid_tag_start(self):
  725. """Handle the (possible) start of an implicitly closing single tag."""
  726. reset = self._head + 1
  727. self._head += 2
  728. try:
  729. if not is_single_only(self.tag_splitter.split(self._read())[0]):
  730. raise BadRoute()
  731. tag = self._really_parse_tag()
  732. except BadRoute:
  733. self._head = reset
  734. self._emit_text("</")
  735. else:
  736. tag[0].invalid = True # Set flag of TagOpenOpen
  737. self._emit_all(tag)
  738. def _parse_tag(self):
  739. """Parse an HTML tag at the head of the wikicode string."""
  740. reset = self._head
  741. self._head += 1
  742. try:
  743. tag = self._really_parse_tag()
  744. except BadRoute:
  745. self._head = reset
  746. self._emit_text("<")
  747. else:
  748. self._emit_all(tag)
  749. def _emit_style_tag(self, tag, markup, body):
  750. """Write the body of a tag and the tokens that should surround it."""
  751. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  752. self._emit_text(tag)
  753. self._emit(tokens.TagCloseOpen())
  754. self._emit_all(body)
  755. self._emit(tokens.TagOpenClose())
  756. self._emit_text(tag)
  757. self._emit(tokens.TagCloseClose())
  758. def _parse_italics(self):
  759. """Parse wiki-style italics."""
  760. reset = self._head
  761. try:
  762. stack = self._parse(contexts.STYLE_ITALICS)
  763. except BadRoute as route:
  764. self._head = reset
  765. if route.context & contexts.STYLE_PASS_AGAIN:
  766. new_ctx = contexts.STYLE_ITALICS | contexts.STYLE_SECOND_PASS
  767. stack = self._parse(new_ctx)
  768. else:
  769. return self._emit_text("''")
  770. self._emit_style_tag("i", "''", stack)
  771. def _parse_bold(self):
  772. """Parse wiki-style bold."""
  773. reset = self._head
  774. try:
  775. stack = self._parse(contexts.STYLE_BOLD)
  776. except BadRoute:
  777. self._head = reset
  778. if self._context & contexts.STYLE_SECOND_PASS:
  779. self._emit_text("'")
  780. return True
  781. elif self._context & contexts.STYLE_ITALICS:
  782. self._context |= contexts.STYLE_PASS_AGAIN
  783. self._emit_text("'''")
  784. else:
  785. self._emit_text("'")
  786. self._parse_italics()
  787. else:
  788. self._emit_style_tag("b", "'''", stack)
  789. def _parse_italics_and_bold(self):
  790. """Parse wiki-style italics and bold together (i.e., five ticks)."""
  791. reset = self._head
  792. try:
  793. stack = self._parse(contexts.STYLE_BOLD)
  794. except BadRoute:
  795. self._head = reset
  796. try:
  797. stack = self._parse(contexts.STYLE_ITALICS)
  798. except BadRoute:
  799. self._head = reset
  800. self._emit_text("'''''")
  801. else:
  802. reset = self._head
  803. try:
  804. stack2 = self._parse(contexts.STYLE_BOLD)
  805. except BadRoute:
  806. self._head = reset
  807. self._emit_text("'''")
  808. self._emit_style_tag("i", "''", stack)
  809. else:
  810. self._push()
  811. self._emit_style_tag("i", "''", stack)
  812. self._emit_all(stack2)
  813. self._emit_style_tag("b", "'''", self._pop())
  814. else:
  815. reset = self._head
  816. try:
  817. stack2 = self._parse(contexts.STYLE_ITALICS)
  818. except BadRoute:
  819. self._head = reset
  820. self._emit_text("''")
  821. self._emit_style_tag("b", "'''", stack)
  822. else:
  823. self._push()
  824. self._emit_style_tag("b", "'''", stack)
  825. self._emit_all(stack2)
  826. self._emit_style_tag("i", "''", self._pop())
  827. def _parse_style(self):
  828. """Parse wiki-style formatting (``''``/``'''`` for italics/bold)."""
  829. self._head += 2
  830. ticks = 2
  831. while self._read() == "'":
  832. self._head += 1
  833. ticks += 1
  834. italics = self._context & contexts.STYLE_ITALICS
  835. bold = self._context & contexts.STYLE_BOLD
  836. if ticks > 5:
  837. self._emit_text("'" * (ticks - 5))
  838. ticks = 5
  839. elif ticks == 4:
  840. self._emit_text("'")
  841. ticks = 3
  842. if (italics and ticks in (2, 5)) or (bold and ticks in (3, 5)):
  843. if ticks == 5:
  844. self._head -= 3 if italics else 2
  845. return self._pop()
  846. elif not self._can_recurse():
  847. if ticks == 3:
  848. if self._context & contexts.STYLE_SECOND_PASS:
  849. self._emit_text("'")
  850. return self._pop()
  851. if self._context & contexts.STYLE_ITALICS:
  852. self._context |= contexts.STYLE_PASS_AGAIN
  853. self._emit_text("'" * ticks)
  854. elif ticks == 2:
  855. self._parse_italics()
  856. elif ticks == 3:
  857. if self._parse_bold():
  858. return self._pop()
  859. elif ticks == 5:
  860. self._parse_italics_and_bold()
  861. self._head -= 1
  862. def _handle_list_marker(self):
  863. """Handle a list marker at the head (``#``, ``*``, ``;``, ``:``)."""
  864. markup = self._read()
  865. if markup == ";":
  866. self._context |= contexts.DL_TERM
  867. self._emit(tokens.TagOpenOpen(wiki_markup=markup))
  868. self._emit_text(get_html_tag(markup))
  869. self._emit(tokens.TagCloseSelfclose())
  870. def _handle_list(self):
  871. """Handle a wiki-style list (``#``, ``*``, ``;``, ``:``)."""
  872. self._handle_list_marker()
  873. while self._read(1) in ("#", "*", ";", ":"):
  874. self._head += 1
  875. self._handle_list_marker()
  876. def _handle_hr(self):
  877. """Handle a wiki-style horizontal rule (``----``) in the string."""
  878. length = 4
  879. self._head += 3
  880. while self._read(1) == "-":
  881. length += 1
  882. self._head += 1
  883. self._emit(tokens.TagOpenOpen(wiki_markup="-" * length))
  884. self._emit_text("hr")
  885. self._emit(tokens.TagCloseSelfclose())
  886. def _handle_dl_term(self):
  887. """Handle the term in a description list (``foo`` in ``;foo:bar``)."""
  888. self._context ^= contexts.DL_TERM
  889. if self._read() == ":":
  890. self._handle_list_marker()
  891. else:
  892. self._emit_text("\n")
  893. def _handle_end(self):
  894. """Handle the end of the stream of wikitext."""
  895. if self._context & contexts.FAIL:
  896. if self._context & contexts.TAG_BODY:
  897. if is_single(self._stack[1].text):
  898. return self._handle_single_tag_end()
  899. if self._context & contexts.DOUBLE:
  900. self._pop()
  901. self._fail_route()
  902. return self._pop()
  903. def _verify_safe(self, this):
  904. """Make sure we are not trying to write an invalid character."""
  905. context = self._context
  906. if context & contexts.FAIL_NEXT:
  907. return False
  908. if context & contexts.WIKILINK:
  909. if context & contexts.WIKILINK_TEXT:
  910. return not (this == self._read(1) == "[")
  911. elif this == "]" or this == "{":
  912. self._context |= contexts.FAIL_NEXT
  913. elif this == "\n" or this == "[" or this == "}":
  914. return False
  915. return True
  916. elif context & contexts.EXT_LINK_TITLE:
  917. return this != "\n"
  918. elif context & contexts.TEMPLATE_NAME:
  919. if this == "{" or this == "}" or this == "[":
  920. self._context |= contexts.FAIL_NEXT
  921. return True
  922. if this == "]":
  923. return False
  924. if this == "|":
  925. return True
  926. if context & contexts.HAS_TEXT:
  927. if context & contexts.FAIL_ON_TEXT:
  928. if this is self.END or not this.isspace():
  929. return False
  930. else:
  931. if this == "\n":
  932. self._context |= contexts.FAIL_ON_TEXT
  933. elif this is self.END or not this.isspace():
  934. self._context |= contexts.HAS_TEXT
  935. return True
  936. elif context & contexts.TAG_CLOSE:
  937. return this != "<"
  938. else:
  939. if context & contexts.FAIL_ON_EQUALS:
  940. if this == "=":
  941. return False
  942. elif context & contexts.FAIL_ON_LBRACE:
  943. if this == "{" or (self._read(-1) == self._read(-2) == "{"):
  944. if context & contexts.TEMPLATE:
  945. self._context |= contexts.FAIL_ON_EQUALS
  946. else:
  947. self._context |= contexts.FAIL_NEXT
  948. return True
  949. self._context ^= contexts.FAIL_ON_LBRACE
  950. elif context & contexts.FAIL_ON_RBRACE:
  951. if this == "}":
  952. if context & contexts.TEMPLATE:
  953. self._context |= contexts.FAIL_ON_EQUALS
  954. else:
  955. self._context |= contexts.FAIL_NEXT
  956. return True
  957. self._context ^= contexts.FAIL_ON_RBRACE
  958. elif this == "{":
  959. self._context |= contexts.FAIL_ON_LBRACE
  960. elif this == "}":
  961. self._context |= contexts.FAIL_ON_RBRACE
  962. return True
  963. def _parse(self, context=0, push=True):
  964. """Parse the wikicode string, using *context* for when to stop."""
  965. if push:
  966. self._push(context)
  967. while True:
  968. this = self._read()
  969. if self._context & contexts.UNSAFE:
  970. if not self._verify_safe(this):
  971. if self._context & contexts.DOUBLE:
  972. self._pop()
  973. self._fail_route()
  974. if this not in self.MARKERS:
  975. self._emit_text(this)
  976. self._head += 1
  977. continue
  978. if this is self.END:
  979. return self._handle_end()
  980. next = self._read(1)
  981. if this == next == "{":
  982. if self._can_recurse():
  983. self._parse_template_or_argument()
  984. else:
  985. self._emit_text("{")
  986. elif this == "|" and self._context & contexts.TEMPLATE:
  987. self._handle_template_param()
  988. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  989. self._handle_template_param_value()
  990. elif this == next == "}" and self._context & contexts.TEMPLATE:
  991. return self._handle_template_end()
  992. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  993. self._handle_argument_separator()
  994. elif this == next == "}" and self._context & contexts.ARGUMENT:
  995. if self._read(2) == "}":
  996. return self._handle_argument_end()
  997. else:
  998. self._emit_text("}")
  999. elif this == next == "[" and self._can_recurse():
  1000. if not self._context & contexts.INVALID_LINK:
  1001. self._parse_wikilink()
  1002. else:
  1003. self._emit_text("[")
  1004. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  1005. self._handle_wikilink_separator()
  1006. elif this == next == "]" and self._context & contexts.WIKILINK:
  1007. return self._handle_wikilink_end()
  1008. elif this == "[":
  1009. self._parse_external_link(True)
  1010. elif this == ":" and self._read(-1) not in self.MARKERS:
  1011. self._parse_external_link(False)
  1012. elif this == "]" and self._context & contexts.EXT_LINK_TITLE:
  1013. return self._pop()
  1014. elif this == "=" and not self._global & contexts.GL_HEADING:
  1015. if self._read(-1) in ("\n", self.START):
  1016. self._parse_heading()
  1017. else:
  1018. self._emit_text("=")
  1019. elif this == "=" and self._context & contexts.HEADING:
  1020. return self._handle_heading_end()
  1021. elif this == "\n" and self._context & contexts.HEADING:
  1022. self._fail_route()
  1023. elif this == "&":
  1024. self._parse_entity()
  1025. elif this == "<" and next == "!":
  1026. if self._read(2) == self._read(3) == "-":
  1027. self._parse_comment()
  1028. else:
  1029. self._emit_text(this)
  1030. elif this == "<" and next == "/" and self._read(2) is not self.END:
  1031. if self._context & contexts.TAG_BODY:
  1032. self._handle_tag_open_close()
  1033. else:
  1034. self._handle_invalid_tag_start()
  1035. elif this == "<" and not self._context & contexts.TAG_CLOSE:
  1036. if self._can_recurse():
  1037. self._parse_tag()
  1038. else:
  1039. self._emit_text("<")
  1040. elif this == ">" and self._context & contexts.TAG_CLOSE:
  1041. return self._handle_tag_close_close()
  1042. elif this == next == "'":
  1043. result = self._parse_style()
  1044. if result is not None:
  1045. return result
  1046. elif self._read(-1) in ("\n", self.START):
  1047. if this in ("#", "*", ";", ":"):
  1048. self._handle_list()
  1049. elif this == next == self._read(2) == self._read(3) == "-":
  1050. self._handle_hr()
  1051. else:
  1052. self._emit_text(this)
  1053. elif this in ("\n", ":") and self._context & contexts.DL_TERM:
  1054. self._handle_dl_term()
  1055. else:
  1056. self._emit_text(this)
  1057. self._head += 1
  1058. def tokenize(self, text, context=0):
  1059. """Build a list of tokens from a string of wikicode and return it."""
  1060. split = self.regex.split(text)
  1061. self._text = [segment for segment in split if segment]
  1062. self._head = self._global = self._depth = self._cycles = 0
  1063. return self._parse(context)