First working parser.
4 Author: Eugen Sawin <sawine@informatik.uni-freiburg.de>
22 class Operator(object):
23 def __init__(self, id):
30 Operator.__init__(self, NOT)
36 Operator.__init__(self, AND)
40 Operator.__init__(self, OR)
44 Operator.__init__(self, IMP)
48 Operator.__init__(self, EQ)
52 Operator.__init__(self,BOX )
54 class Diamond(Operator):
56 Operator.__init__(self, DIAMOND)
58 class Variable(Operator):
60 Operator.__init__(self, VARIABLE)
62 class Formula(object):
63 def __init__(self, f):
66 TOKENS = {re.compile("\("): LB,
71 re.compile("->"): Imp,
72 re.compile("<->"): Eq,
73 re.compile("\[\]"): Box,
74 re.compile("<>"): Diamond,
75 re.compile("[a-z]+"): Variable}
77 class Scanner(object):
78 def __init__(self, tokens, source=None):
82 while self.i < len(self.source):
83 for p, token in self.tokens.iteritems():
84 m = p.match(self.source[self.i:])
90 def reset(self, source):
105 SYNTAX = ((Variable,),
115 class Parser(object):
116 def __init__(self, syntax, scanner):
118 self.scanner = scanner
119 def parse(self, source):
120 table = {(S, Variable): 0,
129 (A, Variable, And): 5,
130 (A, Variable, Or): 6,
131 (A, Variable, Imp): 7,
132 (A, Variable, Eq): 8}
135 self.scanner.reset(source)
136 token = self.scanner.next()
137 lookahead = self.scanner.next()
139 while token and len(stack):
143 #print "token ", token
144 #print "lookahead ", lookahead
148 lookahead = self.scanner.next()
151 if (top, token) in table:
152 action = table[(top, token)]
153 elif (top, token, lookahead) in table:
154 action = table[(top, token, lookahead)]
155 #print "action ", action, " replace ", self.syntax[action]
161 stack.extend(reversed(self.syntax[action]))
162 return (accepted and not len(stack), out)
167 args = parse_arguments()
168 scanner = Scanner(TOKENS)
169 parser = Parser(SYNTAX, scanner)
170 print parser.parse(args.formula)
172 from argparse import ArgumentParser
174 def parse_arguments():
175 parser = ArgumentParser(description="Parses Simple Modal Logic syntax.")
176 parser.add_argument("formula", help="your formula")
177 return parser.parse_args()
179 if __name__ == "__main__":