def visit_ifnode(self, node, context):
     """
     Accesses the IfNode instance in the stream.
     :param node: IfNode instance we wish to visit.
     :param context: Context of the caller.
     :return: Value of the if-statement, or None.
     """
     runtime_result = RuntimeResult()
     for condition, expr, should_return_null in node.cases:
         condition_value = runtime_result.register(
             self.visit(condition, context))
         if runtime_result.should_return():
             return runtime_result
         if condition_value.is_true():
             expr_value = runtime_result.register(self.visit(expr, context))
             if runtime_result.should_return():
                 return runtime_result
             return runtime_result.success(
                 Number(0) if should_return_null else expr_value)
     if node.else_case:
         expr, should_return_null = node.else_case
         expr_value = runtime_result.register(self.visit(expr, context))
         if runtime_result.should_return():
             return runtime_result
         return runtime_result.success(
             Number(0) if should_return_null else expr_value)
     return runtime_result.success(Number(0))
    def visit_fornode(self, node, context):
        """
        Visits the ForNode for for-loops in the stream.
        :param node: Node of the for-loop.
        :param context: Context of the caller.
        :return: List of evaluated values.
        """
        elements = []
        runtime_result = RuntimeResult()
        start_value = runtime_result.register(
            self.visit(node.start_value_node, context))
        if runtime_result.should_return():
            return runtime_result
        end_value = runtime_result.register(
            self.visit(node.end_value_node, context))
        if runtime_result.should_return():
            return runtime_result
        if node.step_value_node:
            step_value = runtime_result.register(
                self.visit(node.step_value_node, context))
            if runtime_result.should_return():
                return runtime_result
        else:  # Default to one iteration
            step_value = Number(1)

        # Note: PEP 8 doesn't allow for lambda expressions to be assigned to
        #       variables directly. They prefer a function definition. However, this
        #       is the cleanest way to do this. Code is read more often than it's
        #       written. This expression is easier to read and understand as an
        #       inline lambda assignment.
        index = start_value.value
        if step_value.value >= 0:
            condition = lambda: index < end_value.value
        else:  # Step value must be negative
            condition = lambda: index > end_value.value

        while condition():
            context.symbol_table.set(node.var_name_token.value, Number(index))
            index += step_value.value
            current_value = runtime_result.register(
                self.visit(node.body_node, context))
            if runtime_result.should_return() \
                    and runtime_result.loop_should_continue is False \
                    and runtime_result.loop_should_break is False:
                return runtime_result
            if runtime_result.loop_should_continue:
                continue
            if runtime_result.loop_should_break:
                break
            elements.append(current_value)
        return runtime_result.success(
            Number(0) if node.should_return_null else List(elements).
            set_context(context).set_position(node.start_pos, node.end_pos))
