-
Notifications
You must be signed in to change notification settings - Fork 115
/
prolog.py
executable file
·390 lines (317 loc) · 9.32 KB
/
prolog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#! /usr/bin/env python
import argparse
import logging
import sys
from paip import logic
## Parser and REPL
# QUESTION = "?"
# DEFN_BEGIN = "<-"
# QUERY_BEGIN = QUESTION "-"
# NUM = (-|+)?[0-9]+("."[0-9]+)?
# IDENT: [a-zA-Z][a-zA-Z0-9_]*
# WHEN = ":-"
# LPAREN = "("
# RPAREN = ")"
# COMMA = ","
# command: EOF | query | defn
# query: QUERY_BEGIN relation
# defn: DEFN_BEGIN relation (WHEN relation_list)?
# relation_list = relation [COMMA relation]*
# relation: IDENT LPAREN term [COMMA term]* RPAREN
# term: relation | var | atom
# atom: NUM | IDENT
# var: QUESTION IDENT
class ParseError(Exception):
def __init__(self, err):
self.err = err
def __str__(self):
return 'Parse error: %s' % self.err
class Parser(object):
k = 2
def __init__(self, lexer):
self.lexer = lexer
self.lookahead = []
for i in xrange(Parser.k):
self.lookahead.append(lexer.next())
def la(self, i):
return self.lookahead[i-1]
def match(self, exp_tt):
tt, tok = self.la(1)
if tt != exp_tt:
raise ParseError('Expected %s, got %s' % (exp_tt, tt))
self.lookahead.pop(0)
self.lookahead.append(self.lexer.next())
return tok
def command(self):
tt, tok = self.la(1)
if tt == EOF:
return
if tt == QUERY_BEGIN:
return self.query()
elif tt == DEFN_BEGIN:
return self.defn()
raise ParseError('Unknown command: %s' % tok)
def query(self):
self.match(QUERY_BEGIN)
return self.relation()
def defn(self):
self.match(DEFN_BEGIN)
head = self.relation()
tt, tok = self.la(1)
if tt == WHEN:
self.match(WHEN)
return logic.Clause(head, self.relation_list())
return logic.Clause(head)
def relation_list(self):
rels = [self.relation()]
tt, tok = self.la(1)
while tt == COMMA:
self.match(COMMA)
rels.append(self.relation())
tt, tok = self.la(1)
return rels
def relation(self):
pred = self.match(IDENT)
body = []
self.match(LPAREN)
body.append(self.term())
tt, tok = self.la(1)
while tt == COMMA:
self.match(COMMA)
body.append(self.term())
tt, tok = self.la(1)
self.match(RPAREN)
return logic.Relation(pred, body)
def term(self):
tt, tok = self.la(1)
if tt == QUESTION:
return self.var()
elif tt == NUM:
return self.atom()
elif tt == IDENT:
tt2, tok2 = self.la(2)
if tt2 == LPAREN:
return self.relation()
else:
return self.atom()
else:
raise ParseError('Unknown term lookahead: %s' % tok)
def var(self):
self.match(QUESTION)
return logic.Var(self.match(IDENT))
def atom(self):
tt, tok = self.la(1)
if tt == NUM:
return logic.Atom(self.match(NUM))
elif tt == IDENT:
return logic.Atom(self.match(IDENT))
else:
raise ParseError('Unknown atom: %s' % tok)
class TokenError(Exception):
def __init__(self, err):
self.err = err
def __str__(self):
return 'Token error: %s' % self.err
LPAREN = 'LPAREN'
RPAREN = 'RPAREN'
COMMA = 'COMMA'
QUESTION = 'QUESTION'
DEFN_BEGIN = 'DEFN_BEGIN'
QUERY_BEGIN = 'QUERY_BEGIN'
NUM = 'NUM'
IDENT = 'IDENT'
WHEN = 'WHEN'
EOF = 'EOF'
class Lexer(object):
def __init__(self, line):
self.line = line
self.pos = 0
self.ch = line[self.pos]
def eat(self):
ret = self.ch
self.pos += 1
if self.pos >= len(self.line):
self.ch = EOF
else:
self.ch = self.line[self.pos]
return ret
def match(self, exp):
if self.ch != exp:
raise TokenError('expected %s' % exp)
self.eat()
def expect(self, is_type):
if not is_type():
raise TokenError('expected type %s' % repr(is_type))
def is_ws(self):
return self.ch in (' ', '\t', '\n')
def DEFN_BEGIN(self):
self.match('<')
self.match('-')
return DEFN_BEGIN, '<-'
def is_when(self):
return self.ch == ':'
def WHEN(self):
self.match(':')
self.match('-')
return WHEN, ':-'
def is_number(self):
return self.ch in '0123456789'
def is_num(self):
return self.is_number() or self.ch in ('+', '-')
def NUM(self):
# get the leading sign
sign = 1
if self.ch == '+':
self.eat()
elif self.ch == '-':
sign = -1
self.eat()
# read the whole part
num = ''
self.expect(self.is_number)
while self.is_number():
num += self.eat()
if not self.ch == '.':
return NUM, int(num)
num += self.eat()
# read the fractional part
self.expect(self.is_number)
while self.is_number():
num += self.eat()
return NUM, float(num)
def is_ident(self):
letters = 'abcdefghijklmnopqrstuvwxyz'
return self.ch in letters or self.ch in letters.upper()
def IDENT(self):
ident = ''
self.expect(self.is_ident)
while self.is_ident() or self.is_number():
ident += self.eat()
return IDENT, ident
def comment(self):
self.match('#')
while self.ch != '\n':
self.eat()
def next(self):
while self.pos < len(self.line):
if self.is_ws():
self.eat()
continue
if self.ch == '#':
self.comment()
continue
if self.ch == '<':
return self.DEFN_BEGIN()
if self.ch == '?':
self.eat()
if self.ch == '-':
self.eat()
return QUERY_BEGIN, '?-'
return QUESTION, '?'
if self.is_ident():
return self.IDENT()
if self.is_num():
return self.NUM()
if self.is_when():
return self.WHEN()
if self.ch == '(':
return LPAREN, self.eat()
if self.ch == ')':
return RPAREN, self.eat()
if self.ch == ',':
return COMMA, self.eat()
raise TokenError('no token begins with %s' % self.ch)
return EOF, EOF
def tokens(line):
lexer = Lexer(line)
while True:
tokt, tok = lexer.next()
if tokt == EOF:
return
yield tokt, tok
def parse(line):
p = Parser(Lexer(line))
return p.command()
def print_db(db):
print 'Database:'
longest = -1
for pred in db:
if len(pred) > longest:
longest = len(pred)
for pred, items in db.items():
if not isinstance(items, list):
continue
print '%s:' % pred
for item in items:
print '\t', item
def read_db(db_file):
db = {}
for line in db_file:
if line == '\n': continue
q = parse(line)
if q:
logic.store(db, q)
return db
## Running
help='''This interpreter provides basic functionality only--the subset of Prolog known
as "Pure Prolog". That is, only clauses are supported--no lists, user-defined
procedures, or arithmetic evaluation.
The REPL allows both rule/fact definition as well as goal proving. The syntax
is as follows:
Defining rules and facts:
<- this(is, ?a) :- simple(?rule), for(?demonstration, only)
<- coprime(14, 15)
Proving goals:
?- coprime(?x, 9)
For some example rule databases, see `paip/examples/prolog`. They can be loaded
with the `--db` option.
'''
argparser = argparse.ArgumentParser(description='A Prolog implementation.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=help)
argparser.add_argument('--logging',
action='store_true',
help='Enable logging',
dest='log')
argparser.add_argument('--db',
type=file,
help='Database file',
dest='db_file')
def main():
print 'Welcome to PyLogic. Type "help" for help.'
args = argparser.parse_args()
db = read_db(args.db_file) if args.db_file else {}
if args.log:
logging.basicConfig(level=logging.DEBUG)
print_db(db)
while True:
try:
line = raw_input('>> ')
except EOFError:
break
if not line:
continue
if line == 'quit':
break
if line == 'help':
print help
continue
try:
q = parse(line)
except ParseError as e:
print e
continue
except TokenError as e:
print e
continue
if isinstance(q, logic.Relation):
try:
logic.prolog_prove([q], db)
except KeyboardInterrupt:
print 'Cancelled.'
elif isinstance(q, logic.Clause):
logic.store(db, q)
print_db(db)
print 'Goodbye.'
if __name__ == '__main__':
main()