pmacs3/parse.py

76 lines
1.8 KiB
Python

import lex
class Rule(object):
def __init__(self, *rules):
self.rules = rules
def match(self, tokens):
raise Exception("unimplemented")
class Match(Rule):
method = lex.Token.match
def __init__(self, *args):
self.args = args
def match(self, tokens):
if not tokens:
return False
elif method(tokens[0], *self.args):
tokens.pop(0)
return True
else:
return False
class Matchs(Match):
method = lex.Token.matchs
class Matchp(Match):
method = lex.Token.matchp
class Fqmatch(Match):
method = lex.Token.fqmatch
class Fqmatchs(Match):
method = lex.Token.fqmatchs
class Fqmatchp(Match):
method = lex.Token.fqmatchp
class And(Rule):
def match(self, tokens):
for r in self.rules:
if not r.match(tokens):
return False
return True
class Or(Rule):
def match(self, tokens):
for r in self.rules:
if r.match(tokens):
return True
return False
class Repeat(Rule):
def __init__(self, rule, minimum, maximum):
self.rule = rule
self.minimum = minimum
self.maximum = maximum
def match(self, tokens):
for i in range(0, self.minimum):
if not self.rule.match(tokens):
return False
while self.rules.match(tokens):
pass
return True
self.rule.match(tokens)
return True
class Star(Rule):
def __init__(self, rule):
self.rule = rule
def match(self, tokens):
if not self.rule.match(tokens):
return False
while self.rules.match(tokens):
pass
return True
class End(Rule):
def __init__(self):
pass
def match(self, tokens):
return not tokens