Beispiel #1
0
    def runsource(self, source, filename='<input>', symbol='single'):
        global SIMPLE_TRACEBACKS

        def error_handler(e, use_simple_traceback=False):
            self.locals[mangle("*e")] = e
            if use_simple_traceback:
                print(e, file=sys.stderr)
            else:
                self.showtraceback()

        try:
            try:
                do = hy_parse(source)
            except PrematureEndOfInput:
                return True
        except LexException as e:
            if e.source is None:
                e.source = source
                e.filename = filename
            error_handler(e, use_simple_traceback=True)
            return False

        try:

            def ast_callback(main_ast, expr_ast):
                if self.spy:
                    # Mush the two AST chunks into a single module for
                    # conversion into Python.
                    new_ast = ast.Module(main_ast.body +
                                         [ast.Expr(expr_ast.body)])
                    print(astor.to_source(new_ast))

            value = hy_eval(do, self.locals, "__console__", ast_callback)
        except HyTypeError as e:
            if e.source is None:
                e.source = source
                e.filename = filename
            error_handler(e, use_simple_traceback=SIMPLE_TRACEBACKS)
            return False
        except Exception as e:
            error_handler(e)
            return False

        if value is not None:
            # Shift exisitng REPL results
            next_result = value
            for sym in self._repl_results_symbols:
                self.locals[sym], next_result = next_result, self.locals[sym]

            # Print the value.
            try:
                output = self.output_fn(value)
            except Exception as e:
                error_handler(e)
                return False
            print(output)
        return False
Beispiel #2
0
def cant_compile(expr):
    try:
        hy_compile(hy_parse(expr), "__main__")
        assert False
    except HyTypeError as e:
        # Anything that can't be compiled should raise a user friendly
        # error, otherwise it's a compiler bug.
        assert isinstance(e.expression, HyObject)
        assert e.message
        return e
    except HyCompileError as e:
        # Anything that can't be compiled should raise a user friendly
        # error, otherwise it's a compiler bug.
        assert isinstance(e.exception, HyTypeError)
        assert e.traceback
        return e
Beispiel #3
0
def run_command(source):
    tree = hy_parse(source)
    pretty_error(hy_eval, tree, module_name="__main__")
    return 0
Beispiel #4
0
def can_eval(expr):
    return hy_eval(hy_parse(expr))
Beispiel #5
0
def can_compile(expr):
    return hy_compile(hy_parse(expr), "__main__")
Beispiel #6
0
 def _import_error_test():
     try:
         _ = hy_compile(hy_parse("(import \"sys\")"), '')
     except HyTypeError:
         return "Error reported"
Beispiel #7
0
def test_stringer():
    _ast = hy_compile(hy_parse("(defn square [x] (* x x))"), '')

    assert type(_ast.body[0]) == ast.FunctionDef
Beispiel #8
0
def repl_import(filename, code, globals_d, context_name, lang = "hy"):
    """'code' should be a Hy sexp or None. If it's None, the
    file 'filename' is opened to get the code to evaluate, and
    None is returned. If it's a Hy sexp, it's evaluated and the
    result is returned.

    'lang' can be "hy" or "python" when 'code' is None, but must
    be 'hy' when 'code' is not None.

    We use different semantics from import *. In particular,
    __all__ is ignored.
   
    The goal of this somewhat involved method (including the
    module daylight-hy.load) is to ensure that:
    - (def x 15) (defn foo [] x) followed by (foo) at the command
      line works
    - After loading two files, you can access variables defined in
      file 1 that are shadowed by variables defined in file 2."""
    mname = 'daylight-' + os.path.dirname(os.path.abspath(filename))
    m = None
    try:
        if code is None:
            preexisting = mname in sys.modules
            try:
                with open(filename) as o:
                    text = o.read()
                if lang == "hy":
                    model = hy_parse(text)
                m = (sys.modules[mname]
                    if preexisting
                    else imp.new_module(mname))
                m.__file__ = filename
                if lang == "hy":
                    _ast = hy_compile(model, mname)
                    eval(ast_compile(_ast, filename, "exec"), m.__dict__)
                elif lang == "python":
                    exec(compile(text, filename, 'exec'), m.__dict__)
                else:
                    raise ValueError("Unknown language: {}".format(lang))
                sys.modules[mname] = m
            except (HyTypeError, LexException) as e:
                if e.source is None:
                    with open(filename, 'rt') as fp:
                        e.source = fp.read()
                    e.filename = filename
                raise
            except Exception:
                if not preexisting:
                    sys.modules.pop(mname, None)
                raise
            returnval = None
        else:
            if lang != 'hy':
                raise NotImplementedError
            m = sys.modules.get(mname)
            if not m:
                m = imp.new_module(mname)
                sys.modules[mname] = m
            returnval = hy_eval(code, m.__dict__, mname)
    finally:
        if m is not None:
            # Copy the module's names (except for names starting with "_")
            # into our globals.
            for k in dir(m):
               if not k.startswith('_'):
                   globals_d[k] = getattr(m, k)
    # Import macros.
    hy.macros.require(mname, context_name, "ALL")
    return returnval