Beispiel #1
0
def eval_hy_string(obj):
    try:
        import hy
    except ImportError:
        print("Hy not supported in this kernel. Execute `pip install hy` if you want this support.")

    expr = hy.read_str(obj)
    ret = hy.eval(expr)

    return ret
Beispiel #2
0
def nsHyEval(ns, expression):
    env = nsHYmkenv(ns)
    env = nsImportPfun(ns, env, "/psbin", "/pbin")
    try:
        _expr = read_str(str(expression))
        _res = eval(_expr, env)
    except Exception as e:
        nsGlobalError(ns, "{}".format(e))
        return None
    return _res
def __ein_eval_hy_string(obj):
    try:
        import hy
    except ImportError:
        print("Hy not supported in this kernel. Execute `pip install hy` if you want this support.")

    expr = hy.read_str(obj)
    ret = hy.eval(expr)

    return ret
Beispiel #4
0
def nsHyEvalRestrict(ns, expression, *path):
    env = {}
    env = nsImportPfun(ns, env, *path)
    print(list(env.keys()))
    try:
        _expr = read_str(str(expression))
        _res = eval(_expr, env)
    except Exception as e:
        nsGlobalError(ns, "{}".format(e))
        return None
    return _res
Beispiel #5
0
 def _execute_script(self, witch_code):
     """Given a pile of script revision code, this function prepends the
     (witch) macro definition and then reads and evals the combined code."""
     script_text = self.script_revision.code
     with_header = '{}\n{}'.format(WITCH_HEADER, script_text)
     buff = io.StringIO(with_header)
     stop = False
     result = None
     while not stop:
         try:
             tree = hy.read(buff)
             result = hy.eval(tree,
                              namespace={'ScriptEngine': ScriptEngine})
         except EOFError:
             stop = True
     return result
Beispiel #6
0
def eval(*abstr_tree, source="", supermacro=True):
	if supermacro:
		if type(abstr_tree[0]) == hy.HyExpression:
			abstr_tree = hy.HyExpression([hy.HySymbol('do'),
				hy.HyExpression([hy.HySymbol('supermacro'),*abstr_tree])])
		else:
			abstr_tree = hy.HyExpression([hy.HySymbol('do'),
				hy.HyExpression([hy.HySymbol('supermacro'),abstr_tree])])
	else:
		if type(abstr_tree[0]) == hy.HyExpression:
			abstr_tree = hy.HyExpression([hy.HySymbol('do'),*abstr_tree])
		else:
			abstr_tree = hy.HyExpression([hy.HySymbol('do'),abstr_tree])
	each_eval = hy.eval(abstr_tree, globalscope, source=source)
	try:
		return each_eval[-1]
	except:
		return each_eval
Beispiel #7
0
 def do_execute_direct(self, code):
     '''
     Exceute the code, and return result.
     '''
     self.result = None
     #### try to parse it:
     try:
         tokens = tokenize(code)
         self.result = hy.eval(tokens, locals=self.env)
     except Exception as e:
         self.Error(traceback.format_exc())
         self.kernel_resp.update({
             "status": "error",
             'ename' : e.__class__.__name__,   # Exception name, as a string
             'evalue' : e.__class__.__name__,  # Exception value, as a string
             'traceback' : [], # traceback frames as strings
         })
         return None
     return self.result
Beispiel #8
0
# tUtils.py - Utils written by TDL9
# Import this module as t

# import numpy as np
import functools as fn
import itertools as itt
import hy

# eval Hy expression
# see hy document for more details
hyc = hy.eval(hy.read_str("(comp hy.eval hy.read_str)"))

# functools.reduce(function, iterable[, initializer])
reduce = fn.reduce

# built-in function, filter(function, iterable) ~= (item for item in iterable if function(item))
filter = filter

# built-in function, map(function, iterable, ...)
map = map

# starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
starmap = itt.starmap

# product(p, q, … [repeat=1])
product = itt.product

# flatten ["foo" (, 1 2) [1 [2 3] 4] "bar"] => ['foo', 1, 2, 1, 2, 3, 4, 'bar']
flatten = hyc("flatten")

# return reversed iterator
Beispiel #9
0
def test_hy_python_require():
    # https://github.com/hylang/hy/issues/1911
    test = "(do (require [tests.resources.macros [test-macro]]) (test-macro) blah)"
    assert hy.eval(hy.read_str(test)) == 1
Beispiel #10
0
 def hy(self, code):
     if hy is None:
         self.log(hyErr)
         return
     expr = hy.read_str(code)
     self.log(hy.eval(expr, self.evalArgs))
Beispiel #11
0
            cyear,
            centity)
    else:
        guts = 'This work is licensed under {}. Copyright {} {}.'.format(
            license_html[license_url],
            year_created
                if year_created and not info['daylight-show-mdate']
                else '{}–{}'.format(year_created, year_modified)
                if year_created and year_created != year_modified
                else year_modified,
            authors_html)
    text = text.replace(rep,
        '<footer id="license-footer"><p>{}</p></footer>'.format(guts) +
        rep)

