def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_min_callable_length(self, 2, len(operands)) bindings = operands[0] if not isinstance(bindings, Pair) and bindings is not Nil: raise OperandDeduceError(f"Expected first argument of let to be a Pair, not {bindings}.") new_frame = Frame("anonymous let", frame) bindings_holder = gui_holder.expression.children[1] bindings = pair_to_list(bindings) for i, binding in enumerate(bindings): if not isinstance(binding, Pair): raise OperandDeduceError(f"Expected binding to be a Pair, not {binding}.") binding_holder = bindings_holder.expression.children[i] binding = pair_to_list(binding) if len(binding) != 2: raise OperandDeduceError(f"Expected binding to be of length 2, not {len(binding)}.") name, expr = binding if not isinstance(name, Symbol): raise OperandDeduceError(f"Expected first element of binding to be a Symbol, not {name}.") new_frame.assign(name, evaluate(expr, frame, binding_holder.expression.children[1])) value = None for i, (operand, holder) in enumerate(zip(operands[1:], gui_holder.expression.children[2:])): value = evaluate(operand, new_frame, holder, i == len(operands) - 2) new_frame.assign(return_symbol, value) return value
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_min_callable_length(self, 1, len(operands)) for (cond_i, cond) in enumerate(operands): if (not isinstance(cond, Pair)): raise OperandDeduceError(''.join([ 'Unable to evaluate clause of cond, as ', '{}'.format(cond), ' is not a Pair.' ])) expanded = pair_to_list(cond) cond_holder = gui_holder.expression.children[(cond_i + 1)] cond_holder.link_visual(VisualExpression(cond)) eval_condition = SingletonTrue if ((not isinstance(expanded[0], Symbol)) or (expanded[0].value != 'else')): eval_condition = evaluate(expanded[0], frame, cond_holder.expression.children[0]) if ((isinstance(expanded[0], Symbol) and (expanded[0].value == 'else')) or (eval_condition is not SingletonFalse)): out = eval_condition for (i, expr) in enumerate(expanded[1:]): out = evaluate(expr, frame, cond_holder.expression.children[(i + 1)], (i == (len(expanded) - 2))) return out return Undefined
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: operand = evaluate(operands[0], frame, gui_holder.expression.children[1]) else: operand = operands[0] gui_holder.expression.set_entries([VisualExpression(operand, gui_holder.expression.display_value)]) gui_holder.apply() return evaluate(operand, frame, gui_holder.expression.children[0], True)
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_min_callable_length(self, 2, len(operands)) if len(operands) > 3: verify_exact_callable_length(self, 3, len(operands)) if evaluate(operands[0], frame, gui_holder.expression.children[1]) is SingletonFalse: if len(operands) == 2: return Undefined else: return evaluate(operands[2], frame, gui_holder.expression.children[3], True) else: return evaluate(operands[1], frame, gui_holder.expression.children[2], True)
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 execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): value = None for i, expr in enumerate(operands): value = evaluate(expr, frame, gui_holder.expression.children[i + 1], i == len(operands) - 1) if value is SingletonFalse: return SingletonFalse return value if operands else SingletonTrue
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_min_callable_length(self, 2, len(operands)) params = operands[0] if isinstance(params, Symbol): verify_exact_callable_length(self, 2, len(operands)) frame.assign( params, evaluate(operands[1], frame, gui_holder.expression.children[2])) return params elif isinstance(params, Pair): name = params.first operands[0] = params.rest if (not isinstance(name, Symbol)): raise OperandDeduceError(''.join( ['Expected a Symbol, not ', '{}'.format(name), '.'])) frame.assign( name, Lambda().execute(operands, frame, gui_holder, name.value)) return name else: raise OperandDeduceError(''.join([ 'Expected a Pair, not ', '{}'.format(params), ', as the first operand of define-macro.' ]))
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_exact_callable_length(self, 2, len(operands)) name = operands[0] if not isinstance(name, Symbol): raise OperandDeduceError(f"Expected a Symbol, not {name}, as the first operand of set!") frame.mutate(name, evaluate(operands[1], frame, gui_holder.expression.children[2])) return Undefined
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], Symbol): raise OperandDeduceError( f"Load expected a Symbol, received {operands[0]}.") if logger.fragile: raise IrreversibleOperationError() try: with open(f"{operands[0].value}.scm") as file: code = "(begin-noexcept" + "\n".join(file.readlines()) + "\n)" buffer = TokenBuffer([code]) expr = get_expression(buffer) gui_holder.expression.set_entries([ VisualExpression(expr, gui_holder.expression.display_value) ]) gui_holder.apply() return evaluate(expr, frame, gui_holder.expression.children[0], True) except OSError as e: raise LoadError(e)
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder, eval_operands=True): verify_exact_callable_length(self, 1, len(operands)) operand = operands[0] if eval_operands: operand = evaluate_all(operands, frame, gui_holder.expression.children[1:])[0] if not isinstance(operand, Promise): raise OperandDeduceError( f"Force expected a Promise, received {operand}") if operand.forced: return operand.expr if logger.fragile: raise IrreversibleOperationError() gui_holder.expression.set_entries([ VisualExpression(operand.expr, gui_holder.expression.display_value) ]) gui_holder.apply() evaluated = evaluate(operand.expr, operand.frame, gui_holder.expression.children[0]) if not logger.dotted and not isinstance(evaluated, (Pair, NilType)): raise TypeMismatchError( f"Unable to force a Promise evaluating to {operand.expr}, expected another Pair or Nil" ) operand.expr = evaluated operand.force() return operand.expr
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], Symbol)): raise OperandDeduceError(''.join([ 'Load expected a Symbol, received ', '{}'.format(operands[0]), '.' ])) if logger.fragile: raise IrreversibleOperationError() try: with open(''.join(['{}'.format(operands[0].value), '.scm'])) as file: code = (('(begin' + '\n'.join(file.readlines())) + '\n)') buffer = TokenBuffer([code]) expr = get_expression(buffer) gui_holder.expression.set_entries([ VisualExpression(expr, gui_holder.expression.display_value) ]) gui_holder.apply() return evaluate(expr, frame, gui_holder.expression.children[0], True) except OSError as e: raise LoadError(e)
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_min_callable_length(self, 1, len(operands)) for cond_i, cond in enumerate(operands): if not isinstance(cond, Pair): raise OperandDeduceError(f"Unable to evaluate clause of cond, as {cond} is not a Pair.") expanded = pair_to_list(cond) cond_holder = gui_holder.expression.children[cond_i + 1] eval_condition = SingletonTrue if not isinstance(expanded[0], Symbol) or expanded[0].value != "else": eval_condition = evaluate(expanded[0], frame, cond_holder.expression.children[0]) if (isinstance(expanded[0], Symbol) and expanded[0].value == "else") \ or eval_condition is not SingletonFalse: out = eval_condition for i, expr in enumerate(expanded[1:]): out = evaluate(expr, frame, cond_holder.expression.children[i + 1], i == len(expanded) - 2) return out return Undefined
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_min_callable_length(self, 1, len(operands)) out = None for i, (operand, holder) in enumerate( zip(operands, gui_holder.expression.children[1:])): out = evaluate(operand, frame, holder, i == len(operands) - 1) return out
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): out = Undefined for i, (operand, holder) in enumerate(zip(operands, gui_holder.expression.children[1:])): try: out = evaluate(operand, frame, holder, i == len(operands) - 1) except (SchemeError, RecursionError, ValueError, ZeroDivisionError) as e: logger.raw_out("LoadError: " + str(e) + "\n") return out
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): for (i, expr) in enumerate(operands): value = evaluate(expr, frame, gui_holder.expression.children[(i + 1)], (i == (len(operands) - 1))) if (value is not SingletonFalse): return value return SingletonFalse
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_min_callable_length(self, 2, len(operands)) bindings = operands[0] if ((not isinstance(bindings, Pair)) and (bindings is not Nil)): raise OperandDeduceError(''.join([ 'Expected first argument of let to be a Pair, not ', '{}'.format(bindings), '.' ])) new_frame = Frame('anonymous let', frame) gui_holder.expression.children[1].link_visual( VisualExpression(bindings)) bindings_holder = gui_holder.expression.children[1] bindings = pair_to_list(bindings) for (i, binding) in enumerate(bindings): if (not isinstance(binding, Pair)): raise OperandDeduceError(''.join([ 'Expected binding to be a Pair, not ', '{}'.format(binding), '.' ])) binding_holder = bindings_holder.expression.children[i] binding_holder.link_visual(VisualExpression(binding)) binding = pair_to_list(binding) if (len(binding) != 2): raise OperandDeduceError(''.join([ 'Expected binding to be of length 2, not ', '{}'.format(len(binding)), '.' ])) (name, expr) = binding if (not isinstance(name, Symbol)): raise OperandDeduceError(''.join([ 'Expected first element of binding to be a Symbol, not ', '{}'.format(name), '.' ])) new_frame.assign( name, evaluate(expr, frame, binding_holder.expression.children[1])) value = None for (i, (operand, holder)) in enumerate( zip(operands[1:], gui_holder.expression.children[2:])): value = evaluate(operand, new_frame, holder, (i == (len(operands) - 2))) new_frame.assign(return_symbol, value) return value
def quasiquote_evaluate(cls, expr: Expression, frame: Frame, gui_holder: Holder, splicing=False): is_well_formed = False if isinstance(expr, Pair): try: lst = pair_to_list(expr) except OperandDeduceError: pass else: is_well_formed = not any(map( lambda x: isinstance(x, Symbol) and x.value in ["unquote", "quasiquote", "unquote-splicing"], lst)) visual_expression = gui_holder.expression if not is_well_formed: visual_expression.children[2:] = [] if isinstance(expr, Pair): if isinstance(expr.first, Symbol) and expr.first.value in ("unquote", "unquote-splicing"): if expr.first.value == "unquote-splicing" and not splicing: raise OperandDeduceError("Unquote-splicing must be in list template.") gui_holder.evaluate() verify_exact_callable_length(expr.first, 1, len(pair_to_list(expr)) - 1) out = evaluate(expr.rest.first, frame, visual_expression.children[1]) visual_expression.value = out gui_holder.complete() return out elif isinstance(expr.first, Symbol) and expr.first.value == "quasiquote": visual_expression.value = expr gui_holder.complete() return expr else: if is_well_formed: out = [] for sub_expr, holder in zip(pair_to_list(expr), visual_expression.children): splicing = isinstance(sub_expr, Pair) and isinstance(sub_expr.first, Symbol) \ and sub_expr.first.value == "unquote-splicing" evaluated = Quasiquote.quasiquote_evaluate(sub_expr, frame, holder, splicing) if splicing: if not isinstance(evaluated, (Pair, NilType)): raise TypeMismatchError(f"Can only splice lists, not {evaluated}.") out.extend(pair_to_list(evaluated)) else: out.append(evaluated) out = make_list(out) else: if not logger.dotted: raise OperandDeduceError(f"{expr} is an ill-formed quasiquotation.") out = Pair(Quasiquote.quasiquote_evaluate(expr.first, frame, visual_expression.children[0]), Quasiquote.quasiquote_evaluate(expr.rest, frame, visual_expression.children[1])) visual_expression.value = out gui_holder.complete() return out else: visual_expression.value = expr gui_holder.complete() return expr
def execute(self, operands: List[Expression], frame: Frame, gui_holder: Holder): verify_exact_callable_length(self, 2, len(operands)) case = operands[0] operands[0] = evaluate(operands[0], frame, gui_holder.expression.children[1]) if not IsEqual().execute_evaluated(operands, frame).value: log.logger.raw_out( f"Evaluated {case}, expected {operands[1]}, got {operands[0]}.\n" ) else: log.logger.raw_out( f"Evaluated {case}, got {operands[0]}, as expected.\n") return Undefined
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): verify_exact_callable_length(self, 2, len(operands)) operands[0] = evaluate(operands[0], frame, gui_holder.expression.children[1]) return Pair(operands[0], Promise(operands[1], frame))
def quasiquote_evaluate(cls, expr: Expression, frame: Frame, gui_holder: Holder, splicing=False): is_well_formed = False if isinstance(expr, Pair): try: lst = pair_to_list(expr) except OperandDeduceError: pass else: is_well_formed = (not any( map((lambda x: (isinstance(x, Symbol) and (x.value in ['unquote', 'quasiquote', 'unquote-splicing']))), lst))) visual_expression = VisualExpression(expr) gui_holder.link_visual(visual_expression) if (not is_well_formed): visual_expression.children[2:] = [] if isinstance(expr, Pair): if (isinstance(expr.first, Symbol) and (expr.first.value in ('unquote', 'unquote-splicing'))): if ((expr.first.value == 'unquote-splicing') and (not splicing)): raise OperandDeduceError( 'Unquote-splicing must be in list template.') gui_holder.evaluate() verify_exact_callable_length(expr.first, 1, (len(pair_to_list(expr)) - 1)) out = evaluate(expr.rest.first, frame, visual_expression.children[1]) visual_expression.value = out gui_holder.complete() return out elif (isinstance(expr.first, Symbol) and (expr.first.value == 'quasiquote')): visual_expression.value = expr gui_holder.complete() return expr else: if is_well_formed: out = [] for (sub_expr, holder) in zip(pair_to_list(expr), visual_expression.children): splicing = (isinstance(sub_expr, Pair) and isinstance(sub_expr.first, Symbol) and (sub_expr.first.value == 'unquote-splicing')) evaluated = Quasiquote.quasiquote_evaluate( sub_expr, frame, holder, splicing) if splicing: if (not isinstance(evaluated, (Pair, NilType))): raise TypeMismatchError(''.join([ 'Can only splice lists, not ', '{}'.format(evaluated), '.' ])) out.extend(pair_to_list(evaluated)) else: out.append(evaluated) out = make_list(out) else: if (not logger.dotted): raise OperandDeduceError(''.join([ '{}'.format(expr), ' is an ill-formed quasiquotation.' ])) out = Pair( Quasiquote.quasiquote_evaluate( expr.first, frame, visual_expression.children[0]), Quasiquote.quasiquote_evaluate( expr.rest, frame, visual_expression.children[1])) visual_expression.value = out gui_holder.complete() return out else: visual_expression.value = expr gui_holder.complete() return expr
def string_exec(strings, out, visualize_tail_calls, global_frame=None): import log empty = False if global_frame is None: empty = True from environment import build_global_frame log.logger.f_delta -= 1 global_frame = build_global_frame() log.logger.active_frames.pop(0) # clear builtin frame log.logger.f_delta += 1 log.logger.global_frame = log.logger.frame_lookup[id(global_frame)] log.logger.graphics_lookup[id(global_frame)] = Canvas() log.logger.export_states = [] log.logger.roots = [] log.logger.frame_updates = [] log.logger._out = [] log.logger.visualize_tail_calls(visualize_tail_calls) for i, string in enumerate(strings): try: if not string.strip(): continue buff = TokenBuffer([string]) while not buff.done: expr = get_expression(buff) if expr is None: continue empty = False log.logger.new_expr() holder = Holder(expr, None) Root.setroot(holder) res = evaluate(expr, global_frame, holder) if res is not Undefined: out(res) if not log.logger.fragile and log.logger.autodraw: try: log.logger.raw_out("AUTODRAW" + json.dumps([log.logger.i, log.logger.heap.record(res)]) + "\n") except RecursionError: pass except (SchemeError, ZeroDivisionError, RecursionError, ValueError) as e: if isinstance(e, ParseError): log.logger.new_expr() raise if not log.logger.fragile: log.logger.raw_out("Traceback (most recent call last)\n") for j, expr in enumerate(log.logger.eval_stack[:MAX_TRACEBACK_LENGTH - 1]): log.logger.raw_out(str(j).ljust(3) + " " + expr + "\n") truncated = len(log.logger.eval_stack) - MAX_TRACEBACK_LENGTH if len(log.logger.eval_stack) > MAX_TRACEBACK_LENGTH: log.logger.raw_out(f"[{truncated} lines omitted from traceback]\n") log.logger.raw_out( str(len(log.logger.eval_stack) - 1).ljust(3) + " " + log.logger.eval_stack[-1] + "\n" ) log.logger.out(e) except TimeLimitException: if not log.logger.fragile: log.logger.out("Time limit exceeded.") log.logger.new_expr() if empty: log.logger.new_expr() holder = Holder(Undefined, None) Root.setroot(holder) evaluate(Undefined, global_frame, holder) log.logger.new_expr()
def string_exec(strings, out, global_frame=None): import log empty = False if (global_frame is None): empty = True from environment import build_global_frame log.logger.f_delta -= 1 global_frame = build_global_frame() log.logger.active_frames.pop(0) log.logger.f_delta += 1 log.logger.global_frame = log.logger.frame_lookup[id(global_frame)] log.logger.graphics_lookup[id(global_frame)] = Canvas() log.logger.export_states = [] log.logger.roots = [] log.logger.frame_updates = [] log.logger._out = [] for (i, string) in enumerate(strings): try: if (not string.strip()): continue buff = TokenBuffer([string]) while (not buff.done): expr = get_expression(buff) if (expr is None): continue empty = False log.logger.new_expr() holder = Holder(expr, None) Root.setroot(holder) res = evaluate(expr, global_frame, holder) if (res is not Undefined): out(res) if ((not log.logger.fragile) and log.logger.autodraw and isinstance(res, Pair)): log.logger.raw_out((('AUTODRAW' + json.dumps( [log.logger.i, log.logger.heap.record(res)])) + '\n')) except (SchemeError, ZeroDivisionError, RecursionError, ValueError) as e: if isinstance(e, ParseError): log.logger.new_expr() raise if (not log.logger.fragile): log.logger.raw_out('Traceback (most recent call last)\n') for (j, expr) in enumerate( log.logger.eval_stack[:(MAX_TRACEBACK_LENGTH - 1)]): log.logger.raw_out( (((str(j).ljust(3) + ' ') + expr) + '\n')) truncated = (len(log.logger.eval_stack) - MAX_TRACEBACK_LENGTH) if (len(log.logger.eval_stack) > MAX_TRACEBACK_LENGTH): log.logger.raw_out(''.join([ '[', '{}'.format(truncated), ' lines omitted from traceback]\n' ])) log.logger.raw_out((((str( (len(log.logger.eval_stack) - 1)).ljust(3) + ' ') + log.logger.eval_stack[(-1)]) + '\n')) log.logger.out(e) except TimeLimitException: if (not log.logger.fragile): log.logger.out('Time limit exceeded.') log.logger.new_expr() if empty: log.logger.new_expr() holder = Holder(Undefined, None) Root.setroot(holder) evaluate(Undefined, global_frame, holder) log.logger.new_expr()