Project

General

Profile

1 11 aaronmk
# A general recursive descent parser
2
3
import re
4
5
class SyntaxException(Exception): pass
6
7
class Parser:
8 76 aaronmk
    def __init__(self, str_):
9
        self._str = str_
10 11 aaronmk
        self._pos = 0
11
12 76 aaronmk
    def end(self):
13 11 aaronmk
        if not self._pos == len(self._str): self._syntax_err('End of string')
14
15 76 aaronmk
    def str_(self, str_, required=False):
16
        end_pos = self._pos + len(str_)
17
        if self._str[self._pos:end_pos] == str_:
18
            self._pos = end_pos
19
            return True
20
        elif required: self._syntax_err(str_)
21
        else: return False
22
23
    def re(self, pattern, required=False):
24 11 aaronmk
        matcher = re.compile(pattern).match(self._str, self._pos)
25
        if matcher:
26
            self._pos = matcher.end(0)
27
            return matcher.group(0)
28
        elif required: self._syntax_err(pattern)
29 38 aaronmk
        else: return None
30 11 aaronmk
31
    def _syntax_err(self, token):
32 62 aaronmk
        raise SyntaxException(self.__class__.__name__+' syntax error: '+token
33
            +' expected in '+self._str[self._pos:])