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.

tokenizer.py 44 KiB

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