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.
 
 
 
 

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