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.
 
 
 
 

96 lines
3.9 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2016 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. """
  23. This package contains the actual wikicode parser, split up into two main
  24. modules: the :mod:`.tokenizer` and the :mod:`.builder`. This module joins them
  25. together into one interface.
  26. """
  27. class ParserError(Exception):
  28. """Exception raised when an internal error occurs while parsing.
  29. This does not mean that the wikicode was invalid, because invalid markup
  30. should still be parsed correctly. This means that the parser caught itself
  31. with an impossible internal state and is bailing out before other problems
  32. can happen. Its appearance indicates a bug.
  33. """
  34. def __init__(self, extra):
  35. msg = "This is a bug and should be reported. Info: {}.".format(extra)
  36. super(ParserError, self).__init__(msg)
  37. from .builder import Builder
  38. try:
  39. from ._tokenizer import CTokenizer
  40. use_c = True
  41. except ImportError:
  42. from .tokenizer import Tokenizer
  43. CTokenizer = None
  44. use_c = False
  45. __all__ = ["use_c", "Parser", "ParserError"]
  46. class Parser(object):
  47. """Represents a parser for wikicode.
  48. Actual parsing is a two-step process: first, the text is split up into a
  49. series of tokens by the :class:`.Tokenizer`, and then the tokens are
  50. converted into trees of :class:`.Wikicode` objects and :class:`.Node`\ s by
  51. the :class:`.Builder`.
  52. Instances of this class or its dependents (:class:`.Tokenizer` and
  53. :class:`.Builder`) should not be shared between threads. :meth:`parse` can
  54. be called multiple times as long as it is not done concurrently. In
  55. general, there is no need to do this because parsing should be done through
  56. :func:`mwparserfromhell.parse`, which creates a new :class:`.Parser` object
  57. as necessary.
  58. """
  59. def __init__(self):
  60. if use_c and CTokenizer:
  61. self._tokenizer = CTokenizer()
  62. else:
  63. from .tokenizer import Tokenizer
  64. self._tokenizer = Tokenizer()
  65. self._builder = Builder()
  66. def parse(self, text, context=0, skip_style_tags=False):
  67. """Parse *text*, returning a :class:`.Wikicode` object tree.
  68. If given, *context* will be passed as a starting context to the parser.
  69. This is helpful when this function is used inside node attribute
  70. setters. For example, :class:`.ExternalLink`\ 's
  71. :attr:`~.ExternalLink.url` setter sets *context* to
  72. :mod:`contexts.EXT_LINK_URI <.contexts>` to prevent the URL itself
  73. from becoming an :class:`.ExternalLink`.
  74. If *skip_style_tags* is ``True``, then ``''`` and ``'''`` will not be
  75. parsed, but instead will be treated as plain text.
  76. If there is an internal error while parsing, :exc:`.ParserError` will
  77. be raised.
  78. """
  79. tokens = self._tokenizer.tokenize(text, context, skip_style_tags)
  80. code = self._builder.build(tokens)
  81. return code