Skip to content

Commit 7f4e406

Browse files
committed
add Interpreter pattern
1 parent b16e27e commit 7f4e406

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

interpreter/Interpreter.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#
2+
# Python Design Patterns: Interpreter
3+
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
4+
# 2016
5+
#
6+
# Source code is licensed under MIT License
7+
# (for more details see LICENSE)
8+
#
9+
10+
import sys
11+
12+
#
13+
# Context
14+
# contains information that's global to the interpreter
15+
#
16+
class Context:
17+
def __init__(self):
18+
self._vars = {}
19+
20+
def set(self, var, value):
21+
self._vars[var] = value
22+
23+
def get(self, exp):
24+
return self._vars[exp]
25+
26+
#
27+
# Abstract Expression
28+
# declares an abstract Interpret operation that is common to all nodes
29+
# in the abstract syntax tree
30+
#
31+
class AbstractExpression:
32+
def interpret(self, context):
33+
return False
34+
35+
#
36+
# Terminal Expression
37+
# implements an Interpret operation associated with terminal symbols
38+
# in the grammar (an instance is required for every terminal symbol
39+
# in a sentence)
40+
#
41+
class TerminalExpression(AbstractExpression):
42+
def __init__(self, value):
43+
AbstractExpression.__init__(self)
44+
self._value = value
45+
46+
def interpret(self, context):
47+
return context.get(self._value)
48+
49+
#
50+
# Nonterminal Expression
51+
# implements an Interpret operation for nonterminal symbols
52+
# in the grammar (one such class is required for every rule in the grammar)
53+
#
54+
class NonterminalExpression(AbstractExpression):
55+
def __init__(self, expr_left, expr_right):
56+
self._lop = expr_left
57+
self._rop = expr_right
58+
59+
def interpret(self, context):
60+
return self._lop.interpret(context) and self._rop.interpret(context)
61+
62+
63+
# An example of very simple expression tree
64+
# that corresponds to expression (A AND B)
65+
if __name__ == "__main__":
66+
A = TerminalExpression("A")
67+
B = TerminalExpression("B")
68+
exp = NonterminalExpression(A, B)
69+
70+
context = Context()
71+
context.set("A", True)
72+
context.set("B", True)
73+
74+
print(str(context.get("A")) + " AND " + str(context.get("B")), end = "" )
75+
print(" = " + str(exp.interpret(context)))
76+
77+
context.set("A", True)
78+
context.set("B", False)
79+
80+
print(str(context.get("A")) + " AND " + str(context.get("B")), end = "" )
81+
print(" = " + str(exp.interpret(context)))

0 commit comments

Comments
 (0)