def build_global_frame(): import primitives primitives.load_primitives() frame = Frame("builtins") for k, v in defdict.items(): frame.assign(Symbol(k), v()) # moved to the parser # frame.assign(Symbol("nil"), Nil) # frame.assign(Symbol("#t"), SingletonTrue) # frame.assign(Symbol("#f"), SingletonFalse) for name in [ "acos", "acosh", "asin", "asinh", "atan", "atanh", "ceil", "copysign", "cos", "cosh", "degrees", "floor", "log", "log10", "log1p", "log2", "radians", "sin", "sinh", "sqrt", "tan", "tanh", "trunc" ]: frame.assign(Symbol(name), MathProcedure(getattr(math, name), name)) with open("editor/builtins.scm") as file: execution.string_exec([" ".join(file.readlines())], lambda *x, **y: None, False, frame) return Frame("Global", frame)
def build_global_frame(): import primitives primitives.load_primitives() frame = Frame('builtins') for (k, v) in defdict.items(): frame.assign(Symbol(k), v()) for name in [ 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'floor', 'log', 'log10', 'log1p', 'log2', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc' ]: frame.assign(Symbol(name), MathProcedure(getattr(math, name), name)) with open('editor/builtins.scm') as file: execution.string_exec([' '.join(file.readlines())], (lambda *x, **y: None), False, frame) return Frame('Global', frame)
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder, eval_operands=True): verify_exact_callable_length(self, 1, len(operands)) if eval_operands: operands = evaluate_all(operands, frame, gui_holder.expression.children[1:]) if not isinstance(operands[0], String): raise OperandDeduceError(f"Load expected a String, received {operands[0]}.") if logger.fragile: raise IrreversibleOperationError() from os import listdir from os.path import join directory = operands[0].value try: targets = sorted(listdir(directory)) targets = [join(directory, target) for target in targets if target.endswith(".scm")] exprs = [make_list([Symbol("load"), make_list([Symbol("quote"), Symbol(x[:-4])])]) for x in targets] equiv = make_list([Symbol("begin-noexcept")] + exprs) gui_holder.expression.set_entries([equiv]) gui_holder.apply() return evaluate(equiv, frame, gui_holder.expression.children[0], True) except Exception as e: raise SchemeError(e)
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder, eval_operands=True): new_frame = Frame(self.name, self.frame if self.lexically_scoped else frame) if eval_operands and self.evaluates_operands: operands = evaluate_all(operands, frame, gui_holder.expression.children[1:]) if self.var_param: verify_min_callable_length(self, len(self.params), len(operands)) else: verify_exact_callable_length(self, len(self.params), len(operands)) if len(self.body) > 1: body = [Pair(Symbol("begin"), make_list(self.body))] else: body = self.body for param, value in zip(self.params, operands): new_frame.assign(param, value) if self.var_param: new_frame.assign(self.var_param, make_list(operands[len(self.params):])) out = None gui_holder.expression.set_entries([ VisualExpression(expr, gui_holder.expression.display_value) for expr in body ]) gui_holder.apply() for i, expression in enumerate(body): out = evaluate(expression, new_frame, gui_holder.expression.children[i], self.evaluates_operands and i == len(body) - 1, log_stack=len(self.body) == 1) new_frame.assign(return_symbol, out) if not self.evaluates_operands: gui_holder.expression.set_entries( [VisualExpression(out, gui_holder.expression.display_value)]) out = evaluate(out, frame, gui_holder.expression.children[i], True) return out
def get_expression(buffer: TokenBuffer) -> Union[(Expression, None)]: token = buffer.pop_next_token() if (token is None): return None elif (token in ('(', '[')): return get_rest_of_list(buffer, (')' if (token == '(') else ']')) elif (token == "'"): return make_list([Symbol('quote'), get_expression(buffer)]) elif (token == ','): if (buffer.get_next_token() == '@'): buffer.pop_next_token() return make_list( [Symbol('unquote-splicing'), get_expression(buffer)]) else: return make_list([Symbol('unquote'), get_expression(buffer)]) elif (token == '`'): return make_list([Symbol('quasiquote'), get_expression(buffer)]) elif (token == '.'): if logger.dotted: raise ParseError(''.join( ["Unexpected token: '", '{}'.format(token), "'"])) else: return make_list([Symbol('variadic'), get_expression(buffer)]) elif (token == '"'): return get_string(buffer) elif (token in SPECIALS): raise ParseError(''.join( ["Unexpected token: '", '{}'.format(token), "'"])) elif is_number(token.value): try: return Number(int(token.value)) except ValueError: return Number(float(token.value)) elif ((token == '#t') or (token.value.lower() == 'true')): return SingletonTrue elif ((token == '#f') or (token.value.lower() == 'false')): return SingletonFalse elif (token == 'nil'): return Nil elif is_str(token.value): return Symbol(token.value.lower()) else: raise ParseError(''.join( ["Unexpected token: '", '{}'.format(token), "'"]))
def get_expression(buffer: TokenBuffer) -> Union[Expression, None]: token = buffer.pop_next_token() if token is None: return None elif token in ("(", "["): return get_rest_of_list(buffer, ")" if token == "(" else "]") elif token == "'": return make_list([Symbol("quote"), get_expression(buffer)]) elif token == ",": if buffer.get_next_token() == "@": buffer.pop_next_token() return make_list( [Symbol("unquote-splicing"), get_expression(buffer)]) else: return make_list([Symbol("unquote"), get_expression(buffer)]) elif token == "`": return make_list([Symbol("quasiquote"), get_expression(buffer)]) elif token == ".": if logger.dotted: raise ParseError(f"Unexpected token: '{token}'") else: return make_list([Symbol("variadic"), get_expression(buffer)]) elif token == "\"": return get_string(buffer) elif token in SPECIALS: raise ParseError(f"Unexpected token: '{token}'") elif is_number(token.value): try: return Number(int(token.value)) except ValueError: return Number(float(token.value)) elif token == "#t" or token.value.lower() == "true": return SingletonTrue elif token == "#f" or token.value.lower() == "false": return SingletonFalse elif token == "nil": return Nil elif is_str(token.value): return Symbol(token.value.lower()) else: raise ParseError(f"Unexpected token: '{token}'")
def modify(self, id): if (id in self.prev): self.curr[id] = self.prev[id] logger.frame_updates.append(logger.i) def record(self, expr: Expression) -> 'Heap.HeapKey': if isinstance(expr, evaluate_apply.Thunk): return (False, 'thunk') if (expr.id is None): expr.id = get_id() if ((expr.id not in self.prev) and (expr.id not in self.curr)): if isinstance(expr, ValueHolder): return (False, repr(expr)) elif isinstance(expr, Pair): val = [self.record(expr.first), self.record(expr.rest)] elif isinstance(expr, Promise): val = expr.bind() elif isinstance(expr, NilType): return (False, 'nil') elif isinstance(expr, UndefinedType): return (False, 'undefined') else: val = [(False, repr(expr))] self.curr[expr.id] = val return (True, expr.id) return_symbol = Symbol('Return Value') logger = Logger() announce = logger.log
self.curr[id] = self.prev[id] logger.frame_updates.append(logger.i) def record(self, expr: Expression) -> 'Heap.HeapKey': if isinstance(expr, evaluate_apply.Thunk): return False, "thunk" if expr.id is None: expr.id = get_id() if expr.id not in self.prev and expr.id not in self.curr: if isinstance(expr, ValueHolder): return False, repr(expr) elif isinstance(expr, Pair): val = [self.record(expr.first), self.record(expr.rest)] elif isinstance(expr, Promise): val = expr.bind() elif isinstance(expr, NilType): return False, "nil" elif isinstance(expr, UndefinedType): return False, "undefined" else: # assume the repr method is good enough val = [(False, repr(expr))] self.curr[expr.id] = val return True, expr.id return_symbol = Symbol("Return Value") logger = Logger() announce = logger.log