1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2008/2013 Andrey Vlasovskikh
4 # Small Python 3 modifications by Jacob Alexander 2014
6 # Permission is hereby granted, free of charge, to any person obtaining
7 # a copy of this software and associated documentation files (the
8 # "Software"), to deal in the Software without restriction, including
9 # without limitation the rights to use, copy, modify, merge, publish,
10 # distribute, sublicense, and/or sell copies of the Software, and to
11 # permit persons to whom the Software is furnished to do so, subject to
12 # the following conditions:
14 # The above copyright notice and this permission notice shall be included
15 # in all copies or substantial portions of the Software.
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 """A recurisve descent parser library based on functional combinators.
27 Basic combinators are taken from Harrison's book ["Introduction to Functional
28 Programming"][1] and translated from ML into Python. See also [a Russian
29 translation of the book][2].
31 [1]: http://www.cl.cam.ac.uk/teaching/Lectures/funprog-jrh-1996/
32 [2]: http://code.google.com/p/funprog-ru/
34 A parser `p` is represented by a function of type:
36 p :: Sequence(a), State -> (b, State)
38 that takes as its input a sequence of tokens of arbitrary type `a` and a
39 current parsing state and return a pair of a parsed token of arbitrary type
40 `b` and the new parsing state.
42 The parsing state includes the current position in the sequence being parsed and
43 the position of the rightmost token that has been consumed while parsing.
45 Parser functions are wrapped into an object of the class `Parser`. This class
46 implements custom operators `+` for sequential composition of parsers, `|` for
47 choice composition, `>>` for transforming the result of parsing. The method
48 `Parser.parse` provides an easier way for invoking a parser hiding details
49 related to a parser state:
51 Parser.parse :: Parser(a, b), Sequence(a) -> b
53 Altough this module is able to deal with a sequences of any kind of objects, the
54 recommended way of using it is applying a parser to a `Sequence(Token)`.
55 `Token` objects are produced by a regexp-based tokenizer defined in
56 `funcparserlib.lexer`. By using it this way you get more readable parsing error
57 messages (as `Token` objects contain their position in the source file) and good
58 separation of lexical and syntactic levels of the grammar. See examples for more
61 Debug messages are emitted via a `logging.Logger` object named
66 'some', 'a', 'many', 'pure', 'finished', 'maybe', 'skip', 'oneplus',
67 'forward_decl', 'NoParseError',
72 log = logging.getLogger('funcparserlib')
78 """A wrapper around a parser function that defines some operators for parser
82 def __init__(self, p):
83 """Wraps a parser function p into an object."""
86 def named(self, name):
87 """Specifies the name of the parser for more readable parsing log."""
92 """Defines a parser wrapped into this object."""
93 f = getattr(p, 'run', p)
95 setattr(self, '_run', f)
97 setattr(self, 'run', f)
98 self.named(getattr(p, 'name', p.__doc__))
100 def run(self, tokens, s):
101 """Sequence(a), State -> (b, State)
103 Runs a parser wrapped into this object.
106 log.debug(u'trying %s' % self.name)
107 return self._run(tokens, s)
109 def _run(self, tokens, s):
110 raise NotImplementedError(u'you must define() a parser')
112 def parse(self, tokens):
115 Applies the parser to a sequence of tokens producing a parsing result.
117 It provides a way to invoke a parser hiding details related to the
118 parser state. Also it makes error messages more readable by specifying
119 the position of the rightmost token that has been reached.
122 (tree, _) = self.run(tokens, State())
124 except NoParseError as e:
126 if len(tokens) > max:
130 raise NoParseError(u'%s: %s' % (e.msg, tok), e.state)
132 def __add__(self, other):
133 """Parser(a, b), Parser(a, c) -> Parser(a, _Tuple(b, c))
135 A sequential composition of parsers.
137 NOTE: The real type of the parsed value isn't always such as specified.
138 Here we use dynamic typing for ignoring the tokens that are of no
139 interest to the user. Also we merge parsing results into a single _Tuple
140 unless the user explicitely prevents it. See also skip and >>
145 vs = [v for v in [v1, v2] if not isinstance(v, _Ignored)]
149 if isinstance(vs[0], _Tuple):
150 return _Tuple(v1 + (v2,))
158 (v1, s2) = self.run(tokens, s)
159 (v2, s3) = other.run(tokens, s2)
160 return magic(v1, v2), s3
162 # or in terms of bind and pure:
163 # _add = self.bind(lambda x: other.bind(lambda y: pure(magic(x, y))))
164 _add.name = u'(%s , %s)' % (self.name, other.name)
167 def __or__(self, other):
168 """Parser(a, b), Parser(a, c) -> Parser(a, b or c)
170 A choice composition of two parsers.
172 NOTE: Here we are not providing the exact type of the result. In a
173 statically typed langage something like Either b c could be used. See
180 return self.run(tokens, s)
181 except NoParseError as e:
182 return other.run(tokens, State(s.pos, e.state.max))
184 _or.name = u'(%s | %s)' % (self.name, other.name)
187 def __rshift__(self, f):
188 """Parser(a, b), (b -> c) -> Parser(a, c)
190 Given a function from b to c, transforms a parser of b into a parser of
191 c. It is useful for transorming a parser value into another value for
192 making it a part of a parse tree or an AST.
194 This combinator may be thought of as a functor from b -> c to Parser(a,
199 def _shift(tokens, s):
200 (v, s2) = self.run(tokens, s)
203 # or in terms of bind and pure:
204 # _shift = self.bind(lambda x: pure(f(x)))
205 _shift.name = u'(%s)' % (self.name,)
209 """Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c)
211 NOTE: A monadic bind function. It is used internally to implement other
212 combinators. Functions bind and pure make the Parser a Monad.
216 def _bind(tokens, s):
217 (v, s2) = self.run(tokens, s)
218 return f(v).run(tokens, s2)
220 _bind.name = u'(%s >>=)' % (self.name,)
225 """A parsing state that is maintained basically for error reporting.
227 It consists of the current position pos in the sequence being parsed and
228 the position max of the rightmost token that has been consumed while
232 def __init__(self, pos=0, max=0):
237 return unicode((self.pos, self.max))
240 return u'State(%r, %r)' % (self.pos, self.max)
243 class NoParseError(Exception):
244 def __init__(self, msg=u'', state=None):
256 class _Ignored(object):
257 def __init__(self, value):
261 return u'_Ignored(%s)' % repr(self.value)
265 def finished(tokens, s):
268 Throws an exception if any tokens are left in the input unparsed.
270 if s.pos >= len(tokens):
273 raise NoParseError(u'should have reached <EOF>', s)
276 finished.name = u'finished'
280 """Parser(a, b) -> Parser(a, [b])
282 Returns a parser that infinitely applies the parser p to the input sequence
283 of tokens while it successfully parsers them. The resulting parser returns a
284 list of parsed values.
288 def _many(tokens, s):
289 """Iterative implementation preventing the stack overflow."""
293 (v, s) = p.run(tokens, s)
295 except NoParseError as e:
296 return res, State(s.pos, e.state.max)
298 _many.name = u'{ %s }' % p.name
303 """(a -> bool) -> Parser(a, a)
305 Returns a parser that parses a token if it satisfies a predicate pred.
309 def _some(tokens, s):
310 if s.pos >= len(tokens):
311 raise NoParseError(u'no tokens left in the stream', s)
316 s2 = State(pos, max(pos, s.max))
318 log.debug(u'*matched* "%s", new state = %s' % (t, s2))
322 log.debug(u'failed "%s", state = %s' % (t, s))
323 raise NoParseError(u'got unexpected token', s)
325 _some.name = u'(some)'
330 """Eq(a) -> Parser(a, a)
332 Returns a parser that parses a token that is equal to the value value.
334 name = getattr(value, 'name', value)
335 return some(lambda t: t == value).named(u'(a "%s")' % (name,))
343 _pure.name = u'(pure %r)' % (x,)
348 """Parser(a, b) -> Parser(a, b or None)
350 Returns a parser that retuns None if parsing fails.
352 NOTE: In a statically typed language, the type Maybe b could be more
355 return (p | pure(None)).named(u'[ %s ]' % (p.name,))
359 """Parser(a, b) -> Parser(a, _Ignored(b))
361 Returns a parser which results are ignored by the combinator +. It is useful
362 for throwing away elements of concrete syntax (e. g. ",", ";").
368 """Parser(a, b) -> Parser(a, [b])
370 Returns a parser that applies the parser p one or more times.
372 q = p + many(p) >> (lambda x: [x[0]] + x[1])
373 return q.named(u'(%s , { %s })' % (p.name, p.name))
376 def with_forward_decls(suspension):
377 """(None -> Parser(a, b)) -> Parser(a, b)
379 Returns a parser that computes itself lazily as a result of the suspension
380 provided. It is needed when some parsers contain forward references to
381 parsers defined later and such references are cyclic. See examples for more
387 return suspension().run(tokens, s)
393 """None -> Parser(?, ?)
395 Returns an undefined parser that can be used as a forward declaration. You
396 will be able to define() it when all the parsers it depends on are
402 raise NotImplementedError(u'you must define() a forward_decl somewhere')
407 if __name__ == '__main__':