A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

776 строки
30 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 ..tag_defs import is_parsable, is_single, is_single_only
  28. __all__ = ["Tokenizer"]
  29. class BadRoute(Exception):
  30. """Raised internally when the current tokenization route is invalid."""
  31. pass
  32. class _TagOpenData(object):
  33. """Stores data about an HTML open tag, like ``<ref name="foo">``."""
  34. CX_NAME = 1 << 0
  35. CX_ATTR_READY = 1 << 1
  36. CX_ATTR_NAME = 1 << 2
  37. CX_ATTR_VALUE = 1 << 3
  38. CX_QUOTED = 1 << 4
  39. CX_NOTE_SPACE = 1 << 5
  40. CX_NOTE_EQUALS = 1 << 6
  41. CX_NOTE_QUOTE = 1 << 7
  42. def __init__(self):
  43. self.context = self.CX_NAME
  44. self.padding_buffer = {"first": "", "before_eq": "", "after_eq": ""}
  45. self.reset = 0
  46. class Tokenizer(object):
  47. """Creates a list of tokens from a string of wikicode."""
  48. USES_C = False
  49. START = object()
  50. END = object()
  51. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "#", "*", ";", ":",
  52. "/", "\\", '"', "-", "!", "\n", END]
  53. MAX_DEPTH = 40
  54. MAX_CYCLES = 100000
  55. regex = re.compile(r"([{}\[\]<>|=&#*;:/\\\"\-!\n])", flags=re.IGNORECASE)
  56. tag_splitter = re.compile(r"([\s\"\\]+)")
  57. def __init__(self):
  58. self._text = None
  59. self._head = 0
  60. self._stacks = []
  61. self._global = 0
  62. self._depth = 0
  63. self._cycles = 0
  64. @property
  65. def _stack(self):
  66. """The current token stack."""
  67. return self._stacks[-1][0]
  68. @property
  69. def _context(self):
  70. """The current token context."""
  71. return self._stacks[-1][1]
  72. @_context.setter
  73. def _context(self, value):
  74. self._stacks[-1][1] = value
  75. @property
  76. def _textbuffer(self):
  77. """The current textbuffer."""
  78. return self._stacks[-1][2]
  79. @_textbuffer.setter
  80. def _textbuffer(self, value):
  81. self._stacks[-1][2] = value
  82. def _push(self, context=0):
  83. """Add a new token stack, context, and textbuffer to the list."""
  84. self._stacks.append([[], context, []])
  85. self._depth += 1
  86. self._cycles += 1
  87. def _push_textbuffer(self):
  88. """Push the textbuffer onto the stack as a Text node and clear it."""
  89. if self._textbuffer:
  90. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  91. self._textbuffer = []
  92. def _pop(self, keep_context=False):
  93. """Pop the current stack/context/textbuffer, returing the stack.
  94. If *keep_context* is ``True``, then we will replace the underlying
  95. stack's context with the current stack's.
  96. """
  97. self._push_textbuffer()
  98. self._depth -= 1
  99. if keep_context:
  100. context = self._context
  101. stack = self._stacks.pop()[0]
  102. self._context = context
  103. return stack
  104. return self._stacks.pop()[0]
  105. def _can_recurse(self):
  106. """Return whether or not our max recursion depth has been exceeded."""
  107. return self._depth < self.MAX_DEPTH and self._cycles < self.MAX_CYCLES
  108. def _fail_route(self):
  109. """Fail the current tokenization route.
  110. Discards the current stack/context/textbuffer and raises
  111. :py:exc:`~.BadRoute`.
  112. """
  113. self._pop()
  114. raise BadRoute()
  115. def _emit(self, token):
  116. """Write a token to the end of the current token stack."""
  117. self._push_textbuffer()
  118. self._stack.append(token)
  119. def _emit_first(self, token):
  120. """Write a token to the beginning of the current token stack."""
  121. self._push_textbuffer()
  122. self._stack.insert(0, token)
  123. def _emit_text(self, text):
  124. """Write text to the current textbuffer."""
  125. self._textbuffer.append(text)
  126. def _emit_all(self, tokenlist):
  127. """Write a series of tokens to the current stack at once."""
  128. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  129. self._emit_text(tokenlist.pop(0).text)
  130. self._push_textbuffer()
  131. self._stack.extend(tokenlist)
  132. def _emit_text_then_stack(self, text):
  133. """Pop the current stack, write *text*, and then write the stack."""
  134. stack = self._pop()
  135. self._emit_text(text)
  136. if stack:
  137. self._emit_all(stack)
  138. self._head -= 1
  139. def _read(self, delta=0, wrap=False, strict=False):
  140. """Read the value at a relative point in the wikicode.
  141. The value is read from :py:attr:`self._head <_head>` plus the value of
  142. *delta* (which can be negative). If *wrap* is ``False``, we will not
  143. allow attempts to read from the end of the string if ``self._head +
  144. delta`` is negative. If *strict* is ``True``, the route will be failed
  145. (with :py:meth:`_fail_route`) if we try to read from past the end of
  146. the string; otherwise, :py:attr:`self.END <END>` is returned. If we try
  147. to read from before the start of the string, :py:attr:`self.START
  148. <START>` is returned.
  149. """
  150. index = self._head + delta
  151. if index < 0 and (not wrap or abs(index) > len(self._text)):
  152. return self.START
  153. try:
  154. return self._text[index]
  155. except IndexError:
  156. if strict:
  157. self._fail_route()
  158. return self.END
  159. def _parse_template_or_argument(self):
  160. """Parse a template or argument at the head of the wikicode string."""
  161. self._head += 2
  162. braces = 2
  163. while self._read() == "{":
  164. self._head += 1
  165. braces += 1
  166. self._push()
  167. while braces:
  168. if braces == 1:
  169. return self._emit_text_then_stack("{")
  170. if braces == 2:
  171. try:
  172. self._parse_template()
  173. except BadRoute:
  174. return self._emit_text_then_stack("{{")
  175. break
  176. try:
  177. self._parse_argument()
  178. braces -= 3
  179. except BadRoute:
  180. try:
  181. self._parse_template()
  182. braces -= 2
  183. except BadRoute:
  184. return self._emit_text_then_stack("{" * braces)
  185. if braces:
  186. self._head += 1
  187. self._emit_all(self._pop())
  188. if self._context & contexts.FAIL_NEXT:
  189. self._context ^= contexts.FAIL_NEXT
  190. def _parse_template(self):
  191. """Parse a template at the head of the wikicode string."""
  192. reset = self._head
  193. try:
  194. template = self._parse(contexts.TEMPLATE_NAME)
  195. except BadRoute:
  196. self._head = reset
  197. raise
  198. self._emit_first(tokens.TemplateOpen())
  199. self._emit_all(template)
  200. self._emit(tokens.TemplateClose())
  201. def _parse_argument(self):
  202. """Parse an argument at the head of the wikicode string."""
  203. reset = self._head
  204. try:
  205. argument = self._parse(contexts.ARGUMENT_NAME)
  206. except BadRoute:
  207. self._head = reset
  208. raise
  209. self._emit_first(tokens.ArgumentOpen())
  210. self._emit_all(argument)
  211. self._emit(tokens.ArgumentClose())
  212. def _handle_template_param(self):
  213. """Handle a template parameter at the head of the string."""
  214. if self._context & contexts.TEMPLATE_NAME:
  215. self._context ^= contexts.TEMPLATE_NAME
  216. elif self._context & contexts.TEMPLATE_PARAM_VALUE:
  217. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  218. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  219. self._emit_all(self._pop(keep_context=True))
  220. self._context |= contexts.TEMPLATE_PARAM_KEY
  221. self._emit(tokens.TemplateParamSeparator())
  222. self._push(self._context)
  223. def _handle_template_param_value(self):
  224. """Handle a template parameter's value at the head of the string."""
  225. self._emit_all(self._pop(keep_context=True))
  226. self._context ^= contexts.TEMPLATE_PARAM_KEY
  227. self._context |= contexts.TEMPLATE_PARAM_VALUE
  228. self._emit(tokens.TemplateParamEquals())
  229. def _handle_template_end(self):
  230. """Handle the end of a template at the head of the string."""
  231. if self._context & contexts.TEMPLATE_PARAM_KEY:
  232. self._emit_all(self._pop(keep_context=True))
  233. self._head += 1
  234. return self._pop()
  235. def _handle_argument_separator(self):
  236. """Handle the separator between an argument's name and default."""
  237. self._context ^= contexts.ARGUMENT_NAME
  238. self._context |= contexts.ARGUMENT_DEFAULT
  239. self._emit(tokens.ArgumentSeparator())
  240. def _handle_argument_end(self):
  241. """Handle the end of an argument at the head of the string."""
  242. self._head += 2
  243. return self._pop()
  244. def _parse_wikilink(self):
  245. """Parse an internal wikilink at the head of the wikicode string."""
  246. self._head += 2
  247. reset = self._head - 1
  248. try:
  249. wikilink = self._parse(contexts.WIKILINK_TITLE)
  250. except BadRoute:
  251. self._head = reset
  252. self._emit_text("[[")
  253. else:
  254. if self._context & contexts.FAIL_NEXT:
  255. self._context ^= contexts.FAIL_NEXT
  256. self._emit(tokens.WikilinkOpen())
  257. self._emit_all(wikilink)
  258. self._emit(tokens.WikilinkClose())
  259. def _handle_wikilink_separator(self):
  260. """Handle the separator between a wikilink's title and its text."""
  261. self._context ^= contexts.WIKILINK_TITLE
  262. self._context |= contexts.WIKILINK_TEXT
  263. self._emit(tokens.WikilinkSeparator())
  264. def _handle_wikilink_end(self):
  265. """Handle the end of a wikilink at the head of the string."""
  266. self._head += 1
  267. return self._pop()
  268. def _parse_heading(self):
  269. """Parse a section heading at the head of the wikicode string."""
  270. self._global |= contexts.GL_HEADING
  271. reset = self._head
  272. self._head += 1
  273. best = 1
  274. while self._read() == "=":
  275. best += 1
  276. self._head += 1
  277. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  278. try:
  279. title, level = self._parse(context)
  280. except BadRoute:
  281. self._head = reset + best - 1
  282. self._emit_text("=" * best)
  283. else:
  284. self._emit(tokens.HeadingStart(level=level))
  285. if level < best:
  286. self._emit_text("=" * (best - level))
  287. self._emit_all(title)
  288. self._emit(tokens.HeadingEnd())
  289. finally:
  290. self._global ^= contexts.GL_HEADING
  291. def _handle_heading_end(self):
  292. """Handle the end of a section heading at the head of the string."""
  293. reset = self._head
  294. self._head += 1
  295. best = 1
  296. while self._read() == "=":
  297. best += 1
  298. self._head += 1
  299. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  300. level = min(current, min(best, 6))
  301. try: # Try to check for a heading closure after this one
  302. after, after_level = self._parse(self._context)
  303. except BadRoute:
  304. if level < best:
  305. self._emit_text("=" * (best - level))
  306. self._head = reset + best - 1
  307. return self._pop(), level
  308. else: # Found another closure
  309. self._emit_text("=" * best)
  310. self._emit_all(after)
  311. return self._pop(), after_level
  312. def _really_parse_entity(self):
  313. """Actually parse an HTML entity and ensure that it is valid."""
  314. self._emit(tokens.HTMLEntityStart())
  315. self._head += 1
  316. this = self._read(strict=True)
  317. if this == "#":
  318. numeric = True
  319. self._emit(tokens.HTMLEntityNumeric())
  320. self._head += 1
  321. this = self._read(strict=True)
  322. if this[0].lower() == "x":
  323. hexadecimal = True
  324. self._emit(tokens.HTMLEntityHex(char=this[0]))
  325. this = this[1:]
  326. if not this:
  327. self._fail_route()
  328. else:
  329. hexadecimal = False
  330. else:
  331. numeric = hexadecimal = False
  332. valid = "0123456789abcdefABCDEF" if hexadecimal else "0123456789"
  333. if not numeric and not hexadecimal:
  334. valid += "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  335. if not all([char in valid for char in this]):
  336. self._fail_route()
  337. self._head += 1
  338. if self._read() != ";":
  339. self._fail_route()
  340. if numeric:
  341. test = int(this, 16) if hexadecimal else int(this)
  342. if test < 1 or test > 0x10FFFF:
  343. self._fail_route()
  344. else:
  345. if this not in htmlentities.entitydefs:
  346. self._fail_route()
  347. self._emit(tokens.Text(text=this))
  348. self._emit(tokens.HTMLEntityEnd())
  349. def _parse_entity(self):
  350. """Parse an HTML entity at the head of the wikicode string."""
  351. reset = self._head
  352. self._push()
  353. try:
  354. self._really_parse_entity()
  355. except BadRoute:
  356. self._head = reset
  357. self._emit_text(self._read())
  358. else:
  359. self._emit_all(self._pop())
  360. def _parse_comment(self):
  361. """Parse an HTML comment at the head of the wikicode string."""
  362. self._head += 4
  363. reset = self._head - 1
  364. try:
  365. comment = self._parse(contexts.COMMENT)
  366. except BadRoute:
  367. self._head = reset
  368. self._emit_text("<!--")
  369. else:
  370. self._emit(tokens.CommentStart())
  371. self._emit_all(comment)
  372. self._emit(tokens.CommentEnd())
  373. self._head += 2
  374. def _parse_tag(self):
  375. """Parse an HTML tag at the head of the wikicode string."""
  376. reset = self._head
  377. self._head += 1
  378. try:
  379. tag = self._really_parse_tag()
  380. except BadRoute:
  381. self._head = reset
  382. self._emit_text("<")
  383. else:
  384. self._emit_all(tag)
  385. def _really_parse_tag(self):
  386. """Actually parse an HTML tag, starting with the open (``<foo>``)."""
  387. data = _TagOpenData()
  388. self._push(contexts.TAG_OPEN)
  389. self._emit(tokens.TagOpenOpen(showtag=True))
  390. while True:
  391. this, next = self._read(), self._read(1)
  392. can_exit = (not data.context & (data.CX_QUOTED | data.CX_NAME) or
  393. data.context & data.CX_NOTE_SPACE)
  394. if this is self.END:
  395. if self._context & contexts.TAG_ATTR:
  396. if data.context & data.CX_QUOTED:
  397. # Unclosed attribute quote: reset, don't die
  398. data.context = data.CX_ATTR_VALUE
  399. self._pop()
  400. self._head = data.reset
  401. continue
  402. self._pop()
  403. self._fail_route()
  404. elif this == ">" and can_exit:
  405. self._handle_tag_close_open(data, tokens.TagCloseOpen)
  406. self._context = contexts.TAG_BODY
  407. if is_single_only(self._stack[1].text):
  408. return self._handle_single_only_tag()
  409. if is_parsable(self._stack[1].text):
  410. return self._parse(push=False)
  411. return self._handle_blacklisted_tag()
  412. elif this == "/" and next == ">" and can_exit:
  413. self._handle_tag_close_open(data, tokens.TagCloseSelfclose)
  414. return self._pop()
  415. else:
  416. self._handle_tag_data(data, this)
  417. self._head += 1
  418. def _push_tag_buffer(self, data):
  419. """Write a pending tag attribute from *data* to the stack."""
  420. if data.context & data.CX_QUOTED:
  421. self._emit_first(tokens.TagAttrQuote())
  422. self._emit_all(self._pop())
  423. buf = data.padding_buffer
  424. self._emit_first(tokens.TagAttrStart(pad_first=buf["first"],
  425. pad_before_eq=buf["before_eq"], pad_after_eq=buf["after_eq"]))
  426. self._emit_all(self._pop())
  427. data.padding_buffer = {key: "" for key in data.padding_buffer}
  428. def _handle_tag_data(self, data, text):
  429. """Handle all sorts of *text* data inside of an HTML open tag."""
  430. for chunk in self.tag_splitter.split(text):
  431. if not chunk:
  432. continue
  433. if data.context & data.CX_NAME:
  434. if chunk in self.MARKERS or chunk.isspace():
  435. self._fail_route() # Tags must start with text, not spaces
  436. data.context = data.CX_NOTE_SPACE
  437. elif chunk.isspace():
  438. self._handle_tag_space(data, chunk)
  439. continue
  440. elif data.context & data.CX_NOTE_SPACE:
  441. if data.context & data.CX_QUOTED:
  442. data.context = data.CX_ATTR_VALUE
  443. self._pop()
  444. self._head = data.reset - 1 # Will be auto-incremented
  445. return # Break early
  446. self._fail_route()
  447. elif data.context & data.CX_ATTR_READY:
  448. data.context = data.CX_ATTR_NAME
  449. self._push(contexts.TAG_ATTR)
  450. elif data.context & data.CX_ATTR_NAME:
  451. if chunk == "=":
  452. data.context = data.CX_ATTR_VALUE | data.CX_NOTE_QUOTE
  453. self._emit(tokens.TagAttrEquals())
  454. continue
  455. if data.context & data.CX_NOTE_EQUALS:
  456. self._push_tag_buffer(data)
  457. data.context = data.CX_ATTR_NAME
  458. self._push(contexts.TAG_ATTR)
  459. elif data.context & data.CX_ATTR_VALUE:
  460. escaped = self._read(-1) == "\\" and self._read(-2) != "\\"
  461. if data.context & data.CX_NOTE_QUOTE:
  462. data.context ^= data.CX_NOTE_QUOTE
  463. if chunk == '"' and not escaped:
  464. data.context |= data.CX_QUOTED
  465. self._push(self._context)
  466. data.reset = self._head
  467. continue
  468. elif data.context & data.CX_QUOTED:
  469. if chunk == '"' and not escaped:
  470. data.context |= data.CX_NOTE_SPACE
  471. continue
  472. self._handle_tag_text(chunk)
  473. def _handle_tag_space(self, data, text):
  474. """Handle whitespace (*text*) inside of an HTML open tag."""
  475. ctx = data.context
  476. end_of_value = ctx & data.CX_ATTR_VALUE and not ctx & (data.CX_QUOTED | data.CX_NOTE_QUOTE)
  477. if end_of_value or (ctx & data.CX_QUOTED and ctx & data.CX_NOTE_SPACE):
  478. self._push_tag_buffer(data)
  479. data.context = data.CX_ATTR_READY
  480. elif ctx & data.CX_NOTE_SPACE:
  481. data.context = data.CX_ATTR_READY
  482. elif ctx & data.CX_ATTR_NAME:
  483. data.context |= data.CX_NOTE_EQUALS
  484. data.padding_buffer["before_eq"] += text
  485. if ctx & data.CX_QUOTED and not ctx & data.CX_NOTE_SPACE:
  486. self._emit_text(text)
  487. elif data.context & data.CX_ATTR_READY:
  488. data.padding_buffer["first"] += text
  489. elif data.context & data.CX_ATTR_VALUE:
  490. data.padding_buffer["after_eq"] += text
  491. def _handle_tag_text(self, text):
  492. """Handle regular *text* inside of an HTML open tag."""
  493. next = self._read(1)
  494. if not self._can_recurse() or text not in self.MARKERS:
  495. self._emit_text(text)
  496. elif text == next == "{":
  497. self._parse_template_or_argument()
  498. elif text == next == "[":
  499. self._parse_wikilink()
  500. elif text == "<":
  501. self._parse_tag()
  502. else:
  503. self._emit_text(text)
  504. def _handle_blacklisted_tag(self):
  505. """Handle the body of an HTML tag that is parser-blacklisted."""
  506. while True:
  507. this, next = self._read(), self._read(1)
  508. self._head += 1
  509. if this is self.END:
  510. self._fail_route()
  511. elif this == "<" and next == "/":
  512. self._handle_tag_open_close()
  513. return self._parse(push=False)
  514. else:
  515. self._emit_text(this)
  516. def _handle_tag_close_open(self, data, token):
  517. """Handle the closing of a open tag (``<foo>``)."""
  518. if data.context & (data.CX_ATTR_NAME | data.CX_ATTR_VALUE):
  519. self._push_tag_buffer(data)
  520. self._emit(token(padding=data.padding_buffer["first"]))
  521. self._head += 1
  522. def _handle_tag_open_close(self):
  523. """Handle the opening of a closing tag (``</foo>``)."""
  524. self._emit(tokens.TagOpenClose())
  525. self._push(contexts.TAG_CLOSE)
  526. self._head += 1
  527. def _handle_tag_close_close(self):
  528. """Handle the ending of a closing tag (``</foo>``)."""
  529. strip = lambda tok: tok.text.rstrip().lower()
  530. closing = self._pop()
  531. if len(closing) != 1 or (not isinstance(closing[0], tokens.Text) or
  532. strip(closing[0]) != strip(self._stack[1])):
  533. self._fail_route()
  534. self._emit_all(closing)
  535. self._emit(tokens.TagCloseClose())
  536. return self._pop()
  537. def _handle_single_only_tag(self):
  538. """Handle the end of an implicitly closing single-only HTML tag."""
  539. padding = self._stack.pop().padding
  540. token = tokens.TagCloseSelfclose(padding=padding, implicit=True)
  541. self._stack.append(token)
  542. self._head -= 1
  543. return self._pop()
  544. def _handle_single_tag_end(self):
  545. """Handle the stream end when inside a single-supporting HTML tag."""
  546. gen = enumerate(self._stack)
  547. index = next(i for i, t in gen if isinstance(t, tokens.TagCloseOpen))
  548. padding = self._stack[index].padding
  549. token = tokens.TagCloseSelfclose(padding=padding, implicit=True)
  550. self._stack[index] = token
  551. return self._pop()
  552. def _handle_end(self):
  553. """Handle the end of the stream of wikitext."""
  554. fail = (contexts.TEMPLATE | contexts.ARGUMENT | contexts.WIKILINK |
  555. contexts.HEADING | contexts.COMMENT | contexts.TAG)
  556. double_fail = (contexts.TEMPLATE_PARAM_KEY | contexts.TAG_CLOSE)
  557. if self._context & fail:
  558. if self._context & contexts.TAG_BODY:
  559. if is_single(self._stack[1].text):
  560. return self._handle_single_tag_end()
  561. if self._context & double_fail:
  562. self._pop()
  563. self._fail_route()
  564. return self._pop()
  565. def _verify_safe(self, this):
  566. """Make sure we are not trying to write an invalid character."""
  567. context = self._context
  568. if context & contexts.FAIL_NEXT:
  569. return False
  570. if context & contexts.WIKILINK_TITLE:
  571. if this == "]" or this == "{":
  572. self._context |= contexts.FAIL_NEXT
  573. elif this == "\n" or this == "[" or this == "}":
  574. return False
  575. return True
  576. elif context & contexts.TEMPLATE_NAME:
  577. if this == "{" or this == "}" or this == "[":
  578. self._context |= contexts.FAIL_NEXT
  579. return True
  580. if this == "]":
  581. return False
  582. if this == "|":
  583. return True
  584. if context & contexts.HAS_TEXT:
  585. if context & contexts.FAIL_ON_TEXT:
  586. if this is self.END or not this.isspace():
  587. return False
  588. else:
  589. if this == "\n":
  590. self._context |= contexts.FAIL_ON_TEXT
  591. elif this is self.END or not this.isspace():
  592. self._context |= contexts.HAS_TEXT
  593. return True
  594. elif context & contexts.TAG_CLOSE:
  595. return this != "<"
  596. else:
  597. if context & contexts.FAIL_ON_EQUALS:
  598. if this == "=":
  599. return False
  600. elif context & contexts.FAIL_ON_LBRACE:
  601. if this == "{" or (self._read(-1) == self._read(-2) == "{"):
  602. if context & contexts.TEMPLATE:
  603. self._context |= contexts.FAIL_ON_EQUALS
  604. else:
  605. self._context |= contexts.FAIL_NEXT
  606. return True
  607. self._context ^= contexts.FAIL_ON_LBRACE
  608. elif context & contexts.FAIL_ON_RBRACE:
  609. if this == "}":
  610. if context & contexts.TEMPLATE:
  611. self._context |= contexts.FAIL_ON_EQUALS
  612. else:
  613. self._context |= contexts.FAIL_NEXT
  614. return True
  615. self._context ^= contexts.FAIL_ON_RBRACE
  616. elif this == "{":
  617. self._context |= contexts.FAIL_ON_LBRACE
  618. elif this == "}":
  619. self._context |= contexts.FAIL_ON_RBRACE
  620. return True
  621. def _parse(self, context=0, push=True):
  622. """Parse the wikicode string, using *context* for when to stop."""
  623. unsafe = (contexts.TEMPLATE_NAME | contexts.WIKILINK_TITLE |
  624. contexts.TEMPLATE_PARAM_KEY | contexts.ARGUMENT_NAME |
  625. contexts.TAG_CLOSE)
  626. if push:
  627. self._push(context)
  628. while True:
  629. this = self._read()
  630. if self._context & unsafe:
  631. if not self._verify_safe(this):
  632. if self._context & double_fail:
  633. self._pop()
  634. self._fail_route()
  635. if this not in self.MARKERS:
  636. self._emit_text(this)
  637. self._head += 1
  638. continue
  639. if this is self.END:
  640. return self._handle_end()
  641. next = self._read(1)
  642. if self._context & contexts.COMMENT:
  643. if this == next == "-" and self._read(2) == ">":
  644. return self._pop()
  645. else:
  646. self._emit_text(this)
  647. elif this == next == "{":
  648. if self._can_recurse():
  649. self._parse_template_or_argument()
  650. else:
  651. self._emit_text("{")
  652. elif this == "|" and self._context & contexts.TEMPLATE:
  653. self._handle_template_param()
  654. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  655. self._handle_template_param_value()
  656. elif this == next == "}" and self._context & contexts.TEMPLATE:
  657. return self._handle_template_end()
  658. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  659. self._handle_argument_separator()
  660. elif this == next == "}" and self._context & contexts.ARGUMENT:
  661. if self._read(2) == "}":
  662. return self._handle_argument_end()
  663. else:
  664. self._emit_text("}")
  665. elif this == next == "[":
  666. if not self._context & contexts.WIKILINK_TITLE and self._can_recurse():
  667. self._parse_wikilink()
  668. else:
  669. self._emit_text("[")
  670. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  671. self._handle_wikilink_separator()
  672. elif this == next == "]" and self._context & contexts.WIKILINK:
  673. return self._handle_wikilink_end()
  674. elif this == "=" and not self._global & contexts.GL_HEADING:
  675. if self._read(-1) in ("\n", self.START):
  676. self._parse_heading()
  677. else:
  678. self._emit_text("=")
  679. elif this == "=" and self._context & contexts.HEADING:
  680. return self._handle_heading_end()
  681. elif this == "\n" and self._context & contexts.HEADING:
  682. self._fail_route()
  683. elif this == "&":
  684. self._parse_entity()
  685. elif this == "<" and next == "!":
  686. if self._read(2) == self._read(3) == "-":
  687. self._parse_comment()
  688. else:
  689. self._emit_text(this)
  690. elif this == "<" and next == "/" and self._context & contexts.TAG_BODY:
  691. self._handle_tag_open_close()
  692. elif this == "<":
  693. if not self._context & contexts.TAG_CLOSE and self._can_recurse():
  694. self._parse_tag()
  695. else:
  696. self._emit_text("<")
  697. elif this == ">" and self._context & contexts.TAG_CLOSE:
  698. return self._handle_tag_close_close()
  699. else:
  700. self._emit_text(this)
  701. self._head += 1
  702. def tokenize(self, text):
  703. """Build a list of tokens from a string of wikicode and return it."""
  704. split = self.regex.split(text)
  705. self._text = [segment for segment in split if segment]
  706. return self._parse()