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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2008/2013 Andrey Vlasovskikh
  3. # Modifications by Jacob Alexander 2014, 2016
  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. def Parser_debug(enable, stream=None):
  60. '''
  61. Enables/Disables debug logger for parser.py
  62. NOTE: This is not really multi-thread friendly
  63. @param stream: StringIO stream to use
  64. @param enable: Enable/disable debug stream
  65. '''
  66. global debug
  67. debug = enable
  68. if enable:
  69. logging.raiseExceptions = False
  70. log.setLevel(logging.DEBUG)
  71. ch = logging.StreamHandler(stream)
  72. log.addHandler(ch)
  73. class Parser(object):
  74. """A wrapper around a parser function that defines some operators for parser
  75. composition.
  76. """
  77. def __init__(self, p):
  78. """Wraps a parser function p into an object."""
  79. self.define(p)
  80. def named(self, name):
  81. """Specifies the name of the parser for more readable parsing log."""
  82. self.name = name
  83. return self
  84. def define(self, p):
  85. """Defines a parser wrapped into this object."""
  86. f = getattr(p, 'run', p)
  87. if debug:
  88. setattr(self, '_run', f)
  89. else:
  90. setattr(self, 'run', f)
  91. self.named(getattr(p, 'name', p.__doc__))
  92. def run(self, tokens, s):
  93. """Sequence(a), State -> (b, State)
  94. Runs a parser wrapped into this object.
  95. """
  96. if debug:
  97. # Truncate at 500 characters
  98. # Any longer isn't that useful and makes the output hard to read
  99. output = 'trying %s' % self.name
  100. if len( output ) > 500:
  101. output = output[:250] + ' ... [truncated] ... ' + output[-250:]
  102. log.debug(output)
  103. return self._run(tokens, s)
  104. def _run(self, tokens, s):
  105. raise NotImplementedError('you must define() a parser')
  106. def parse(self, tokens):
  107. """Sequence(a) -> b
  108. Applies the parser to a sequence of tokens producing a parsing result.
  109. It provides a way to invoke a parser hiding details related to the
  110. parser state. Also it makes error messages more readable by specifying
  111. the position of the rightmost token that has been reached.
  112. """
  113. try:
  114. (tree, _) = self.run(tokens, State())
  115. return tree
  116. except NoParseError as e:
  117. max = e.state.max
  118. if len(tokens) > max:
  119. tok = tokens[max]
  120. else:
  121. tok = '<EOF>'
  122. raise NoParseError('%s: %s' % (e.msg, tok), e.state)
  123. def __add__(self, other):
  124. """Parser(a, b), Parser(a, c) -> Parser(a, _Tuple(b, c))
  125. A sequential composition of parsers.
  126. NOTE: The real type of the parsed value isn't always such as specified.
  127. Here we use dynamic typing for ignoring the tokens that are of no
  128. interest to the user. Also we merge parsing results into a single _Tuple
  129. unless the user explicitely prevents it. See also skip and >>
  130. combinators.
  131. """
  132. def magic(v1, v2):
  133. vs = [v for v in [v1, v2] if not isinstance(v, _Ignored)]
  134. if len(vs) == 1:
  135. return vs[0]
  136. elif len(vs) == 2:
  137. if isinstance(vs[0], _Tuple):
  138. return _Tuple(v1 + (v2,))
  139. else:
  140. return _Tuple(vs)
  141. else:
  142. return _Ignored(())
  143. @Parser
  144. def _add(tokens, s):
  145. (v1, s2) = self.run(tokens, s)
  146. (v2, s3) = other.run(tokens, s2)
  147. return magic(v1, v2), s3
  148. # or in terms of bind and pure:
  149. # _add = self.bind(lambda x: other.bind(lambda y: pure(magic(x, y))))
  150. _add.name = '(%s , %s)' % (self.name, other.name)
  151. return _add
  152. def __or__(self, other):
  153. """Parser(a, b), Parser(a, c) -> Parser(a, b or c)
  154. A choice composition of two parsers.
  155. NOTE: Here we are not providing the exact type of the result. In a
  156. statically typed langage something like Either b c could be used. See
  157. also + combinator.
  158. """
  159. @Parser
  160. def _or(tokens, s):
  161. try:
  162. return self.run(tokens, s)
  163. except NoParseError as e:
  164. return other.run(tokens, State(s.pos, e.state.max))
  165. _or.name = '(%s | %s)' % (self.name, other.name)
  166. return _or
  167. def __rshift__(self, f):
  168. """Parser(a, b), (b -> c) -> Parser(a, c)
  169. Given a function from b to c, transforms a parser of b into a parser of
  170. c. It is useful for transorming a parser value into another value for
  171. making it a part of a parse tree or an AST.
  172. This combinator may be thought of as a functor from b -> c to Parser(a,
  173. b) -> Parser(a, c).
  174. """
  175. @Parser
  176. def _shift(tokens, s):
  177. (v, s2) = self.run(tokens, s)
  178. return f(v), s2
  179. # or in terms of bind and pure:
  180. # _shift = self.bind(lambda x: pure(f(x)))
  181. _shift.name = '(%s)' % (self.name,)
  182. return _shift
  183. def bind(self, f):
  184. """Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c)
  185. NOTE: A monadic bind function. It is used internally to implement other
  186. combinators. Functions bind and pure make the Parser a Monad.
  187. """
  188. @Parser
  189. def _bind(tokens, s):
  190. (v, s2) = self.run(tokens, s)
  191. return f(v).run(tokens, s2)
  192. _bind.name = '(%s >>=)' % (self.name,)
  193. return _bind
  194. class State(object):
  195. """A parsing state that is maintained basically for error reporting.
  196. It consists of the current position pos in the sequence being parsed and
  197. the position max of the rightmost token that has been consumed while
  198. parsing.
  199. """
  200. def __init__(self, pos=0, max=0):
  201. self.pos = pos
  202. self.max = max
  203. def __str__(self):
  204. return str((self.pos, self.max))
  205. def __repr__(self):
  206. return 'State(%r, %r)' % (self.pos, self.max)
  207. class NoParseError(Exception):
  208. def __init__(self, msg='', state=None):
  209. self.msg = msg
  210. self.state = state
  211. def __str__(self):
  212. return self.msg
  213. class _Tuple(tuple):
  214. pass
  215. class _Ignored(object):
  216. def __init__(self, value):
  217. self.value = value
  218. def __repr__(self):
  219. return '_Ignored(%s)' % repr(self.value)
  220. @Parser
  221. def finished(tokens, s):
  222. """Parser(a, None)
  223. Throws an exception if any tokens are left in the input unparsed.
  224. """
  225. if s.pos >= len(tokens):
  226. return None, s
  227. else:
  228. raise NoParseError('should have reached <EOF>', s)
  229. finished.name = 'finished'
  230. def many(p):
  231. """Parser(a, b) -> Parser(a, [b])
  232. Returns a parser that infinitely applies the parser p to the input sequence
  233. of tokens while it successfully parsers them. The resulting parser returns a
  234. list of parsed values.
  235. """
  236. @Parser
  237. def _many(tokens, s):
  238. """Iterative implementation preventing the stack overflow."""
  239. res = []
  240. try:
  241. while True:
  242. (v, s) = p.run(tokens, s)
  243. res.append(v)
  244. except NoParseError as e:
  245. return res, State(s.pos, e.state.max)
  246. _many.name = '{ %s }' % p.name
  247. return _many
  248. def some(pred):
  249. """(a -> bool) -> Parser(a, a)
  250. Returns a parser that parses a token if it satisfies a predicate pred.
  251. """
  252. @Parser
  253. def _some(tokens, s):
  254. if s.pos >= len(tokens):
  255. raise NoParseError('no tokens left in the stream', s)
  256. else:
  257. t = tokens[s.pos]
  258. if pred(t):
  259. pos = s.pos + 1
  260. s2 = State(pos, max(pos, s.max))
  261. if debug:
  262. log.debug('*matched* "%s", new state = %s' % (t, s2))
  263. return t, s2
  264. else:
  265. if debug:
  266. log.debug('failed "%s", state = %s' % (t, s))
  267. raise NoParseError('got unexpected token', s)
  268. _some.name = '(some)'
  269. return _some
  270. def a(value):
  271. """Eq(a) -> Parser(a, a)
  272. Returns a parser that parses a token that is equal to the value value.
  273. """
  274. name = getattr(value, 'name', value)
  275. return some(lambda t: t == value).named('(a "%s")' % (name,))
  276. def pure(x):
  277. @Parser
  278. def _pure(_, s):
  279. return x, s
  280. _pure.name = '(pure %r)' % (x,)
  281. return _pure
  282. def maybe(p):
  283. """Parser(a, b) -> Parser(a, b or None)
  284. Returns a parser that retuns None if parsing fails.
  285. NOTE: In a statically typed language, the type Maybe b could be more
  286. approprieate.
  287. """
  288. return (p | pure(None)).named('[ %s ]' % (p.name,))
  289. def skip(p):
  290. """Parser(a, b) -> Parser(a, _Ignored(b))
  291. Returns a parser which results are ignored by the combinator +. It is useful
  292. for throwing away elements of concrete syntax (e. g. ",", ";").
  293. """
  294. return p >> _Ignored
  295. def oneplus(p):
  296. """Parser(a, b) -> Parser(a, [b])
  297. Returns a parser that applies the parser p one or more times.
  298. """
  299. q = p + many(p) >> (lambda x: [x[0]] + x[1])
  300. return q.named('(%s , { %s })' % (p.name, p.name))
  301. def with_forward_decls(suspension):
  302. """(None -> Parser(a, b)) -> Parser(a, b)
  303. Returns a parser that computes itself lazily as a result of the suspension
  304. provided. It is needed when some parsers contain forward references to
  305. parsers defined later and such references are cyclic. See examples for more
  306. details.
  307. """
  308. @Parser
  309. def f(tokens, s):
  310. return suspension().run(tokens, s)
  311. return f
  312. def forward_decl():
  313. """None -> Parser(?, ?)
  314. Returns an undefined parser that can be used as a forward declaration. You
  315. will be able to define() it when all the parsers it depends on are
  316. available.
  317. """
  318. @Parser
  319. def f(tokens, s):
  320. raise NotImplementedError('you must define() a forward_decl somewhere')
  321. return f
  322. if __name__ == '__main__':
  323. import doctest
  324. doctest.testmod()