Exemple #3
0
    def __init__(self, parent=None):
        """
        Initialize an empty dictionary for the symbol table
        as well as a copy of the parent's symbol table.
        :param parent: Parent SymbolTable instance.
        """
        self.symbols = dict()
        self.parent = parent

        # Special values in the language
        self.symbols['NULL'] = Number(0)
        self.symbols['TRUE'] = Number(1)
        self.symbols['FALSE'] = Number(0)
 def visit_whilenode(self, node, context):
     """
     Visits the WhileNode for while-loops in the stream.
     :param node: Node of the while-loop.
     :param context: Context of the caller.
     :return: List of all evaluated results.
     """
     elements = []
     runtime_result = RuntimeResult()
     while True:
         condition = runtime_result.register(
             self.visit(node.condition, context))
         if runtime_result.should_return():
             return runtime_result
         if not condition.is_true():
             break
         current_value = runtime_result.register(
             self.visit(node.body_node, context))
         if runtime_result.should_return() \
                 and runtime_result.loop_should_continue is False \
                 and runtime_result.loop_should_break is False:
             return runtime_result
         if runtime_result.loop_should_continue:
             continue
         if runtime_result.loop_should_break:
             break
         elements.append(current_value)
     return runtime_result.success(
         Number(0) if node.should_return_null else List(elements).
         set_context(context).set_position(node.start_pos, node.end_pos))
 def execute_len(self, exec_context):
     list_ = exec_context.symbol_table.get("list")
     if not isinstance(list_, List):
         return RuntimeResult().failure(
             ActiveRuntimeError("Argument must be list", self.start_pos,
                                self.end_pos, exec_context))
     return RuntimeResult().success(Number(len(list_.elements)))
 def execute_input_int(self, exec_context):
     while True:
         text = input()
         try:  # Try converting to int
             number = int(text)
             break
         except ValueError:
             print("'{}' must be an integer. Try again!".format(text))
     return RuntimeResult().success(Number(number))
 def execute_append(self, exec_context):
     list_ = exec_context.symbol_table.get("list")
     value = exec_context.symbol_table.get("value")
     if not isinstance(list_, List):
         return RuntimeResult().failure(
             ActiveRuntimeError("First argument must be list",
                                self.start_pos, self.end_pos, exec_context))
     list_.elements.append(value)
     return RuntimeResult().success(Number(0))
 def visit_numbernode(self, node, context):
     """
     Returns the value of the Node as a Number.
     :param node: The Node with the numeric value.
     :param context: Context of the caller.
     :return: Number instance with the Node value.
     """
     return RuntimeResult().success(
         Number(node.token.value).set_context(context).set_position(
             node.start_pos, node.end_pos))
 def execute_extend(self, exec_context):
     first_list = exec_context.symbol_table.get("first_list")
     end_list = exec_context.symbol_table.get("second_list")
     if not isinstance(first_list, List):
         return RuntimeResult().failure(
             ActiveRuntimeError("First argument must be list",
                                self.start_pos, self.end_pos, exec_context))
     if not isinstance(end_list, List):
         return RuntimeResult().failure(
             ActiveRuntimeError("Second argument must be list",
                                self.start_pos, self.end_pos, exec_context))
     first_list.elements.extend(end_list.elements)
     return RuntimeResult().success(Number(0))
 def visit_returnnode(self, node, context):
     """
     Visits the ReturnNode instance.
     :param node: The ReturnNode instance.
     :param context: The caller's context.
     :return: Value of the ReturnNode instance.
     """
     runtime_result = RuntimeResult()
     if node.node_to_return:
         value = runtime_result.register(
             self.visit(node.node_to_return, context))
         if runtime_result.should_return():
             return runtime_result
     else:
         value = Number(0)
     return runtime_result.success_return(value)
 def visit_unaryopnode(self, node, context):
     """
     Returns result of the unary operator on the node.
     :param node: Node with which to perform a unary operation.
     :param context: Context of the caller.
     :return: Result of the unary operation on the node.
     """
     error = None
     runtime_result = RuntimeResult()
     number = runtime_result.register(self.visit(node.right_node, context))
     if runtime_result.should_return():
         return runtime_result
     if node.op_token.type == TP_MINUS:
         number, error = number.multiply_by(Number(-1))
     elif node.op_token.matches(TP_KEYWORD, 'NOT'):
         number, error = number.notted()
     if error:
         return runtime_result.failure(error)
     return runtime_result.success(
         number.set_position(node.start_pos, node.end_pos))
 def execute_run(self, exec_context):
     file_name = exec_context.symbol_table.get("fn")
     if not isinstance(file_name, String):
         return RuntimeResult().failure(
             ActiveRuntimeError("Second argument must be string",
                                self.start_pos, self.end_pos, exec_context))
     file_name = file_name.value
     try:
         with open(file_name, "r") as f:
             script = f.read()
     except Exception as exception:
         return RuntimeResult().failure(
             ActiveRuntimeError(
                 "Failed to load script \"{}\"\n".format(file_name) +
                 str(exception), self.start_pos, self.end_pos,
                 exec_context))
     _, error = run(file_name, script)
     if error:
         return RuntimeResult().failure(
             ActiveRuntimeError(
                 "Failed to finish executing script \"{}\"\n".format(
                     file_name) + error.as_string(), self.start_pos,
                 self.end_pos, exec_context))
     return RuntimeResult().success(Number(0))
 def execute_print(self, exec_context):
     print(str(exec_context.symbol_table.get('value')))
     return RuntimeResult().success(Number(0))
 def execute_is_function(self, exec_context):
     is_number = isinstance(exec_context.symbol_table.get("value"),
                            BaseFunction)
     return RuntimeResult().success(Number(1) if is_number else Number(0))
 def execute_is_string(self, exec_context):
     is_number = isinstance(exec_context.symbol_table.get("value"), String)
     return RuntimeResult().success(Number(1) if is_number else Number(0))
 def execute_clear(self, exec_context):
     os.system('cls' if os.name == 'nt' else 'cls')
     return RuntimeResult().success(Number(0))
from bin.parser import Parser
from bin.runtime_result import RuntimeResult
from bin.string import String
from bin.symbol_table import SymbolTable

##############################
# DEFINE GLOBAL SYMBOL TABLE #
##############################

global_symbol_table = SymbolTable()

########################
# DEFINE ALL CONSTANTS #
########################

Number.null = Number(0)
Number.false = Number(0)
Number.true = Number(1)
Number.math_PI = Number(math.pi)

################################################################
# BUILTIN FUNCTION CLASS                                       #
# DEFINED HERE BECAUSE IT CALLS THE RUN() FUNCTION             #
# WHICH RESULTS IN A CIRCULAR IMPORT IF PLACED IN ITS OWN FILE #
################################################################


class BuiltInFunction(BaseFunction):
    """Class of all built-in functions."""
    def __init__(self, name):
        """
 def execute(self, args):
     """
     Execute a Function instance.
     :param args: Arguments being passed into the Function.
     :return: Value of the executed Function.
     """
     runtime_result = RuntimeResult()
     interpreter = Interpreter()
     exec_context = self.generate_new_context()
     runtime_result.register(
         self.check_and_populate_args(self.arg_names, args, exec_context))
     if runtime_result.should_return():
         return runtime_result
     value = runtime_result.register(
         interpreter.visit(self.body_node, exec_context))
     if runtime_result.should_return(
     ) and runtime_result.func_return_value is None:
         return runtime_result
     return_value \
         = (value if self.should_auto_return else None) or runtime_result.func_return_value or Number(0)
     return runtime_result.success(return_value)