KLL Compiler
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

parser.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2008/2013 Andrey Vlasovskikh
  3. # Small Python 3 modifications by Jacob Alexander 2014
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining
  6. # a copy of this software and associated documentation files (the
  7. # "Software"), to deal in the Software without restriction, including
  8. # without limitation the rights to use, copy, modify, merge, publish,
  9. # distribute, sublicense, and/or sell copies of the Software, and to
  10. # permit persons to whom the Software is furnished to do so, subject to
  11. # the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included
  14. # in all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  20. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  21. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  22. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. """A recurisve descent parser library based on functional combinators.
  24. Basic combinators are taken from Harrison's book ["Introduction to Functional
  25. Programming"][1] and translated from ML into Python. See also [a Russian
  26. translation of the book][2].
  27. [1]: http://www.cl.cam.ac.uk/teaching/Lectures/funprog-jrh-1996/
  28. [2]: http://code.google.com/p/funprog-ru/
  29. A parser `p` is represented by a function of type:
  30. p :: Sequence(a), State -> (b, State)
  31. that takes as its input a sequence of tokens of arbitrary type `a` and a
  32. current parsing state and return a pair of a parsed token of arbitrary type
  33. `b` and the new parsing state.
  34. The parsing state includes the current position in the sequence being parsed and
  35. the position of the rightmost token that has been consumed while parsing.
  36. Parser functions are wrapped into an object of the class `Parser`. This class
  37. implements custom operators `+` for sequential composition of parsers, `|` for
  38. choice composition, `>>` for transforming the result of parsing. The method
  39. `Parser.parse` provides an easier way for invoking a parser hiding details
  40. related to a parser state:
  41. Parser.parse :: Parser(a, b), Sequence(a) -> b
  42. Altough this module is able to deal with a sequences of any kind of objects, the
  43. recommended way of using it is applying a parser to a `Sequence(Token)`.
  44. `Token` objects are produced by a regexp-based tokenizer defined in
  45. `funcparserlib.lexer`. By using it this way you get more readable parsing error
  46. messages (as `Token` objects contain their position in the source file) and good
  47. separation of lexical and syntactic levels of the grammar. See examples for more
  48. info.
  49. Debug messages are emitted via a `logging.Logger` object named
  50. `"funcparserlib"`.
  51. """
  52. __all__ = [
  53. 'some', 'a', 'many', 'pure', 'finished', 'maybe', 'skip', 'oneplus',
  54. 'forward_decl', 'NoParseError',
  55. ]
  56. import logging
  57. log = logging.getLogger('funcparserlib')
  58. debug = False
  59. class Parser(object):
  60. """A wrapper around a parser function that defines some operators for parser
  61. composition.
  62. """
  63. def __init__(self, p):
  64. """Wraps a parser function p into an object."""
  65. self.define(p)
  66. def named(self, name):
  67. """Specifies the name of the parser for more readable parsing log."""
  68. self.name = name
  69. return self
  70. def define(self, p):
  71. """Defines a parser wrapped into this object."""
  72. f = getattr(p, 'run', p)
  73. if debug:
  74. setattr(self, '_run', f)
  75. else:
  76. setattr(self, 'run', f)
  77. self.named(getattr(p, 'name', p.__doc__))
  78. def run(self, tokens, s):
  79. """Sequence(a), State -> (b, State)
  80. Runs a parser wrapped into this object.
  81. """
  82. if debug:
  83. log.debug('trying %s' % self.name)
  84. return self._run(tokens, s)
  85. def _run(self, tokens, s):
  86. raise NotImplementedError('you must define() a parser')
  87. def parse(self, tokens):
  88. """Sequence(a) -> b
  89. Applies the parser to a sequence of tokens producing a parsing result.
  90. It provides a way to invoke a parser hiding details related to the
  91. parser state. Also it makes error messages more readable by specifying
  92. the position of the rightmost token that has been reached.
  93. """
  94. try:
  95. (tree, _) = self.run(tokens, State())
  96. return tree
  97. except NoParseError as e:
  98. max = e.state.max
  99. if len(tokens) > max:
  100. tok = tokens[max]
  101. else:
  102. tok = '<EOF>'
  103. raise NoParseError('%s: %s' % (e.msg, tok), e.state)
  104. def __add__(self, other):
  105. """Parser(a, b), Parser(a, c) -> Parser(a, _Tuple(b, c))
  106. A sequential composition of parsers.
  107. NOTE: The real type of the parsed value isn't always such as specified.
  108. Here we use dynamic typing for ignoring the tokens that are of no
  109. interest to the user. Also we merge parsing results into a single _Tuple
  110. unless the user explicitely prevents it. See also skip and >>
  111. combinators.
  112. """
  113. def magic(v1, v2):
  114. vs = [v for v in [v1, v2] if not isinstance(v, _Ignored)]
  115. if len(vs) == 1:
  116. return vs[0]
  117. elif len(vs) == 2:
  118. if isinstance(vs[0], _Tuple):
  119. return _Tuple(v1 + (v2,))
  120. else:
  121. return _Tuple(vs)
  122. else:
  123. return _Ignored(())
  124. @Parser
  125. def _add(tokens, s):
  126. (v1, s2) = self.run(tokens, s)
  127. (v2, s3) = other.run(tokens, s2)
  128. return magic(v1, v2), s3
  129. # or in terms of bind and pure:
  130. # _add = self.bind(lambda x: other.bind(lambda y: pure(magic(x, y))))
  131. _add.name = '(%s , %s)' % (self.name, other.name)
  132. return _add
  133. def __or__(self, other):
  134. """Parser(a, b), Parser(a, c) -> Parser(a, b or c)
  135. A choice composition of two parsers.
  136. NOTE: Here we are not providing the exact type of the result. In a
  137. statically typed langage something like Either b c could be used. See
  138. also + combinator.
  139. """
  140. @Parser
  141. def _or(tokens, s):
  142. try:
  143. return self.run(tokens, s)
  144. except NoParseError as e:
  145. return other.run(tokens, State(s.pos, e.state.max))
  146. _or.name = '(%s | %s)' % (self.name, other.name)
  147. return _or
  148. def __rshift__(self, f):
  149. """Parser(a, b), (b -> c) -> Parser(a, c)
  150. Given a function from b to c, transforms a parser of b into a parser of
  151. c. It is useful for transorming a parser value into another value for
  152. making it a part of a parse tree or an AST.
  153. This combinator may be thought of as a functor from b -> c to Parser(a,
  154. b) -> Parser(a, c).
  155. """
  156. @Parser
  157. def _shift(tokens, s):
  158. (v, s2) = self.run(tokens, s)
  159. return f(v), s2
  160. # or in terms of bind and pure:
  161. # _shift = self.bind(lambda x: pure(f(x)))
  162. _shift.name = '(%s)' % (self.name,)
  163. return _shift
  164. def bind(self, f):
  165. """Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c)
  166. NOTE: A monadic bind function. It is used internally to implement other
  167. combinators. Functions bind and pure make the Parser a Monad.
  168. """
  169. @Parser
  170. def _bind(tokens, s):
  171. (v, s2) = self.run(tokens, s)
  172. return f(v).run(tokens, s2)
  173. _bind.name = '(%s >>=)' % (self.name,)
  174. return _bind
  175. class State(object):
  176. """A parsing state that is maintained basically for error reporting.
  177. It consists of the current position pos in the sequence being parsed and
  178. the position max of the rightmost token that has been consumed while
  179. parsing.
  180. """
  181. def __init__(self, pos=0, max=0):
  182. self.pos = pos
  183. self.max = max
  184. def __str__(self):
  185. return unicode((self.pos, self.max))
  186. def __repr__(self):
  187. return 'State(%r, %r)' % (self.pos, self.max)
  188. class NoParseError(Exception):
  189. def __init__(self, msg='', state=None):
  190. self.msg = msg
  191. self.state = state
  192. def __str__(self):
  193. return self.msg
  194. class _Tuple(tuple):
  195. pass
  196. class _Ignored(object):
  197. def __init__(self, value):
  198. self.value = value
  199. def __repr__(self):
  200. return '_Ignored(%s)' % repr(self.value)
  201. @Parser
  202. def finished(tokens, s):
  203. """Parser(a, None)
  204. Throws an exception if any tokens are left in the input unparsed.
  205. """
  206. if s.pos >= len(tokens):
  207. return None, s
  208. else:
  209. raise NoParseError('should have reached <EOF>', s)
  210. finished.name = 'finished'
  211. def many(p):
  212. """Parser(a, b) -> Parser(a, [b])
  213. Returns a parser that infinitely applies the parser p to the input sequence
  214. of tokens while it successfully parsers them. The resulting parser returns a
  215. list of parsed values.
  216. """
  217. @Parser
  218. def _many(tokens, s):
  219. """Iterative implementation preventing the stack overflow."""
  220. res = []
  221. try:
  222. while True:
  223. (v, s) = p.run(tokens, s)
  224. res.append(v)
  225. except NoParseError as e:
  226. return res, State(s.pos, e.state.max)
  227. _many.name = '{ %s }' % p.name
  228. return _many
  229. def some(pred):
  230. """(a -> bool) -> Parser(a, a)
  231. Returns a parser that parses a token if it satisfies a predicate pred.
  232. """
  233. @Parser
  234. def _some(tokens, s):
  235. if s.pos >= len(tokens):
  236. raise NoParseError('no tokens left in the stream', s)
  237. else:
  238. t = tokens[s.pos]
  239. if pred(t):
  240. pos = s.pos + 1
  241. s2 = State(pos, max(pos, s.max))
  242. if debug:
  243. log.debug('*matched* "%s", new state = %s' % (t, s2))
  244. return t, s2
  245. else:
  246. if debug:
  247. log.debug('failed "%s", state = %s' % (t, s))
  248. raise NoParseError('got unexpected token', s)
  249. _some.name = '(some)'
  250. return _some
  251. def a(value):
  252. """Eq(a) -> Parser(a, a)
  253. Returns a parser that parses a token that is equal to the value value.
  254. """
  255. name = getattr(value, 'name', value)
  256. return some(lambda t: t == value).named('(a "%s")' % (name,))
  257. def pure(x):
  258. @Parser
  259. def _pure(_, s):
  260. return x, s
  261. _pure.name = '(pure %r)' % (x,)
  262. return _pure
  263. def maybe(p):
  264. """Parser(a, b) -> Parser(a, b or None)
  265. Returns a parser that retuns None if parsing fails.
  266. NOTE: In a statically typed language, the type Maybe b could be more
  267. approprieate.
  268. """
  269. return (p | pure(None)).named('[ %s ]' % (p.name,))
  270. def skip(p):
  271. """Parser(a, b) -> Parser(a, _Ignored(b))
  272. Returns a parser which results are ignored by the combinator +. It is useful
  273. for throwing away elements of concrete syntax (e. g. ",", ";").
  274. """
  275. return p >> _Ignored
  276. def oneplus(p):
  277. """Parser(a, b) -> Parser(a, [b])
  278. Returns a parser that applies the parser p one or more times.
  279. """
  280. q = p + many(p) >> (lambda x: [x[0]] + x[1])
  281. return q.named('(%s , { %s })' % (p.name, p.name))
  282. def with_forward_decls(suspension):
  283. """(None -> Parser(a, b)) -> Parser(a, b)
  284. Returns a parser that computes itself lazily as a result of the suspension
  285. provided. It is needed when some parsers contain forward references to
  286. parsers defined later and such references are cyclic. See examples for more
  287. details.
  288. """
  289. @Parser
  290. def f(tokens, s):
  291. return suspension().run(tokens, s)
  292. return f
  293. def forward_decl():
  294. """None -> Parser(?, ?)
  295. Returns an undefined parser that can be used as a forward declaration. You
  296. will be able to define() it when all the parsers it depends on are
  297. available.
  298. """
  299. @Parser
  300. def f(tokens, s):
  301. raise NotImplementedError('you must define() a forward_decl somewhere')
  302. return f
  303. if __name__ == '__main__':
  304. import doctest
  305. doctest.testmod()