Project

General

Profile

1
# A general recursive descent parser
2

    
3
import re
4

    
5
class SyntaxException(Exception): pass
6

    
7
class Parser:
8
    def __init__(self, str_):
9
        self._str = str_
10
        self._pos = 0
11
    
12
    def end(self):
13
        if not self._pos == len(self._str): self._syntax_err('End of string')
14
    
15
    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
        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
        else: return None
30
    
31
    def _syntax_err(self, token):
32
        raise SyntaxException(self.__class__.__name__+' syntax error: '+token
33
            +' expected in '+self._str[self._pos:])
(1-1/9)