From 65126d8b27edb116359672a8a264a81d95dd1885 Mon Sep 17 00:00:00 2001 From: "C. Mangla" Date: Tue, 2 Feb 2021 16:01:40 +0000 Subject: [PATCH 1/2] Attach values directly to tree nodes As mentioned in the book, in dynamic languages such as Python, where object attributes can be added at runtime, a map to store the values is not needed. --- 07-LableRule/test_EvalContext.py | 27 +++++++++------------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/07-LableRule/test_EvalContext.py b/07-LableRule/test_EvalContext.py index e8b540f..d4c9e3e 100644 --- a/07-LableRule/test_EvalContext.py +++ b/07-LableRule/test_EvalContext.py @@ -15,30 +15,21 @@ class ContextMap(LExprListener): - def __init__(self): - self.tree_property = {} - - def getValue(self, node): - return self.tree_property[node] - - def setValue(self, node, value): - self.tree_property[node] = value - def exitInt(self, ctx): - self.setValue(ctx, int(ctx.INT().getText())) + ctx.value = int(ctx.INT().getText()) def exitAdd(self, ctx): - left = self.getValue(ctx.e(0)) - right= self.getValue(ctx.e(1)) - self.setValue(ctx, left+right) + left = ctx.e(0).value + right= ctx.e(1).value + ctx.value = left + right def exitMult(self, ctx): - left = self.getValue(ctx.e(0)) - right= self.getValue(ctx.e(1)) - self.setValue(ctx, left*right) + left = ctx.e(0).value + right= ctx.e(1).value + ctx.value = left * right def exitS(self, ctx): - self.setValue(ctx, self.getValue(ctx.e())) + ctx.value = ctx.e().value if __name__ == '__main__': @@ -60,4 +51,4 @@ def exitS(self, ctx): listener = ContextMap() walker = ParseTreeWalker() walker.walk(listener, tree) - print('result_at_top =', listener.getValue(tree)) + print('result_at_top =', listener.value) From 04353ed2eb900c25c99aee0dd79739e9604ee66b Mon Sep 17 00:00:00 2001 From: "C. Mangla" Date: Tue, 2 Feb 2021 23:29:21 +0000 Subject: [PATCH 2/2] Fix: result_at_top is in the tree, not listener --- 07-LableRule/test_EvalContext.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/07-LableRule/test_EvalContext.py b/07-LableRule/test_EvalContext.py index d4c9e3e..f558d75 100644 --- a/07-LableRule/test_EvalContext.py +++ b/07-LableRule/test_EvalContext.py @@ -51,4 +51,4 @@ def exitS(self, ctx): listener = ContextMap() walker = ParseTreeWalker() walker.walk(listener, tree) - print('result_at_top =', listener.value) + print('result_at_top =', tree.value)