def eval(self, code): """Evals the given code. Returns a dict with reponses.""" self.ret = [] # We might catch errors when tokenizing code. try: tokens = tokenize(code) except: self._format_excp(sys.exc_info()) return self.ret # Setting stdout in a way so we can catch anything printed and return that oldout = sys.stdout oldin = sys.stdin stdout = None sys.stdout = StringIO() for i in tokens: try: p = str(hy_eval(i, self.mod.__dict__, "__main__")) except: self._format_excp(sys.exc_info()) else: self.ret.append({"value": p, "ns": 'None'}) # If there is nothing in return, we see if anything is in stdout if p == "None": stdout = sys.stdout.getvalue() if stdout: self.ret.append({'out': stdout}) sys.stdout = oldout return self.ret
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
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 = import_buffer_to_hst(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
def runsource(self, source, filename='<input>', symbol='single'): global SIMPLE_TRACEBACKS try: try: do = import_buffer_to_hst(source) except PrematureEndOfInput: return True except LexException as e: if e.source is None: e.source = source e.filename = filename print(e, file=sys.stderr) 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 if SIMPLE_TRACEBACKS: print(e, file=sys.stderr) else: self.showtraceback() return False except Exception: self.showtraceback() return False if value is not None: # Make the last non-None value available to # the user as `_`. self.locals['_'] = value # Print the value. try: output = self.output_fn(value) except Exception: self.showtraceback() return False print(output) return False
def evaluate(self, context, dialect='psql'): ctx = dict(globals()) ctx['esckwd'] = EscapeKeywords(dialect) ctx.update(context) result = string_to_quoted_expr(self.expression) result = hy_eval(result, ctx, 'inline_hy')[0] quote_func = lambda p: quote_param(p, dialect) conv_func = quote_func if self.quote else EscapeKeywords(dialect) if result is None: result = '' elif isinstance(result, list) or isinstance(result, imap): result = ', '.join(list(map(conv_func, result))) else: result = conv_func(result) return result
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)) if code is None: m = import_file_to_module(mname, filename, lang) 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) # 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, too. hy.macros.require(mname, context_name, all_macros = True) return returnval
def evaluate(self, context, dialect='psql'): ctx = dict(globals()) ctx['esckwd'] = EscapeKeywords(dialect) ctx['quotename'] = QuoteName(dialect) ctx['coalesce'] = coalesce ctx['chainlist'] = chainlist ctx.update(context) result = string_to_quoted_expr(self.expression) result = hy_eval(result, ctx, 'inline_hy')[0] quote_func = lambda p: quote_param(p, dialect) conv_func = quote_func if self.quote else EscapeKeywords(dialect) if result is None: result = '' elif isinstance(result, list) or isinstance(result, map): #result = list(result) result = ', '.join(list(map(conv_func, result))) else: result = conv_func(result) return result
def can_eval(expr): return hy_eval(import_buffer_to_hst(expr))
def can_eval(expr): return hy_eval(hy_parse(expr))
def heval(tokens): try: return hy_eval(import_buffer_to_hst(tokens), {}, '<string>') except Exception as e: print(e)
def exec_fn(code, ns): tokens = HyList(tokenize(code)) hy_eval(tokens, ns, '__pineal__')
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