-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell.py
113 lines (106 loc) · 3.75 KB
/
shell.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
import typing as t
import engine
import interpreter as interp
import lexer
import parse
def process(
eng: engine.InferenceEngine,
stmts: t.List[interp.Statement],
ln: t.Optional[int] = 0,
) -> None:
for stmt in stmts:
if isinstance(stmt, interp.Fact):
eng.add_fact(stmt)
elif isinstance(stmt, interp.Rule):
eng.add_rule(stmt)
else:
if ln:
print("Line {}: ".format(ln), end="")
try:
print("Rule {}, {}".format(stmt.name, eng.infer_hypothesis(stmt.name)))
except (engine.ContradictionError, engine.CycleError) as e:
print("Rule {}, False ({})".format(stmt.name, e))
def stdin_parse() -> None:
eng = engine.InferenceEngine()
while True:
user_input = input("#=> ").strip()
try:
if user_input == "quit":
print("Goodbye !")
break
if user_input == "reset":
eng = engine.InferenceEngine()
continue
processed_input = lexer.lex(user_input)
if not processed_input:
continue
if processed_input[0] in ("=", "?"):
process(
eng,
interp.run(
parse.AST(
processed_input[0], parse.ident_serie(processed_input[1:])
)
),
)
else:
stmt = parse.ifop(processed_input)
if stmt.name == "<=>":
process(
eng,
interp.run(parse.AST("=>", stmt.operands))
+ interp.run(parse.AST("=>", stmt.operands[::-1])),
)
else:
process(eng, interp.run(stmt))
except RuntimeError:
print(
"Maximum recursion depth reached, "
"please make the expression simpler."
)
except Exception as e:
print(e)
def fparse(filename: str) -> None:
eng = engine.InferenceEngine()
with open(filename) as f:
for i, line in enumerate(f, 1):
try:
if line.strip() == "reset":
eng = engine.InferenceEngine()
continue
if line.strip().startswith("display "):
print(line.strip()[8:])
continue
if not line.strip():
continue
processed_input = lexer.lex(line)
if not processed_input:
continue
if processed_input[0] in ("=", "?"):
process(
eng,
interp.run(
parse.AST(
processed_input[0],
parse.ident_serie(processed_input[1:]),
)
),
i,
)
else:
stmt = parse.ifop(processed_input)
if stmt.name == "<=>":
process(
eng,
interp.run(parse.AST("=>", stmt.operands))
+ interp.run(parse.AST("=>", stmt.operands[::-1])),
)
else:
process(eng, interp.run(stmt))
except RuntimeError:
print(
"Line {}: Maximum recursion depth reached, "
"please make the expression simpler.".format(i + 1)
)
except Exception as e:
print(e)