A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

1152 行
44 KiB

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