Updated syntax tree to support variables in the espression.

This commit is contained in:
2020-07-01 22:15:25 -05:00
parent 503b16ec65
commit 3cab3f03e8
2 changed files with 27 additions and 0 deletions
+25
View File
@@ -34,6 +34,7 @@ class Parser:
def __init__(self, tokens):
if len(tokens) == 0:
raise ValueError("Token list can't be empty")
self.variables = {}
self.tokens = tokens
self.current_token = None
self.advance_current_token()
@@ -51,6 +52,7 @@ class Parser:
return node
elif self.current_token.type == token.TokenType.variable:
node = Variable(self.current_token)
self.variables[self.current_token.value] = node
self.advance_current_token()
return node
elif self.current_token.type == token.TokenType.exp_start:
@@ -91,3 +93,26 @@ class Parser:
def generate_ast(self):
return self.topLevel()
def update_variable(self, symbol, value):
if symbol in self.variables:
self.variables[symbol].value = float(value)
else:
raise ValueError("Variable value must be a number.", value)
def update_variables(self, variables):
if len(variables) == 0:
return
for symbol in variables:
if symbol in self.variables:
self.variables[symbol].value = float(variables[symbol])
else:
raise ValueError("Variable value must be a number.")
def get_variable_value_pairs(self):
keys = {}
for symbol in self.variables:
keys[symbol] = self.variables[symbol].value
return keys