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.
 
 
 
 

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