def test_tree_subs(): tree = LTree.parse((thunk.fromvalue(1) + 2) - 3) assert tree.subs({ Call(Normal(op.add), (Normal(1), Normal(2)), {}): Normal(4) }) == Call(Normal(op.sub), (Normal(4), Normal(3)), {}) other_tree = LTree.parse(thunk.fromvalue(1) + 1 + 1) assert other_tree.subs({1: 2}) == LTree.parse(thunk.fromvalue(2) + 2 + 2)
def _unwrap_name(arg): name = capture_string() if LTree.parse(arg) != Call(Normal(name_lookup), (Normal(name),), {}): # this should actually be a recursive destructure like in haskell # but I haven't gotten to that yet raise SyntaxError("can't assign to expression") return name.value
def __new__(mcls, name, bases, dict_): if bases and bases[0] is mcls._marker: return super().__new__(mcls, name, (), dict_) for name in ('__module__', '__qualname__'): del dict_[name] if dict_: raise TypeError( 'Case dictionaries should only contain alternatives, got: %r' % dict_ ) alttrees = { LTree.parse(alt._if_not_alt): alt for alt in dict_._constructors.values() } altconstructors = { k.args[0]: v for k, v in alttrees.items() } for alt, expr in alttrees.items(): # drop the first element of the iter because it is the node itself for leaf in alt.leaves(): try: if altconstructors[leaf] is not expr: del altconstructors[leaf] except (KeyError, TypeError): pass return partial(scrutinize, altconstructors.values())
def test_tree_contains(): tree = LTree.parse((thunk.fromvalue(1) + 2) + 3) assert 1 in tree assert 2 in tree assert 3 in tree sub = Call(Normal(op.add), (Normal(1), Normal(2)), {}) assert sub in tree assert Call(Normal(op.add), (sub, Normal(3)), {}) in tree
def scrutinize(self, scrutine, context_frame): constructor = type(scrutine) if constructor.__name__ != self._constructor_name: raise NoMatch() kwargs = scrutine._kwargs # the context to evaluate the thunk in context = { Call(Normal(name_lookup), (Normal(name),), {}): Normal(value) for name, value in merge( vars(builtins), context_frame.f_globals, context_frame.f_locals, # the newly bound arguments have the highest precedence dict(zip(self._argnames, scrutine._args)), {v: kwargs[k] for k, v in self._kwargnames.items()}, ).items() } bound_tree = LTree.parse(self._expr).subs(context) return strict(bound_tree.lcompile())
def __strict__(self): return __class__._get(*ltree_to_dask(LTree.parse(self)))
def test_tree_hash(expr): assert hash(LTree.parse(expr())) == hash(LTree.parse(expr()))
def test_tree_eq(expr): assert LTree.parse(expr()) == LTree.parse(expr())
def test_compile_of_parse_identity(expr): assert strict(LTree.parse(expr()).lcompile()) == strict(expr())