-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
460 lines (393 loc) · 11.8 KB
/
main.py
File metadata and controls
460 lines (393 loc) · 11.8 KB
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import re
from enum import Enum
class error(Exception):
def __init__(self, arg):
global num_errors
self.args = arg
num_errors += 1
def __str__(self):
outputFile.write(''.join(self.args))
outputFile.write('\n')
return ''.join(self.args)
################################ SYNTAX ANALYZER ################################
# <program> -> <clause-list> <query> | <query>
def program():
getChar()
print("Enter Program")
lex()
try:
clause_list()
except error as e:
print(e)
while nextToken != TokenClass.QUERY_SYM and nextToken != CharClass.EOF:
lex()
try:
query()
except error as e:
print(e)
if nextToken != CharClass.EOF:
lex()
if nextToken == TokenClass.ATOM:
predicateList()
else:
e_ = error(f"Invalid Query at line {line}, no atom found at expected predicate list.")
print(e_)
if nextToken == CharClass.EOF:
print("End of File reached")
# <clause-list> -> <clause> | <clause> <clause-list>
def clause_list():
print("Enter Clause_List")
try:
while nextToken == TokenClass.ATOM:
clause()
except error as e:
print(e)
while nextChar != '\n':
lex()
# <clause> -> <predicate> . | <predicate> :- <predicate-list> .
def clause():
print("Enter Clause")
try:
predicate()
except error as e:
print(e)
while nextToken != TokenClass.IMPLY and nextToken != TokenClass.DELIMITER:
lex()
if nextToken == TokenClass.IMPLY:
lex()
predicateList()
if nextToken == TokenClass.DELIMITER:
lex()
else:
# Error - no Full Stop/End of Statement
raise error(f"Invalid clause at line {line}, no Delimiter at end of clause")
# <query> -> ?- <predicate-list> .
def query():
print("Enter Query")
# Check if it starts with Query
if nextToken == TokenClass.QUERY_SYM:
# Get the next Token
lex()
predicateList()
if nextToken == TokenClass.DELIMITER:
lex()
else:
# Error - no ending delimiter
raise error(f"Invalid Query at line {line}, No ending delimiter at Query")
else:
# Error - no query symbol
raise error(f"Invalid Query at line {line}, No Query symbol in Query")
# <predicate-list> -> <predicate> | <predicate> , <predicate-list>
def predicateList():
print("Enter Predicate List")
try:
predicate()
except error as e:
print(e)
while nextToken != TokenClass.AND_OP and nextChar != '\n' and nextToken != CharClass.EOF:
lex()
while nextToken == TokenClass.AND_OP:
lex()
predicateList()
# <predicate> -> <atom> | <atom> ( <term-list> )
def predicate():
print("Enter Predicate")
if nextToken == TokenClass.ATOM:
lex()
if nextToken == CharClass.LEFT_PAREN:
lex()
try:
term_list()
except error as e:
print(e)
while nextToken != CharClass.RIGHT_PAREN and nextChar != '\n' and nextToken != CharClass.EOF:
lex()
if nextToken == CharClass.RIGHT_PAREN:
lex()
else:
# Error - no Right Parenthesis
raise error(f"Invalid Predicate at line {line}, No Right Parenthesis at Predicate")
else:
pass
else:
# Error - no Atom
raise error(f"Invalid Predicate at line {line}, No Atom at expected Predicate, lexeme {lexeme}")
# <term-list> -> <term> | <term> , <term-list>
def term_list():
print("Enter term list")
try:
term()
except error as e:
print(e)
while nextToken != TokenClass.AND_OP and nextChar != '\n':
lex()
while nextToken == TokenClass.AND_OP:
lex()
term_list()
if nextToken == TokenClass.UNKNOWN:
raise error(f"Invalid Term list at line {line}, lexeme {lexeme}")
print("Exiting term_list")
# <term> -> <atom> | <structure> | <variable> | <numeral>
# <term> -> <predicate> | <variable> | <numeral>
def term():
print("Enter Term")
if nextToken == TokenClass.VARIABLE:
lex()
elif nextToken == TokenClass.NUMERAL:
lex()
elif nextToken == TokenClass.ATOM:
lex()
if nextToken == CharClass.LEFT_PAREN:
lex()
try:
term_list()
except error as e:
print(e)
if nextToken == CharClass.RIGHT_PAREN:
lex()
else:
# no right parenthesis
raise error(f"Invalid structure at line {line}, missing right parenthesis")
else:
pass
else:
raise error(f"Invalid Term at line {line}, Invalid Token, lexeme {lexeme}.")
# <structure> -> <atom> ( <term-list> )
# def structure():
# print("Enter Structure")
# if nextToken == TokenClass.ATOM:
# lex()
# if nextToken == CharClass.LEFT_PAREN:
# lex()
# term_list()
# if nextToken == CharClass.RIGHT_PAREN:
# lex()
################################ LEXICAL ANALYZER ################################
class CharClass(Enum):
LOWERCASE = 0
UPPERCASE = 1
DIGIT = 2
COLON = 100
BACKSLASH = 101
CARET = 102
TILD = 103
FULLSTOP = 104
QUESTIONMARK = 105
HASH = 106
DOLLARSIGN = 107
AMPERSAND = 108
ADD_OP = 109
SUB_OP = 110
MULT_OP = 111
DIV_OP = 112
SPACE = 113
LEFT_PAREN = 3
RIGHT_PAREN = 4
SINGLEQUOTE = 5
COMMA = 6
EOF = 666
UNKNOWN = 777
class TokenClass(Enum):
SPECIAL = 0
CHARACTER = 1
STRING = 2
NUMERAL = 3
ALPHANUMERIC = 4
CHAR_LIST = 5
VARIABLE = 6
ATOM = 8
QUERY_SYM = 15
IMPLY = 16
DELIMITER = 20
AND_OP = 21
UNKNOWN = -1
line = 1
num_errors = 0
charClass = 0
lexeme = ''
nextChar = ''
nextToken = 0
inputFile = None
SPECIAL = ['+', '-', '*', '/', '\\', '^', '~', ':', '.', '?', ' ', '\#', '$', '&']
def getChar():
global nextChar, charClass, line, num_errors
nextChar = inputFile.read(1)
if nextChar:
if re.match('[A-Z_]', nextChar):
charClass = CharClass.UPPERCASE
elif re.match('[a-z]', nextChar):
charClass = CharClass.LOWERCASE
elif re.match(r'\d', nextChar):
charClass = CharClass.DIGIT
elif nextChar == '.':
charClass = CharClass.FULLSTOP
elif nextChar == '(':
charClass = CharClass.LEFT_PAREN
elif nextChar == ')':
charClass = CharClass.RIGHT_PAREN
elif nextChar == "'":
charClass = CharClass.SINGLEQUOTE
elif nextChar == '+':
charClass = CharClass.ADD_OP
elif nextChar == '-':
charClass = CharClass.SUB_OP
elif nextChar == '*':
charClass = CharClass.MULT_OP
elif nextChar == '/':
charClass = CharClass.DIV_OP
elif nextChar == '\\':
charClass = CharClass.BACKSLASH
elif nextChar == ':':
charClass = CharClass.COLON
elif nextChar == '&':
charClass = CharClass.AMPERSAND
elif nextChar == '^':
charClass = CharClass.CARET
elif nextChar == '$':
charClass = CharClass.DOLLARSIGN
elif nextChar == '~':
charClass = CharClass.TILD
elif nextChar == '?':
charClass = CharClass.QUESTIONMARK
elif nextChar == '#':
charClass = CharClass.HASH
elif nextChar == ' ':
charClass = CharClass.SPACE
elif nextChar == ',':
charClass = CharClass.COMMA
elif nextChar == '\n':
line += 1
charClass = CharClass.UNKNOWN
else:
print(f'Error - unrecognized character {nextChar} at line {line}')
outputFile.write(f'Error - unrecognized character {nextChar} at line {line}\n')
num_errors += 1
charClass = CharClass.UNKNOWN
else:
charClass = CharClass.EOF
def addChar():
global lexeme
lexeme += nextChar
def getNonBlank():
while nextChar.isspace():
getChar()
def lex():
global nextToken, lexeme
lexeme = ''
getNonBlank()
# End of program
if not charClass or charClass == CharClass.EOF:
nextToken = CharClass.EOF
# Parse variable
elif charClass == CharClass.UPPERCASE:
addChar()
getChar()
while 0 <= charClass.value <= 2:
addChar()
getChar()
nextToken = TokenClass.VARIABLE
# Parse numeral
elif charClass == CharClass.DIGIT:
addChar()
getChar()
while charClass == CharClass.DIGIT:
addChar()
getChar()
nextToken = TokenClass.NUMERAL
# Parse Query
elif charClass == CharClass.QUESTIONMARK:
addChar()
getChar()
if charClass == CharClass.SUB_OP:
addChar()
getChar()
nextToken = TokenClass.QUERY_SYM
else:
# ERROR
pass
# Parse Implied By
elif charClass == CharClass.COLON:
addChar()
getChar()
if charClass == CharClass.SUB_OP:
addChar()
getChar()
nextToken = TokenClass.IMPLY
else:
# ERROR
pass
# Parse String into Atom
elif charClass == CharClass.SINGLEQUOTE:
addChar()
getChar()
while 100 <= charClass.value <= 113 or 0 <= charClass.value <= 2:
addChar()
getChar()
if charClass == CharClass.SINGLEQUOTE:
addChar()
getChar()
nextToken = TokenClass.ATOM
else:
# ERROR
pass
# Parse Small Atom into Atom
# A small atom is also an atom. Think about combining with string rule if possible
elif charClass == CharClass.LOWERCASE:
addChar()
getChar()
while 0 <= charClass.value <= 2:
addChar()
getChar()
nextToken = TokenClass.ATOM
# Parse And Operator
elif charClass == CharClass.COMMA:
addChar()
getChar()
nextToken = TokenClass.AND_OP
# Parse Delimiter (End of Statement)
elif charClass == CharClass.FULLSTOP:
addChar()
getChar()
nextToken = TokenClass.DELIMITER
# Parse Left Parenthesis
elif charClass == CharClass.LEFT_PAREN:
addChar()
getChar()
nextToken = CharClass.LEFT_PAREN
# Parse Right Parenthesis
elif charClass == CharClass.RIGHT_PAREN:
addChar()
getChar()
nextToken = CharClass.RIGHT_PAREN
else:
addChar()
getChar()
nextToken = TokenClass.UNKNOWN
print(f'{lexeme:<20} is a {nextToken:20}')
################################ MAIN ################################
if __name__ == '__main__':
# Here we open the file and insert it into the analyzer
try:
try:
outputFile = open('parser_output.txt', 'w')
i = 1
while True:
line = 1
num_errors = 0
file = f"{i}.txt"
inputFile = open(file, 'r')
outputFile.write(file.center(30, '~') + '\n')
print(file.center(30, '~'))
program()
if num_errors == 0:
outputFile.write('Syntactically Correct\n')
else:
outputFile.write(f'{num_errors} error(s) found\n')
inputFile.close()
i += 1
outputFile.close()
except Exception:
outputFile.close()
print("Done")
except Exception as e:
print(e)