SHARE
TWEET

Untitled

a guest Nov 20th, 2019 101 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """A Scheme interpreter and its read-eval-print loop."""
  2. from __future__ import print_function  # Python 2 compatibility
  3.  
  4. from scheme_builtins import *
  5. from scheme_reader import *
  6. from ucb import main, trace
  7.  
  8. ##############
  9. # Eval/Apply #
  10. ##############
  11.  
  12.  
  13. def scheme_eval(expr, env, _=None): # Optional third argument is ignored
  14.     """Evaluate Scheme expression EXPR in environment ENV.
  15.  
  16.     >>> expr = read_line('(+ 2 2)')
  17.     >>> expr
  18.     Pair('+', Pair(2, Pair(2, nil)))
  19.     >>> scheme_eval(expr, create_global_frame())
  20.     4
  21.     """
  22.     # Evaluate atoms
  23.     if scheme_symbolp(expr):
  24.         return env.lookup(expr)
  25.     elif self_evaluating(expr):
  26.         return expr
  27.  
  28.     # All non-atomic expressions are lists (combinations)
  29.     if not scheme_listp(expr):
  30.         raise SchemeError('malformed list: {0}'.format(repl_str(expr)))
  31.     first, rest = expr.first, expr.rest
  32.     if scheme_symbolp(first) and first in SPECIAL_FORMS:
  33.         return SPECIAL_FORMS[first](rest, env)
  34.     else:
  35.         # BEGIN PROBLEM 4
  36.         expr_eval = expr.map(lambda subexpr: scheme_eval(subexpr, env, _))
  37.         return scheme_apply(expr_eval.first, expr_eval.rest, env)
  38.         # END PROBLEM 4
  39.  
  40. def self_evaluating(expr):
  41.     """Return whether EXPR evaluates to itself."""
  42.     return (scheme_atomp(expr) and not scheme_symbolp(expr)) or expr is None
  43.  
  44. def scheme_apply(procedure, args, env):
  45.     """Apply Scheme PROCEDURE to argument values ARGS (a Scheme list) in
  46.     environment ENV."""
  47.     check_procedure(procedure)
  48.     if isinstance(procedure, BuiltinProcedure):
  49.         return procedure.apply(args, env)
  50.     else:
  51.         new_env = procedure.make_call_frame(args, env)
  52.         return eval_all(procedure.body, new_env)
  53.  
  54. def eval_all(expressions, env):
  55.     """Evaluate each expression in the Scheme list EXPRESSIONS in
  56.     environment ENV and return the value of the last."""
  57.     # BEGIN PROBLEM 7
  58.     if expressions is nil:
  59.         return None
  60.     return_expr = expressions.map(lambda eval_expr: scheme_eval(eval_expr, env))
  61.     while return_expr.rest is not nil:
  62.         return_expr = return_expr.rest
  63.     return return_expr.first
  64.     # END PROBLEM 7
  65.  
  66. ################
  67. # Environments #
  68. ################
  69.  
  70. class Frame(object):
  71.     """An environment frame binds Scheme symbols to Scheme values."""
  72.  
  73.     def __init__(self, parent):
  74.         """An empty frame with parent frame PARENT (which may be None)."""
  75.         self.bindings = {}
  76.         self.parent = parent
  77.  
  78.     def __repr__(self):
  79.         if self.parent is None:
  80.             return '<Global Frame>'
  81.         s = sorted(['{0}: {1}'.format(k, v) for k, v in self.bindings.items()])
  82.         return '<{{{0}}} -> {1}>'.format(', '.join(s), repr(self.parent))
  83.  
  84.     def define(self, symbol, value):
  85.         """Define Scheme SYMBOL to have VALUE."""
  86.         # BEGIN PROBLEM 2
  87.         self.bindings[symbol] = value
  88.         # END PROBLEM 2
  89.  
  90.     def lookup(self, symbol):
  91.         """Return the value bound to SYMBOL. Errors if SYMBOL is not found."""
  92.         # BEGIN PROBLEM 2
  93.         value = self.bindings.get(symbol)
  94.         if value is not None: #need to specify None because value itself can be 0 or False
  95.             return value
  96.         elif self.parent:
  97.             return Frame.lookup(self.parent, symbol)
  98.         "*** YOUR CODE HERE ***"
  99.         # END PROBLEM 2
  100.         raise SchemeError('unknown identifier: {0}'.format(symbol))
  101.  
  102.  
  103.     def make_child_frame(self, formals, vals):
  104.         """Return a new local frame whose parent is SELF, in which the symbols
  105.         in a Scheme list of formal parameters FORMALS are bound to the Scheme
  106.         values in the Scheme list VALS. Raise an error if too many or too few
  107.         vals are given.
  108.  
  109.         >>> env = create_global_frame()
  110.         >>> formals, expressions = read_line('(a b c)'), read_line('(1 2 3)')
  111.         >>> env.make_child_frame(formals, expressions)
  112.         <{a: 1, b: 2, c: 3} -> <Global Frame>>
  113.         """
  114.         # BEGIN PROBLEM 10
  115.         child_frame = Frame(self)
  116.         env_vars, env_vals = formals, vals
  117.         while env_vars is not nil and env_vals is not nil:
  118.             child_frame.define(env_vars.first, env_vals.first)
  119.             env_vars, env_vals = env_vars.rest, env_vals.rest
  120.         if env_vars is not nil or env_vals is not nil:
  121.             raise SchemeError('Values do not correspond to variables.')
  122.         return child_frame
  123.         # END PROBLEM 10
  124.  
  125. ##############
  126. # Procedures #
  127. ##############
  128.  
  129. class Procedure(object):
  130.     """The supertype of all Scheme procedures."""
  131.  
  132. def scheme_procedurep(x):
  133.     return isinstance(x, Procedure)
  134.  
  135. class BuiltinProcedure(Procedure):
  136.     """A Scheme procedure defined as a Python function."""
  137.  
  138.     def __init__(self, fn, use_env=False, name='builtin'):
  139.         self.name = name
  140.         self.fn = fn
  141.         self.use_env = use_env
  142.  
  143.     def __str__(self):
  144.         return '#[{0}]'.format(self.name)
  145.  
  146.     def apply(self, args, env):
  147.         """Apply SELF to ARGS in ENV, where ARGS is a Scheme list.
  148.  
  149.         >>> env = create_global_frame()
  150.         >>> plus = env.bindings['+']
  151.         >>> twos = Pair(2, Pair(2, nil))
  152.         >>> plus.apply(twos, env)
  153.         4
  154.         """
  155.         if not scheme_listp(args):
  156.             raise SchemeError('arguments are not in a list: {0}'.format(args))
  157.         # Convert a Scheme list to a Python list
  158.         python_args = []
  159.         while args is not nil:
  160.             python_args.append(args.first)
  161.             args = args.rest
  162.         # BEGIN PROBLEM 3
  163.         if self.use_env:
  164.             python_args.append(env)
  165.         try:
  166.             return self.fn(*python_args)
  167.         except TypeError:
  168.             raise SchemeError('Wrong number of arguments for', self.fn)
  169.         # END PROBLEM 3
  170.  
  171. class LambdaProcedure(Procedure):
  172.     """A procedure defined by a lambda expression or a define form."""
  173.  
  174.     def __init__(self, formals, body, env):
  175.         """A procedure with formal parameter list FORMALS (a Scheme list),
  176.         whose body is the Scheme list BODY, and whose parent environment
  177.         starts with Frame ENV."""
  178.         self.formals = formals
  179.         self.body = body
  180.         self.env = env
  181.  
  182.     def make_call_frame(self, args, env):
  183.         """Make a frame that binds my formal parameters to ARGS, a Scheme list
  184.         of values, for a lexically-scoped call evaluated in environment ENV."""
  185.         # BEGIN PROBLEM 11
  186.         return self.env.make_child_frame(self.formals, args)
  187.         # END PROBLEM 11
  188.  
  189.     def __str__(self):
  190.         return str(Pair('lambda', Pair(self.formals, self.body)))
  191.  
  192.     def __repr__(self):
  193.         return 'LambdaProcedure({0}, {1}, {2})'.format(
  194.             repr(self.formals), repr(self.body), repr(self.env))
  195.  
  196. class MacroProcedure(LambdaProcedure):
  197.     """A macro: a special form that operates on its unevaluated operands to
  198.     create an expression that is evaluated in place of a call."""
  199.  
  200.     def apply_macro(self, operands, env):
  201.         """Apply this macro to the operand expressions."""
  202.         return complete_apply(self, operands, env)
  203.  
  204. def add_builtins(frame, funcs_and_names):
  205.     """Enter bindings in FUNCS_AND_NAMES into FRAME, an environment frame,
  206.     as built-in procedures. Each item in FUNCS_AND_NAMES has the form
  207.     (NAME, PYTHON-FUNCTION, INTERNAL-NAME)."""
  208.     for name, fn, proc_name in funcs_and_names:
  209.         frame.define(name, BuiltinProcedure(fn, name=proc_name))
  210.  
  211. #################
  212. # Special Forms #
  213. #################
  214.  
  215. # Each of the following do_xxx_form functions takes the cdr of a special form as
  216. # its first argument---a Scheme list representing a special form without the
  217. # initial identifying symbol (if, lambda, quote, ...). Its second argument is
  218. # the environment in which the form is to be evaluated.
  219.  
  220. def do_define_form(expressions, env):
  221.     """Evaluate a define form."""
  222.     check_form(expressions, 2)
  223.     target = expressions.first
  224.     if scheme_symbolp(target):
  225.         check_form(expressions, 2, 2)
  226.         # BEGIN PROBLEM 5
  227.         val_bind = scheme_eval(expressions.rest.first, env)
  228.         env.define(target, val_bind)
  229.         return target
  230.         # END PROBLEM 5
  231.     elif isinstance(target, Pair) and scheme_symbolp(target.first):
  232.         # BEGIN PROBLEM 9
  233.         #restructure expressions into a lambda expression
  234.         return do_define_form(Pair(target.first, Pair(Pair('lambda', Pair(target.rest, expressions.rest)), nil)), env)
  235.         # END PROBLEM 9
  236.     else:
  237.         bad_target = target.first if isinstance(target, Pair) else target
  238.         raise SchemeError('non-symbol: {0}'.format(bad_target))
  239.  
  240. def do_quote_form(expressions, env):
  241.     """Evaluate a quote form."""
  242.     check_form(expressions, 1, 1)
  243.     # BEGIN PROBLEM 6
  244.     return expressions.first #expressions is a list containing only one expression, resulted in ((quote hello)) instead of (quote hello)
  245.     # END PROBLEM 6
  246.  
  247. def do_begin_form(expressions, env):
  248.     """Evaluate a begin form."""
  249.     check_form(expressions, 1)
  250.     return eval_all(expressions, env)
  251.  
  252. def do_lambda_form(expressions, env):
  253.     """Evaluate a lambda form."""
  254.     check_form(expressions, 2)
  255.     formals = expressions.first
  256.     check_formals(formals)
  257.     # BEGIN PROBLEM 8
  258.     return LambdaProcedure(expressions.first, expressions.rest, env)
  259.     # END PROBLEM 8
  260.  
  261. def do_if_form(expressions, env):
  262.     """Evaluate an if form."""
  263.     check_form(expressions, 2, 3)
  264.     if scheme_truep(scheme_eval(expressions.first, env)):
  265.         return scheme_eval(expressions.rest.first, env)
  266.     elif len(expressions) == 3:
  267.         return scheme_eval(expressions.rest.rest.first, env)
  268.  
  269. def do_and_form(expressions, env):
  270.     """Evaluate a (short-circuited) and form."""
  271.     # BEGIN PROBLEM 12
  272.     return_val, eval_expr = True, expressions
  273.     while eval_expr is not nil:
  274.         return_val, eval_expr = scheme_eval(eval_expr.first, env), eval_expr.rest
  275.         if scheme_falsep(return_val):
  276.             return return_val
  277.     return return_val
  278.     # END PROBLEM 12
  279.  
  280. def do_or_form(expressions, env):
  281.     """Evaluate a (short-circuited) or form."""
  282.     # BEGIN PROBLEM 12
  283.     return_val, eval_expr = False, expressions
  284.     while eval_expr is not nil:
  285.         return_val, eval_expr = scheme_eval(eval_expr.first, env), eval_expr.rest
  286.         if scheme_truep(return_val):
  287.             return return_val
  288.     return return_val
  289.     # END PROBLEM 12
  290.  
  291. def do_cond_form(expressions, env):
  292.     """Evaluate a cond form."""
  293.     while expressions is not nil:
  294.         clause = expressions.first
  295.         check_form(clause, 1)
  296.         if clause.first == 'else':
  297.             test = True
  298.             if expressions.rest != nil:
  299.                 raise SchemeError('else must be last')
  300.         else:
  301.             test = scheme_eval(clause.first, env)
  302.         if scheme_truep(test):
  303.             # BEGIN PROBLEM 13
  304.             if clause.rest is nil:
  305.                 return test
  306.             else:
  307.                 return eval_all(clause.rest, env)
  308.             # END PROBLEM 13
  309.         expressions = expressions.rest
  310.  
  311. def do_let_form(expressions, env):
  312.     """Evaluate a let form."""
  313.     check_form(expressions, 2)
  314.     let_env = make_let_frame(expressions.first, env)
  315.     return eval_all(expressions.rest, let_env)
  316.  
  317. def make_let_frame(bindings, env):
  318.     """Create a child frame of ENV that contains the definitions given in
  319.     BINDINGS. The Scheme list BINDINGS must have the form of a proper bindings
  320.     list in a let expression: each item must be a list containing a symbol
  321.     and a Scheme expression."""
  322.     if not scheme_listp(bindings):
  323.         raise SchemeError('bad bindings list in let form')
  324.     # BEGIN PROBLEM 14
  325.     formals, vals, bind_eval = nil, nil, bindings
  326.     while bind_eval is not nil: #every element of bind_eval is a "symbol/value binding pair" that should be a linked list of length two
  327.         if bind_eval.first.rest.rest is not nil: #length of linked list is longer than two
  328.             raise SchemeError('Invalid input.')
  329.         formals, vals, bind_eval = Pair(bind_eval.first.first, formals), Pair(scheme_eval(bind_eval.first.rest.first, env), vals), bind_eval.rest
  330.     check_formals(formals)
  331.     return env.make_child_frame(formals, vals)
  332.     # END PROBLEM 14
  333.  
  334. def do_define_macro(expressions, env):
  335.     """Evaluate a define-macro form."""
  336.     # BEGIN Problem 20
  337.     "*** YOUR CODE HERE ***"
  338.     # END Problem 20
  339.  
  340.  
  341. def do_quasiquote_form(expressions, env):
  342.     """Evaluate a quasiquote form with parameters EXPRESSIONS in
  343.     environment ENV."""
  344.     def quasiquote_item(val, env, level):
  345.         """Evaluate Scheme expression VAL that is nested at depth LEVEL in
  346.         a quasiquote form in environment ENV."""
  347.         if not scheme_pairp(val):
  348.             return val
  349.         if val.first == 'unquote':
  350.             level -= 1
  351.             if level == 0:
  352.                 expressions = val.rest
  353.                 check_form(expressions, 1, 1)
  354.                 return scheme_eval(expressions.first, env)
  355.         elif val.first == 'quasiquote':
  356.             level += 1
  357.  
  358.         return val.map(lambda elem: quasiquote_item(elem, env, level))
  359.  
  360.     check_form(expressions, 1, 1)
  361.     return quasiquote_item(expressions.first, env, 1)
  362.  
  363. def do_unquote(expressions, env):
  364.     raise SchemeError('unquote outside of quasiquote')
  365.  
  366.  
  367. SPECIAL_FORMS = {
  368.     'and': do_and_form,
  369.     'begin': do_begin_form,
  370.     'cond': do_cond_form,
  371.     'define': do_define_form,
  372.     'if': do_if_form,
  373.     'lambda': do_lambda_form,
  374.     'let': do_let_form,
  375.     'or': do_or_form,
  376.     'quote': do_quote_form,
  377.     'define-macro': do_define_macro,
  378.     'quasiquote': do_quasiquote_form,
  379.     'unquote': do_unquote,
  380. }
  381.  
  382. # Utility methods for checking the structure of Scheme programs
  383.  
  384. def check_form(expr, min, max=float('inf')):
  385.     """Check EXPR is a proper list whose length is at least MIN and no more
  386.     than MAX (default: no maximum). Raises a SchemeError if this is not the
  387.     case.
  388.  
  389.     >>> check_form(read_line('(a b)'), 2)
  390.     """
  391.     if not scheme_listp(expr):
  392.         raise SchemeError('badly formed expression: ' + repl_str(expr))
  393.     length = len(expr)
  394.     if length < min:
  395.         raise SchemeError('too few operands in form')
  396.     elif length > max:
  397.         raise SchemeError('too many operands in form')
  398.  
  399. def check_formals(formals):
  400.     """Check that FORMALS is a valid parameter list, a Scheme list of symbols
  401.     in which each symbol is distinct. Raise a SchemeError if the list of
  402.     formals is not a list of symbols or if any symbol is repeated.
  403.  
  404.     >>> check_formals(read_line('(a b c)'))
  405.     """
  406.     symbols = set()
  407.     def check_and_add(symbol, is_last):
  408.         if not scheme_symbolp(symbol):
  409.             raise SchemeError('non-symbol: {0}'.format(symbol))
  410.         if symbol in symbols:
  411.             raise SchemeError('duplicate symbol: {0}'.format(symbol))
  412.         symbols.add(symbol)
  413.  
  414.     while isinstance(formals, Pair):
  415.         check_and_add(formals.first, formals.rest is nil)
  416.         formals = formals.rest
  417.  
  418.  
  419. def check_procedure(procedure):
  420.     """Check that PROCEDURE is a valid Scheme procedure."""
  421.     if not scheme_procedurep(procedure):
  422.         raise SchemeError('{0} is not callable: {1}'.format(
  423.             type(procedure).__name__.lower(), repl_str(procedure)))
  424.  
  425. #################
  426. # Dynamic Scope #
  427. #################
  428.  
  429. class MuProcedure(Procedure):
  430.     """A procedure defined by a mu expression, which has dynamic scope.
  431.      _________________
  432.     < Scheme is cool! >
  433.      -----------------
  434.             \   ^__^
  435.              \  (oo)\_______
  436.                 (__)\       )\/\
  437.                     ||----w |
  438.                     ||     ||
  439.     """
  440.  
  441.     def __init__(self, formals, body):
  442.         """A procedure with formal parameter list FORMALS (a Scheme list) and
  443.         Scheme list BODY as its definition."""
  444.         self.formals = formals
  445.         self.body = body
  446.  
  447.     # BEGIN PROBLEM 15
  448.     def make_call_frame(self, args, env):
  449.         return env.make_child_frame(self.formals, args)
  450.     # END PROBLEM 15
  451.  
  452.     def __str__(self):
  453.         return str(Pair('mu', Pair(self.formals, self.body)))
  454.  
  455.     def __repr__(self):
  456.         return 'MuProcedure({0}, {1})'.format(
  457.             repr(self.formals), repr(self.body))
  458.  
  459. def do_mu_form(expressions, env):
  460.     """Evaluate a mu form."""
  461.     check_form(expressions, 2)
  462.     formals = expressions.first
  463.     check_formals(formals)
  464.     # BEGIN PROBLEM 15
  465.     return MuProcedure(expressions.first, expressions.rest)
  466.     # END PROBLEM 15
  467.  
  468. SPECIAL_FORMS['mu'] = do_mu_form
  469.  
  470. ###########
  471. # Streams #
  472. ###########
  473.  
  474. class Promise(object):
  475.     """A promise."""
  476.     def __init__(self, expression, env):
  477.         self.expression = expression
  478.         self.env = env
  479.  
  480.     def evaluate(self):
  481.         if self.expression is not None:
  482.             value = scheme_eval(self.expression, self.env)
  483.             if not (value is nil or isinstance(value, Pair)):
  484.                 raise SchemeError("result of forcing a promise should be a pair or nil, but was %s" % value)
  485.             self.value = value
  486.             self.expression = None
  487.         return self.value
  488.  
  489.     def __str__(self):
  490.         return '#[promise ({0}forced)]'.format(
  491.                 'not ' if self.expression is not None else '')
  492.  
  493. def do_delay_form(expressions, env):
  494.     """Evaluates a delay form."""
  495.     check_form(expressions, 1, 1)
  496.     return Promise(expressions.first, env)
  497.  
  498. def do_cons_stream_form(expressions, env):
  499.     """Evaluate a cons-stream form."""
  500.     check_form(expressions, 2, 2)
  501.     return Pair(scheme_eval(expressions.first, env),
  502.                 do_delay_form(expressions.rest, env))
  503.  
  504. SPECIAL_FORMS['cons-stream'] = do_cons_stream_form
  505. SPECIAL_FORMS['delay'] = do_delay_form
  506.  
  507. ##################
  508. # Tail Recursion #
  509. ##################
  510.  
  511. class Thunk(object):
  512.     """An expression EXPR to be evaluated in environment ENV."""
  513.     def __init__(self, expr, env):
  514.         self.expr = expr
  515.         self.env = env
  516.  
  517. def complete_apply(procedure, args, env):
  518.     """Apply procedure to args in env; ensure the result is not a Thunk."""
  519.     val = scheme_apply(procedure, args, env)
  520.     if isinstance(val, Thunk):
  521.         return scheme_eval(val.expr, val.env)
  522.     else:
  523.         return val
  524.  
  525. def optimize_tail_calls(original_scheme_eval):
  526.     """Return a properly tail recursive version of an eval function."""
  527.     def optimized_eval(expr, env, tail=False):
  528.         """Evaluate Scheme expression EXPR in environment ENV. If TAIL,
  529.         return a Thunk containing an expression for further evaluation.
  530.         """
  531.         if tail and not scheme_symbolp(expr) and not self_evaluating(expr):
  532.             return Thunk(expr, env)
  533.  
  534.         result = Thunk(expr, env)
  535.         # BEGIN
  536.         "*** YOUR CODE HERE ***"
  537.         # END
  538.     return optimized_eval
  539.  
  540.  
  541.  
  542.  
  543.  
  544.  
  545. ################################################################
  546. # Uncomment the following line to apply tail call optimization #
  547. ################################################################
  548. # scheme_eval = optimize_tail_calls(scheme_eval)
  549.  
  550.  
  551.  
  552.  
  553.  
  554.  
  555. ####################
  556. # Extra Procedures #
  557. ####################
  558.  
  559. def scheme_map(fn, s, env):
  560.     check_type(fn, scheme_procedurep, 0, 'map')
  561.     check_type(s, scheme_listp, 1, 'map')
  562.     return s.map(lambda x: complete_apply(fn, Pair(x, nil), env))
  563.  
  564. def scheme_filter(fn, s, env):
  565.     check_type(fn, scheme_procedurep, 0, 'filter')
  566.     check_type(s, scheme_listp, 1, 'filter')
  567.     head, current = nil, nil
  568.     while s is not nil:
  569.         item, s = s.first, s.rest
  570.         if complete_apply(fn, Pair(item, nil), env):
  571.             if head is nil:
  572.                 head = Pair(item, nil)
  573.                 current = head
  574.             else:
  575.                 current.rest = Pair(item, nil)
  576.                 current = current.rest
  577.     return head
  578.  
  579. def scheme_reduce(fn, s, env):
  580.     check_type(fn, scheme_procedurep, 0, 'reduce')
  581.     check_type(s, lambda x: x is not nil, 1, 'reduce')
  582.     check_type(s, scheme_listp, 1, 'reduce')
  583.     value, s = s.first, s.rest
  584.     while s is not nil:
  585.         value = complete_apply(fn, scheme_list(value, s.first), env)
  586.         s = s.rest
  587.     return value
  588.  
  589. ################
  590. # Input/Output #
  591. ################
  592.  
  593. def read_eval_print_loop(next_line, env, interactive=False, quiet=False,
  594.                          startup=False, load_files=(), report_errors=False):
  595.     """Read and evaluate input until an end of file or keyboard interrupt."""
  596.     if startup:
  597.         for filename in load_files:
  598.             scheme_load(filename, True, env)
  599.     while True:
  600.         try:
  601.             src = next_line()
  602.             while src.more_on_line:
  603.                 expression = scheme_read(src)
  604.                 result = scheme_eval(expression, env)
  605.                 if not quiet and result is not None:
  606.                     print(repl_str(result))
  607.         except (SchemeError, SyntaxError, ValueError, RuntimeError) as err:
  608.             if report_errors:
  609.                 if isinstance(err, SyntaxError):
  610.                     err = SchemeError(err)
  611.                     raise err
  612.             if (isinstance(err, RuntimeError) and
  613.                 'maximum recursion depth exceeded' not in getattr(err, 'args')[0]):
  614.                 raise
  615.             elif isinstance(err, RuntimeError):
  616.                 print('Error: maximum recursion depth exceeded')
  617.             else:
  618.                 print('Error:', err)
  619.         except KeyboardInterrupt:  # <Control>-C
  620.             if not startup:
  621.                 raise
  622.             print()
  623.             print('KeyboardInterrupt')
  624.             if not interactive:
  625.                 return
  626.         except EOFError:  # <Control>-D, etc.
  627.             print()
  628.             return
  629.  
  630. def scheme_load(*args):
  631.     """Load a Scheme source file. ARGS should be of the form (SYM, ENV) or
  632.     (SYM, QUIET, ENV). The file named SYM is loaded into environment ENV,
  633.     with verbosity determined by QUIET (default true)."""
  634.     if not (2 <= len(args) <= 3):
  635.         expressions = args[:-1]
  636.         raise SchemeError('"load" given incorrect number of arguments: '
  637.                           '{0}'.format(len(expressions)))
  638.     sym = args[0]
  639.     quiet = args[1] if len(args) > 2 else True
  640.     env = args[-1]
  641.     if (scheme_stringp(sym)):
  642.         sym = eval(sym)
  643.     check_type(sym, scheme_symbolp, 0, 'load')
  644.     with scheme_open(sym) as infile:
  645.         lines = infile.readlines()
  646.     args = (lines, None) if quiet else (lines,)
  647.     def next_line():
  648.         return buffer_lines(*args)
  649.  
  650.     read_eval_print_loop(next_line, env, quiet=quiet, report_errors=True)
  651.  
  652. def scheme_load_all(directory, env):
  653.     """
  654.     Loads all .scm files in the given directory, alphabetically. Used only
  655.         in tests/ code.
  656.     """
  657.     assert scheme_stringp(directory)
  658.     directory = eval(directory)
  659.     import os
  660.     for x in sorted(os.listdir(".")):
  661.         if not x.endswith(".scm"):
  662.             continue
  663.         scheme_load(x, env)
  664.  
  665. def scheme_open(filename):
  666.     """If either FILENAME or FILENAME.scm is the name of a valid file,
  667.     return a Python file opened to it. Otherwise, raise an error."""
  668.     try:
  669.         return open(filename)
  670.     except IOError as exc:
  671.         if filename.endswith('.scm'):
  672.             raise SchemeError(str(exc))
  673.     try:
  674.         return open(filename + '.scm')
  675.     except IOError as exc:
  676.         raise SchemeError(str(exc))
  677.  
  678. def create_global_frame():
  679.     """Initialize and return a single-frame environment with built-in names."""
  680.     env = Frame(None)
  681.     env.define('eval',
  682.                BuiltinProcedure(scheme_eval, True, 'eval'))
  683.     env.define('apply',
  684.                BuiltinProcedure(complete_apply, True, 'apply'))
  685.     env.define('load',
  686.                BuiltinProcedure(scheme_load, True, 'load'))
  687.     env.define('load-all',
  688.                BuiltinProcedure(scheme_load_all, True, 'load-all'))
  689.     env.define('procedure?',
  690.                BuiltinProcedure(scheme_procedurep, False, 'procedure?'))
  691.     env.define('map',
  692.                BuiltinProcedure(scheme_map, True, 'map'))
  693.     env.define('filter',
  694.                BuiltinProcedure(scheme_filter, True, 'filter'))
  695.     env.define('reduce',
  696.                BuiltinProcedure(scheme_reduce, True, 'reduce'))
  697.     env.define('undefined', None)
  698.     add_builtins(env, BUILTINS)
  699.     return env
  700.  
  701. @main
  702. def run(*argv):
  703.     import argparse
  704.     parser = argparse.ArgumentParser(description='CS 61A Scheme Interpreter')
  705.     parser.add_argument('-load', '-i', action='store_true',
  706.                        help='run file interactively')
  707.     parser.add_argument('file', nargs='?',
  708.                         type=argparse.FileType('r'), default=None,
  709.                         help='Scheme file to run')
  710.     args = parser.parse_args()
  711.  
  712.  
  713.     next_line = buffer_input
  714.     interactive = True
  715.     load_files = []
  716.  
  717.     if args.file is not None:
  718.         if args.load:
  719.             load_files.append(getattr(args.file, 'name'))
  720.         else:
  721.             lines = args.file.readlines()
  722.             def next_line():
  723.                 return buffer_lines(lines)
  724.             interactive = False
  725.  
  726.     read_eval_print_loop(next_line, create_global_frame(), startup=True,
  727.                          interactive=interactive, load_files=load_files)
  728.     tscheme_exitonclick()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top