# Apply any post-processing block defined by the file.
if info['postproc']:
    lang, _, body = info['postproc'].partition('\n')
    if lang == 'python':
        exec(body)
        text = POSTPROC(text)
    elif lang == 'hy':
        import hy
        POSTPROC = hy.eval(hy.read_str("(fn [text]\n" + body + "\n)"))
        text = POSTPROC(text)
    else:
        raise ValueError("Unknown POSTPROC language " + repr(lang))

# Done.
print(text, end = '')
Beispiel #12
0
def hy_eval_in_ns(code, ns):
    """Return the result of evaluating the given Hy code in the given
    namespace."""
    return hy.eval(hy.read_str("(do\n" + code + "\n)\n"),
                   locals=ns,
                   module=sys.modules[ns['__name__']])
Beispiel #13
0
 def eval(self, code):
     self._code = code
     code = f"(do (require [hy.extra.anaphoric [*]]) {code})"
     expr = hy.read_str(code)
     self._value = hy.eval(expr)
Beispiel #14
0
import hy

cool = hy.read_str("(+ 1 2)")
print hy.eval(cool)
Beispiel #15
0
 def eval_str(s):
     return hy.eval(hy.read_str(s))
Beispiel #16
0
    async def event_handler(self, details, websocket):
        if details == None:
            return None
        if details[1] == 0: return False  # was just unpressed
        # Check if
        if details[0] in ['start', 'select']:
            # our control actions.
            if details[0] == "start":
                print("> Executing")
                try:
                    expression = hy.read_str(self.typer.display_line(
                        self.line))
                    print("Result:", hy.eval(expression))
                    self.last_returned = hy.eval(expression)
                except Exception as e:
                    print("Exception:", e.__str__())
            elif details[0] == "select":
                self.typer.remove_line(self.line)
        else:
            # Are we in prediction mode or not
            if self.mode == "PREDICT":
                result = self.typer.predict_handler(details[0], self.line)
                if (result != None):
                    if result == "next_prediction":
                        self.curr_pred = (self.curr_pred + 1) \
                            % len(self.predictions_found)
                    elif result == "prev_prediction":
                        self.curr_pred = (self.curr_pred - 1) \
                            % len(self.predictions_found)
                    elif result == "select_prediction":
                        self.typer.append_to_pos(
                            self.line,
                            (self.predictions_found[self.curr_pred] +
                             " ")[len(self.curr):])
                        self.mode = "INSERT"
                        self.predictions_found = []
                        self.curr_pred = []
                    elif result == "exit_prediction_mode":
                        self.mode = "INSERT"
                        self.predictions_found = []
                        self.curr_pred = []
            elif self.mode == "INSERT":
                result = self.typer.add_key(details[0], self.line)
                # check if the user typed a special key combo
                if (result != None):
                    if result == 'up_line':
                        self.line -= 1
                        if self.line <= 0:
                            self.line = 0
                    elif result == 'down_line':
                        if self.line < self.typer.lines() - 1:
                            self.line += 1
                        elif self.line == self.typer.lines() - 1:
                            self.line += 1
                            self.typer.new_line()
                    elif result == 'pos_left':
                        self.typer.changepos(self.line,
                                             self.typer.pos(self.line) - 1)
                    elif result == 'pos_right':
                        self.typer.changepos(self.line,
                                             self.typer.pos(self.line) + 1)
                    elif result == 'remove_current':
                        self.typer.remove_key(self.line)
                    elif result == 'predictive_mode':
                        self.mode = "PREDICT"
                        self.predictions()
        # Get word we are working on
        # Stupid prompt.
        prompt = "dp {} {} {} {}> ".format(self.mode,self.line, \
                                    self.typer.pos(self.line), \
                                    self.typer.inprogress(self.line))
        print("{} {}".format(prompt, self.typer.display_line(self.line)))
        print("{} ^".format(" " * (len(prompt) + self.typer.pos(self.line))))

        if self.mode == "PREDICT":
            print("Prediction:")
            i = 0
            for pred in self.predictions_found:
                print("{} {}".format([" ", "*"][i == self.curr_pred], pred))
                i += 1
        everything = {
            "mode": self.mode,
            "line": self.line,
            "pos": self.typer.pos(self.line),
            "progress": self.typer.inprogress(self.line),
            "line_text": self.typer.display_line(self.line),
            "predictions": self.predictions_found,
            "current_prediction": self.curr_pred,
            "last_output": ""
        }
        await websocket.send(json.dumps(everything))
Beispiel #17
0
 def eval_str(s):
     return hy.eval(hy.read_str(s))
Beispiel #18
0
def nsHyEval(ns, expression):
    env = nsHYmkenv(ns)
    env = nsImportPfun(ns, env, "/psbin", "/pbin")
    _expr = read_str(str(expression))
    _res = eval(_expr, env)
    return _res