Ejemplo n.º 1
0
    def try_to_find_var_and_set_it(self, var: Identifier, evaluated_value):
        # Current scope should not be the outer scope
        if self.parent_scope is None:
            raise Exception

        # We are allowed to change var in the global scope
        if var.get_name() in self.symbol_table:
            self.symbol_table[var.get_name()] = evaluated_value
            return True
        return False
Ejemplo n.º 2
0
    def try_to_find_var_and_set_it(self, var: Identifier, evaluated_value):
        # Check if var is in the current scope.
        # If it's not check in the parent scope.
        # Function stops calling itself when var is found and set
        # or when it reaches global scope where it is stopped.
        # Returns True if found and set var in current scope.
        # Otherwise returns what parent returned.

        if var.get_name() in self.symbol_table:
            self.symbol_table[var.get_name()] = evaluated_value
            return True
        return self.parent_scope.try_to_find_var_and_set_it(
            var, evaluated_value)
Ejemplo n.º 3
0
    def get_var(self, var: Identifier):
        # Loop through all parent scopes (including current scope)
        # and return first matched variable or None if not found.

        scope = self
        while (value := scope.symbol_table.get(var.get_name(), None)) is None\
                and scope.parent_scope is not None:
            scope = scope.parent_scope
Ejemplo n.º 4
0
    def set_var(self, var: Identifier, evaluated_value):
        # To set variable means that
        # the variable got assigned.
        # First check if the variable exists
        # in one of the parent scopes and if it does, reassign it.
        # If it doesn't, add it to the symbol table of this scope.

        if not self.try_to_find_var_and_set_it(var, evaluated_value):
            self.symbol_table[var.get_name()] = evaluated_value