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

571 行
21 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 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. import string
  26. from . import contexts
  27. from . import tokens
  28. from ..nodes.tag import Tag
  29. from ..compat import htmlentities
  30. __all__ = ["Tokenizer"]
  31. class BadRoute(Exception):
  32. """Raised internally when the current tokenization route is invalid."""
  33. pass
  34. class Tokenizer(object):
  35. """Creates a list of tokens from a string of wikicode."""
  36. START = object()
  37. END = object()
  38. MARKERS = ["{", "}", "[", "]", "<", ">", "|", "=", "&", "#", "*", ";", ":",
  39. "/", "-", "!", "\n", END]
  40. regex = re.compile(r"([{}\[\]<>|=&#*;:/\-!\n])", flags=re.IGNORECASE)
  41. def __init__(self):
  42. self._text = None
  43. self._head = 0
  44. self._stacks = []
  45. self._global = 0
  46. @property
  47. def _stack(self):
  48. """The current token stack."""
  49. return self._stacks[-1][0]
  50. @property
  51. def _context(self):
  52. """The current token context."""
  53. return self._stacks[-1][1]
  54. @_context.setter
  55. def _context(self, value):
  56. self._stacks[-1][1] = value
  57. @property
  58. def _textbuffer(self):
  59. """The current textbuffer."""
  60. return self._stacks[-1][2]
  61. @_textbuffer.setter
  62. def _textbuffer(self, value):
  63. self._stacks[-1][2] = value
  64. def _push(self, context=0):
  65. """Add a new token stack, context, and textbuffer to the list."""
  66. self._stacks.append([[], context, []])
  67. def _push_textbuffer(self):
  68. """Push the textbuffer onto the stack as a Text node and clear it."""
  69. if self._textbuffer:
  70. self._stack.append(tokens.Text(text="".join(self._textbuffer)))
  71. self._textbuffer = []
  72. def _pop(self, keep_context=False):
  73. """Pop the current stack/context/textbuffer, returing the stack.
  74. If *keep_context* is ``True``, then we will replace the underlying
  75. stack's context with the current stack's.
  76. """
  77. self._push_textbuffer()
  78. if keep_context:
  79. context = self._context
  80. stack = self._stacks.pop()[0]
  81. self._context = context
  82. return stack
  83. return self._stacks.pop()[0]
  84. def _fail_route(self):
  85. """Fail the current tokenization route.
  86. Discards the current stack/context/textbuffer and raises
  87. :py:exc:`~.BadRoute`.
  88. """
  89. self._pop()
  90. raise BadRoute()
  91. def _write(self, token):
  92. """Write a token to the end of the current token stack."""
  93. self._push_textbuffer()
  94. self._stack.append(token)
  95. def _write_first(self, token):
  96. """Write a token to the beginning of the current token stack."""
  97. self._push_textbuffer()
  98. self._stack.insert(0, token)
  99. def _write_text(self, text):
  100. """Write text to the current textbuffer."""
  101. self._textbuffer.append(text)
  102. def _write_all(self, tokenlist):
  103. """Write a series of tokens to the current stack at once."""
  104. if tokenlist and isinstance(tokenlist[0], tokens.Text):
  105. self._write_text(tokenlist.pop(0).text)
  106. self._push_textbuffer()
  107. self._stack.extend(tokenlist)
  108. def _write_text_then_stack(self, text):
  109. """Pop the current stack, write *text*, and then write the stack."""
  110. stack = self._pop()
  111. self._write_text(text)
  112. if stack:
  113. self._write_all(stack)
  114. self._head -= 1
  115. def _read(self, delta=0, wrap=False, strict=False):
  116. """Read the value at a relative point in the wikicode.
  117. The value is read from :py:attr:`self._head <_head>` plus the value of
  118. *delta* (which can be negative). If *wrap* is ``False``, we will not
  119. allow attempts to read from the end of the string if ``self._head +
  120. delta`` is negative. If *strict* is ``True``, the route will be failed
  121. (with :py:meth:`_fail_route`) if we try to read from past the end of
  122. the string; otherwise, :py:attr:`self.END <END>` is returned. If we try
  123. to read from before the start of the string, :py:attr:`self.START
  124. <START>` is returned.
  125. """
  126. index = self._head + delta
  127. if index < 0 and (not wrap or abs(index) > len(self._text)):
  128. return self.START
  129. try:
  130. return self._text[index]
  131. except IndexError:
  132. if strict:
  133. self._fail_route()
  134. return self.END
  135. def _parse_template_or_argument(self):
  136. """Parse a template or argument at the head of the wikicode string."""
  137. self._head += 2
  138. braces = 2
  139. while self._read() == "{":
  140. self._head += 1
  141. braces += 1
  142. self._push()
  143. while braces:
  144. if braces == 1:
  145. return self._write_text_then_stack("{")
  146. if braces == 2:
  147. try:
  148. self._parse_template()
  149. except BadRoute:
  150. return self._write_text_then_stack("{{")
  151. break
  152. try:
  153. self._parse_argument()
  154. braces -= 3
  155. except BadRoute:
  156. try:
  157. self._parse_template()
  158. braces -= 2
  159. except BadRoute:
  160. return self._write_text_then_stack("{" * braces)
  161. if braces:
  162. self._head += 1
  163. self._write_all(self._pop())
  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._write_first(tokens.TemplateOpen())
  173. self._write_all(template)
  174. self._write(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._write_first(tokens.ArgumentOpen())
  184. self._write_all(argument)
  185. self._write(tokens.ArgumentClose())
  186. def _verify_safe(self, unsafes):
  187. """Verify that there are no unsafe characters in the current stack.
  188. The route will be failed if the name contains any element of *unsafes*
  189. in it (not merely at the beginning or end). This is used when parsing a
  190. template name or parameter key, which cannot contain newlines.
  191. """
  192. self._push_textbuffer()
  193. if self._stack:
  194. text = [tok for tok in self._stack if isinstance(tok, tokens.Text)]
  195. text = "".join([token.text for token in text]).strip()
  196. if text and any([unsafe in text for unsafe in unsafes]):
  197. self._fail_route()
  198. def _handle_template_param(self):
  199. """Handle a template parameter at the head of the string."""
  200. if self._context & contexts.TEMPLATE_NAME:
  201. self._verify_safe(["\n", "{", "}", "[", "]"])
  202. self._context ^= contexts.TEMPLATE_NAME
  203. elif self._context & contexts.TEMPLATE_PARAM_VALUE:
  204. self._context ^= contexts.TEMPLATE_PARAM_VALUE
  205. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  206. self._write_all(self._pop(keep_context=True))
  207. self._context |= contexts.TEMPLATE_PARAM_KEY
  208. self._write(tokens.TemplateParamSeparator())
  209. self._push(self._context)
  210. def _handle_template_param_value(self):
  211. """Handle a template parameter's value at the head of the string."""
  212. try:
  213. self._verify_safe(["\n", "{{", "}}"])
  214. except BadRoute:
  215. self._pop()
  216. raise
  217. self._write_all(self._pop(keep_context=True))
  218. self._context ^= contexts.TEMPLATE_PARAM_KEY
  219. self._context |= contexts.TEMPLATE_PARAM_VALUE
  220. self._write(tokens.TemplateParamEquals())
  221. def _handle_template_end(self):
  222. """Handle the end of a template at the head of the string."""
  223. if self._context & contexts.TEMPLATE_NAME:
  224. self._verify_safe(["\n", "{", "}", "[", "]"])
  225. elif self._context & contexts.TEMPLATE_PARAM_KEY:
  226. self._write_all(self._pop(keep_context=True))
  227. self._head += 1
  228. return self._pop()
  229. def _handle_argument_separator(self):
  230. """Handle the separator between an argument's name and default."""
  231. self._verify_safe(["\n", "{{", "}}"])
  232. self._context ^= contexts.ARGUMENT_NAME
  233. self._context |= contexts.ARGUMENT_DEFAULT
  234. self._write(tokens.ArgumentSeparator())
  235. def _handle_argument_end(self):
  236. """Handle the end of an argument at the head of the string."""
  237. if self._context & contexts.ARGUMENT_NAME:
  238. self._verify_safe(["\n", "{{", "}}"])
  239. self._head += 2
  240. return self._pop()
  241. def _parse_wikilink(self):
  242. """Parse an internal wikilink at the head of the wikicode string."""
  243. self._head += 2
  244. reset = self._head - 1
  245. try:
  246. wikilink = self._parse(contexts.WIKILINK_TITLE)
  247. except BadRoute:
  248. self._head = reset
  249. self._write_text("[[")
  250. else:
  251. self._write(tokens.WikilinkOpen())
  252. self._write_all(wikilink)
  253. self._write(tokens.WikilinkClose())
  254. def _handle_wikilink_separator(self):
  255. """Handle the separator between a wikilink's title and its text."""
  256. self._verify_safe(["\n", "{", "}", "[", "]"])
  257. self._context ^= contexts.WIKILINK_TITLE
  258. self._context |= contexts.WIKILINK_TEXT
  259. self._write(tokens.WikilinkSeparator())
  260. def _handle_wikilink_end(self):
  261. """Handle the end of a wikilink at the head of the string."""
  262. if self._context & contexts.WIKILINK_TITLE:
  263. self._verify_safe(["\n", "{", "}", "[", "]"])
  264. self._head += 1
  265. return self._pop()
  266. def _parse_heading(self):
  267. """Parse a section heading at the head of the wikicode string."""
  268. self._global |= contexts.GL_HEADING
  269. reset = self._head
  270. self._head += 1
  271. best = 1
  272. while self._read() == "=":
  273. best += 1
  274. self._head += 1
  275. context = contexts.HEADING_LEVEL_1 << min(best - 1, 5)
  276. try:
  277. title, level = self._parse(context)
  278. except BadRoute:
  279. self._head = reset + best - 1
  280. self._write_text("=" * best)
  281. else:
  282. self._write(tokens.HeadingStart(level=level))
  283. if level < best:
  284. self._write_text("=" * (best - level))
  285. self._write_all(title)
  286. self._write(tokens.HeadingEnd())
  287. finally:
  288. self._global ^= contexts.GL_HEADING
  289. def _handle_heading_end(self):
  290. """Handle the end of a section heading at the head of the string."""
  291. reset = self._head
  292. self._head += 1
  293. best = 1
  294. while self._read() == "=":
  295. best += 1
  296. self._head += 1
  297. current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
  298. level = min(current, min(best, 6))
  299. try:
  300. after, after_level = self._parse(self._context)
  301. except BadRoute:
  302. if level < best:
  303. self._write_text("=" * (best - level))
  304. self._head = reset + best - 1
  305. return self._pop(), level
  306. else:
  307. self._write_text("=" * best)
  308. self._write_all(after)
  309. return self._pop(), after_level
  310. def _really_parse_entity(self):
  311. """Actually parse an HTML entity and ensure that it is valid."""
  312. self._write(tokens.HTMLEntityStart())
  313. self._head += 1
  314. this = self._read(strict=True)
  315. if this == "#":
  316. numeric = True
  317. self._write(tokens.HTMLEntityNumeric())
  318. self._head += 1
  319. this = self._read(strict=True)
  320. if this[0].lower() == "x":
  321. hexadecimal = True
  322. self._write(tokens.HTMLEntityHex(char=this[0]))
  323. this = this[1:]
  324. if not this:
  325. self._fail_route()
  326. else:
  327. hexadecimal = False
  328. else:
  329. numeric = hexadecimal = False
  330. valid = string.hexdigits if hexadecimal else string.digits
  331. if not numeric and not hexadecimal:
  332. valid += string.ascii_letters
  333. if not all([char in valid for char in this]):
  334. self._fail_route()
  335. self._head += 1
  336. if self._read() != ";":
  337. self._fail_route()
  338. if numeric:
  339. test = int(this, 16) if hexadecimal else int(this)
  340. if test < 1 or test > 0x10FFFF:
  341. self._fail_route()
  342. else:
  343. if this not in htmlentities.entitydefs:
  344. self._fail_route()
  345. self._write(tokens.Text(text=this))
  346. self._write(tokens.HTMLEntityEnd())
  347. def _parse_entity(self):
  348. """Parse an HTML entity at the head of the wikicode string."""
  349. reset = self._head
  350. self._push()
  351. try:
  352. self._really_parse_entity()
  353. except BadRoute:
  354. self._head = reset
  355. self._write_text(self._read())
  356. else:
  357. self._write_all(self._pop())
  358. def _parse_comment(self):
  359. """Parse an HTML comment at the head of the wikicode string."""
  360. self._head += 4
  361. reset = self._head - 1
  362. try:
  363. comment = self._parse(contexts.COMMENT)
  364. except BadRoute:
  365. self._head = reset
  366. self._write_text("<!--")
  367. else:
  368. self._write(tokens.CommentStart())
  369. self._write_all(comment)
  370. self._write(tokens.CommentEnd())
  371. self._head += 2
  372. def _parse_tag(self):
  373. """Parse an HTML tag at the head of the wikicode string."""
  374. self._head += 1
  375. reset = self._head
  376. self._push()
  377. try:
  378. t_open, type_, self_close, o_pad = self._parse(contexts.TAG_OPEN)
  379. if not self_close:
  380. t_body = self._parse(contexts.TAG_BODY)
  381. t_close, c_pad = self._parse(contexts.TAG_CLOSE)
  382. except BadRoute:
  383. self._head = reset
  384. self._pop()
  385. self._write_text("<")
  386. else:
  387. self._pop()
  388. self._write(tokens.TagOpenOpen(type=type_, showtag=False))
  389. self._write_all(t_open)
  390. if self_close:
  391. self._write(tokens.TagCloseSelfclose(padding=o_pad))
  392. else:
  393. self._write(tokens.TagCloseOpen(padding=o_pad))
  394. self._write_all(t_body)
  395. self._write(tokens.TagOpenClose())
  396. self._write_all(t_close)
  397. self._write(tokens.TagCloseClose(padding=c_pad))
  398. def _handle_attribute(self):
  399. if not self._context & contexts.TAG_ATTR:
  400. ## check name is valid
  401. def _handle_attribute_name(self):
  402. ## check if next character is a ", if so, set TAG_ATTR_BODY_QUOTED
  403. pass
  404. def _handle_quoted_attribute_close(self):
  405. pass
  406. def _handle_tag_close_open(self):
  407. pass ## .padding
  408. def _handle_tag_selfclose(self):
  409. pass ## .padding
  410. def _handle_tag_close_open(self):
  411. pass
  412. def _handle_tag_close_close(self):
  413. ## check that the closing name is the same as the opening name
  414. pass ## .padding
  415. def _parse(self, context=0):
  416. """Parse the wikicode string, using *context* for when to stop."""
  417. self._push(context)
  418. while True:
  419. this = self._read()
  420. if this not in self.MARKERS:
  421. self._write_text(this)
  422. self._head += 1
  423. continue
  424. if this is self.END:
  425. fail = (contexts.TEMPLATE | contexts.ARGUMENT |
  426. contexts.WIKILINK | contexts.HEADING |
  427. contexts.COMMENT | contexts.TAG)
  428. if self._context & contexts.TEMPLATE_PARAM_KEY:
  429. self._pop()
  430. if self._context & fail:
  431. self._fail_route()
  432. return self._pop()
  433. next = self._read(1)
  434. if self._context & contexts.COMMENT:
  435. if this == next == "-" and self._read(2) == ">":
  436. return self._pop()
  437. else:
  438. self._write_text(this)
  439. elif this == next == "{":
  440. self._parse_template_or_argument()
  441. elif this == "|" and self._context & contexts.TEMPLATE:
  442. self._handle_template_param()
  443. elif this == "=" and self._context & contexts.TEMPLATE_PARAM_KEY:
  444. self._handle_template_param_value()
  445. elif this == next == "}" and self._context & contexts.TEMPLATE:
  446. return self._handle_template_end()
  447. elif this == "|" and self._context & contexts.ARGUMENT_NAME:
  448. self._handle_argument_separator()
  449. elif this == next == "}" and self._context & contexts.ARGUMENT:
  450. if self._read(2) == "}":
  451. return self._handle_argument_end()
  452. else:
  453. self._write_text("}")
  454. elif this == next == "[":
  455. if not self._context & contexts.WIKILINK_TITLE:
  456. self._parse_wikilink()
  457. else:
  458. self._write_text("[")
  459. elif this == "|" and self._context & contexts.WIKILINK_TITLE:
  460. self._handle_wikilink_separator()
  461. elif this == next == "]" and self._context & contexts.WIKILINK:
  462. return self._handle_wikilink_end()
  463. elif this == "=" and not self._global & contexts.GL_HEADING:
  464. if self._read(-1) in ("\n", self.START):
  465. self._parse_heading()
  466. else:
  467. self._write_text("=")
  468. elif this == "=" and self._context & contexts.HEADING:
  469. return self._handle_heading_end()
  470. elif this == "\n" and self._context & contexts.HEADING:
  471. self._fail_route()
  472. elif this == "&":
  473. self._parse_entity()
  474. elif this == "<" and next == "!":
  475. if self._read(2) == self._read(3) == "-":
  476. self._parse_comment()
  477. else:
  478. self._write_text(this)
  479. elif this == "<" and not self._context & (contexts.TAG ^ contexts.TAG_BODY):
  480. self._parse_tag()
  481. elif this == " " and (self._context & contexts.TAG_OPEN and not
  482. self._context & contexts.TAG_ATTR_BODY_QUOTED):
  483. self._handle_attribute()
  484. elif this == "=" and self._context & contexts.TAG_ATTR_NAME:
  485. self._handle_attribute_name()
  486. elif this == '"' and self._context & contexts.TAG_ATTR_BODY_QUOTED:
  487. self._handle_quoted_attribute_close()
  488. elif this == "\n" and (self._context & contexts.TAG_OPEN and not
  489. self._context & contexts.TAG_ATTR_BODY_QUOTED):
  490. self._fail_route()
  491. elif this == ">" and (self._context & contexts.TAG_ATTR_OPEN and not
  492. self._context & contexts.TAG_ATTR_BODY_QUOTED):
  493. return self._handle_tag_close_open()
  494. elif this == "/" and next == ">" and (
  495. self._context & contexts.TAG_ATTR_OPEN and not
  496. self._context & contexts.TAG_ATTR_BODY_QUOTED):
  497. return self._handle_tag_selfclose()
  498. elif this == "<" and next == "/" and self._context & contexts.TAG_BODY:
  499. self._handle_tag_close_open()
  500. elif this == ">" and self._context & contexts.TAG_CLOSE:
  501. self._handle_tag_close_close()
  502. else:
  503. self._write_text(this)
  504. self._head += 1
  505. def tokenize(self, text):
  506. """Build a list of tokens from a string of wikicode and return it."""
  507. split = self.regex.split(text)
  508. self._text = [segment for segment in split if segment]
  509. return self._parse()