MCPcopy Create free account
hub / github.com/dabeaz/python-cookbook / StackCode

Class StackCode

src/8/implementing_the_visitor_pattern/example.py:71–102  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

69# --- Example 2: Generate stack instructions
70
71class StackCode(NodeVisitor):
72 def generate_code(self, node):
73 self.instructions = []
74 self.visit(node)
75 return self.instructions
76
77 def visit_Number(self, node):
78 self.instructions.append(('PUSH', node.value))
79
80 def binop(self, node, instruction):
81 self.visit(node.left)
82 self.visit(node.right)
83 self.instructions.append((instruction,))
84
85 def visit_Add(self, node):
86 self.binop(node, 'ADD')
87
88 def visit_Sub(self, node):
89 self.binop(node, 'SUB')
90
91 def visit_Mul(self, node):
92 self.binop(node, 'MUL')
93
94 def visit_Div(self, node):
95 self.binop(node, 'DIV')
96
97 def unaryop(self, node, instruction):
98 self.visit(node.operand)
99 self.instructions.append((instruction,))
100
101 def visit_Negate(self, node):
102 self.unaryop(node, 'NEG')
103
104# --- Example of the above classes in action
105

Callers 1

example.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected