def test_overrides_parent_scope(): glob = Frame({'x': 2}, None) child = Frame({}, glob) child['x'] = 3 assert glob['x'] == 3 child['b'] = 3 assert not glob.get('b')
def interpret_function(node, environment): global Return # Save the functions node and current environment in the environment Return.type = node.return_type environment[node.lhs.rhs.lhs.tok] = Func(node, environment) # Check if function is main if node.func_name == "main": Return.ret_type = node.return_type return recursive_interpret(node.rhs, Frame({}, environment))
def interpret_if(node, environment): # Check if the if statement has an else clause predicate = recursive_interpret(node.lhs, environment) new_frame = Frame({}, environment) if node.rhs.tok == "else": if predicate: return recursive_interpret(node.rhs.lhs, new_frame) else: return recursive_interpret(node.rhs.rhs, new_frame) else: if recursive_interpret(node.lhs, environment): return recursive_interpret(node.rhs, new_frame)
def interpret_apply(node, environment): global Return if node.lhs.tok == "print": print(recursive_interpret(node.rhs, environment)) return if node.lhs.tok == "apply": # recursive_interpret the lhs of the apply func, env = recursive_interpret(node.lhs, environment) else: try: func, env = environment[node.lhs.tok] except KeyError as error: sys.exit(f'NameError: func {error} undefined') args = get_args_list(node, environment) or [] params = func.func_params check_args(func, params, args) # Create new environment for function with bindings from env bindings = {p.name: a for p, a in zip(params, args)} new_frame = Frame(bindings, env) Return.ret_type = func.return_type recursive_interpret(func.rhs, new_frame) if Return.returning: # if returning: Return.returning = False check_return_type(Return) return Return.ret_val
def interpret_node(head): global Return Return = ReturnObj(False, None, None) recursive_interpret(head, Frame({}, {})) check_return_type(Return) return Return.ret_val
def test_setitem(): glob = Frame({'x': 2}, None) glob['x'] = 3 assert glob['x'] == 3
def test_str(): assert str(Frame({'x': 2}, None)) == "{'x': 2}"
def test_getitem(): glob = Frame({'x': 2}, None) frame = Frame({'y': 3}, glob) assert frame.get('x') == 2
def test_get(): glob = Frame({'x': 2}, None) Frame({'y': 2, 'a': 3}, glob) assert not glob.get('z')