Exemple #1
0
class BTTest(Base):
    _attrs = dict(a=Attr(int, 1, group='hash_exclude'),
                  b=Attr(float, 1.2, internal=True),
                  c=Attr(str,
                         'abc',
                         groups=('hash_exclude', 'generate_exclude'),
                         internal=True))
Exemple #2
0
class Logger(Tree):
    _opts = dict(init_validate=True)
    _attrs = dict(root=Attr(Event), current_parent=Attr(Event))

    @init_hook
    def _init(self):
        if type(self.root) is Node:
            self.root = Event()
        if not hasattr(self, 'current_parent'):
            self.current_parent = self.root

    def add(self, event):
        self.add_node(event, parent=self.current_parent)

    def plaintext(self, **kwargs):
        return self.root.plaintext(**kwargs)

    def pop(self):
        ret = self.current_parent
        self.current_parent = ret._parent
        return ret

    def push(self, event):
        self.add(event)
        self.current_parent = event

    def reset(self):
        self.current_parent = self.root
Exemple #3
0
class F(B):
    _seq_opts = dict(init_order=('d', 'e'))
    _attrs = dict(d=Attr(float,
                         internal=True,
                         init=lambda self: self.a + self.b),
                  e=Attr(float,
                         internal=True,
                         init=lambda self: self.d + self.a))
Exemple #4
0
class Position(Predicate):
    _attrs = dict(pos=Attr(int),
                  start_offset=Attr(int, 0),
                  pos_attr=Attr(STR, POSITION))
    _opts = dict(args=('pos', ))

    def eval(self, node, **kwargs):
        pos = getattr(node, self.pos_attr)
        return pos == (self.pos - self.start_offset)
Exemple #5
0
class ADOC(Base):
    '''Some documentation.'''
    _attrs = dict(a=Attr(int, doc='attr a'),
                  b=Attr(float, optional=True),
                  c=Attr(int, 2, optional=True, doc='attr c'))
    _opts = dict(args=('a', 'b', 'c'))

    def __init__(self, *args, **kwargs):
        '''Some more documentation.'''
        super(ADOC, self).__init__(*args, **kwargs)
Exemple #6
0
class BuiltinFunction(Function):
    _attrs = dict(body=Attr(Callable),
                  python=Attr(Callable),
                  pass_kwargs=Attr(bool, False))

    def call(self, env, **kwargs):
        args = [env[arg.name] for arg in self.signature]
        if self.pass_kwargs:
            return self.body(*args, **kwargs)
        return self.body(*args)
Exemple #7
0
class Sibling(Axis):
    _attrs = dict(following=Attr(bool, False), preceding=Attr(bool, False))
    _opts = dict(one_true=[('following', 'preceding')])

    def iterate(self, node, **kwargs):
        for k, s in enumerate(
                node.siblings(following=self.following,
                              preceding=self.preceding,
                              axis=True)):
            with assign(s, POSITION, k):
                yield s
Exemple #8
0
class I(B):
    _seq_opts = SeqDict()
    _attrs = dict(d=Attr(float, internal=True), e=Attr(float, internal=True))

    def _foo(self):
        self.d = self.a * self.b

    def _bar(self):
        self.e = self.d + 2

    _seq_opts.init_hooks = ('_foo', '_bar')
Exemple #9
0
class TransformEvent(StringEvent):
    _attrs = dict(obj=Attr(object), ret=Attr(object, optional=True))
    _opts = dict(optional_none=True)

    def display(self, depth=None):
        pre = ' ' * depth
        ret = pre + self._plaintext() + ' ({})\n'.format(self._id)
        if self.obj:
            ret += self.obj.viewable().pretty(indent=depth)
        if self.ret:
            ret += '\n'
            ret += self.ret.viewable().pretty(indent=depth)
        return ret
Exemple #10
0
class Following(Axis):
    _attrs = dict(include_self=Attr(bool, False))

    def iterate(self, node, **kwargs):
        for k, f in enumerate(node.following()):
            with assign(f, POSITION, k):
                yield f
Exemple #11
0
class Preceding(Axis):
    _attrs = dict(include_self=Attr(bool, False))

    def iterate(self, node, **kwargs):
        for k, p in enumerate(node.preceding()):
            with assign(p, POSITION, k):
                yield p
Exemple #12
0
class Ancestor(Axis):
    _attrs = dict(include_self=Attr(bool, False))

    def iterate(self, node, **kwargs):
        for k, a in enumerate(node.ancestors(include_self=self.include_self)):
            with assign(a, POSITION, k):
                yield a
Exemple #13
0
class Descendant(Axis):
    _attrs = dict(include_self=Attr(bool, False))

    def iterate(self, node, **kwargs):
        for k, d in enumerate(
                node.descendants(include_self=self.include_self)):
            with assign(d, POSITION, k):
                yield d
Exemple #14
0
class CT4(Base):
    _attrs = dict(a=Attr(int))

    @classmethod
    def _coerce_hook(cls, value):
        value['a'] += 1

    _seq_opts = dict(coerce_hooks=('_coerce_hook', ))
Exemple #15
0
class AltAttrs(Base, Harvester):
    _opts = dict(init_validate=True, args=('a', ))
    _attrs = dict(a=Attr(int, doc='abc'))

    @pre_create_hook
    def _harvest_attrs(clsdata):
        getfunc(Harvester._harvest_attrs)(clsdata)
        clsdata['dct']['d'] = ''.join(
            attr for attr, value in sorted(clsdata['dct']['_attrs'].items()))
Exemple #16
0
class Function(SyntagmathonNode):
    _attrs = dict(name=Attr((Variable, STR)),
                  signature=Attr(List(Variable)),
                  body=Attr((List(SyntagmathonNode), tuple)),
                  placeholder=Attr(bool, False))
    _opts = dict(args=('name', 'signature', 'body'))

    def __call__(self, *args_, **kwargs):
        args = {}
        for k, arg in enumerate(args_):
            args[self.signature[k].name] = arg

        for key, value in kwargs.items():
            if key in args:
                raise TypeError("Parameter {} specified twice".format(key))
            args[key] = value

        return Call(self, args)

    def call(self, env, **kwargs):
        return eval(self.body, env, **kwargs)

    def eval(self, env, **kwargs):
        env[self.get_name()] = self
        return self

    def get_name(self):
        return self.name if isinstance(self.name, STR) else self.name.name

    def to_python(self, **kwargs):
        from syn.python.b import Arguments, FunctionDef, Pass

        if VER < '3':
            args = Arguments(
                [to_python(arg, **kwargs) for arg in self.signature])
        else:
            from syn.python.b import Arg
            args = Arguments([Arg(arg.name) for arg in self.signature])

        body = to_python(self.body, **kwargs)
        if not body:
            body = [Pass()]
        body[-1] = body[-1].as_return()
        return FunctionDef(self.name, args, body)
Exemple #17
0
class I4(I):
    _attrs = dict(f=Attr(int))

    @init_hook
    @setstate_hook
    def _baz(self):
        if not hasattr(self, 'f'):
            self.f = self.a
        else:
            self.f += 1
Exemple #18
0
class Frame(Base):
    _attrs = dict(globals=Attr(dict, init=lambda self: dict()),
                  locals=Attr(dict, init=lambda self: dict()))
    _opts = dict(init_validate=True)

    def __getitem__(self, key):
        if key in self.locals:
            return self.locals[key]
        elif key in self.globals:
            return self.globals[key]
        raise KeyError(key)

    def __setitem__(self, key, value):
        self.locals[key] = value

    def __delitem__(self, key):
        if key in self.locals:
            del self.locals[key]
        elif key in self.globals:
            del self.globals[key]
        else:
            raise KeyError(key)

    def __iter__(self):
        return iter(sorted(set(self.locals) | set(self.globals)))

    def __len__(self):
        return len(set(self.locals) | set(self.globals))

    def items(self):
        for key in self:
            yield key, self[key]

    def gensym(self):
        pass

    def set_global(self, key, value):
        self.globals[key] = value

    def update(self, dct):
        for key, value in dct.items():
            self[key] = value
Exemple #19
0
class GenSym(Base):
    _attrs = dict(names=Attr(set, init=lambda self: set()),
                  counter=Attr(Counter, init=lambda self: Counter()))
    _opts = dict(args=('names', ), init_validate=True)

    def add(self, name):
        self.names.add(name)

    def _generate(self):
        return '_gensym_{}'.format(self.counter())

    def generate(self):
        ret = self._generate()
        while ret in self.names:
            ret = self._generate()
        self.add(ret)
        return ret

    def update(self, names):
        self.names.update(names)
Exemple #20
0
class Type(Query):
    _attrs = dict(type=Attr(Type_, AnyType()))
    _opts = dict(args=('type', ))

    @init_hook
    def _dispatch_type(self):
        if not isinstance(self.type, Type_):
            self.type = Type_.dispatch(self.type)

    def iterate(self, node, **kwargs):
        if self.type.query(node):
            yield node
Exemple #21
0
class Call(SyntagmathonNode):
    _attrs = dict(func=Attr(Function), args=Attr(dict))
    _opts = dict(args=('func', 'args'))

    def eval(self, env, **kwargs):
        func = self.func
        args = {
            name: eval(value, env, **kwargs)
            for name, value in self.args.items()
        }
        if func.placeholder:
            func = env[self.func.get_name()]
            names = [name.name for name in self.func.signature]
            args = {
                func.signature[names.index(name)].name: value
                for name, value in args.items()
            }
        env.push(args)
        if kwargs.get('trace', False):
            depth = kwargs.get('depth', 0)
            pre = kwargs.get('tab', '  ') * depth
            argstr = ', '.join('{}={}'.format(name, value)
                               for name, value in args.items())
            print(pre + '{}({})'.format(func.get_name(), argstr))
            kwargs['depth'] = depth + 1
        ret = func.call(env, **kwargs)
        env.pop()
        return ret

    def to_python(self, **kwargs):
        from syn.python.b import Call, Name
        args = [
            to_python(self.args[arg.name], **kwargs)
            for arg in self.func.signature
        ]
        if hasattr(self.func, 'python'):
            return self.func.python(*args, **kwargs)
        func = Name(self.func.name)
        return Call(func, args)
Exemple #22
0
class Env(Base):
    _attrs = dict(frames=Attr(List(Frame), init=lambda self: list([Frame()])))
    _opts = dict(init_validate=True)

    current_frame = property(lambda self: self.frames[-1])

    def __getitem__(self, key):
        return self.current_frame[key]

    def __setitem__(self, key, value):
        self.current_frame[key] = value

    def __delitem__(self, key):
        del self.current_frame[key]

    def __iter__(self):
        return iter(self.current_frame)

    def __len__(self):
        return len(self.current_frame)

    def items(self):
        for item in self.current_frame.items():
            yield item

    def gensym(self):
        pass

    def globals(self):
        return dict(self.current_frame.globals)

    def locals(self):
        return dict(self.current_frame.locals)

    def push(self, dct):
        globs = self.globals()
        globs.update(self.locals())
        self.frames.append(Frame(globals=globs, locals=dct))

    def pop(self):
        return self.frames.pop()

    def set_global(self, key, value):
        self.current_frame.set_global(key, value)

    def update(self, dct):
        self.current_frame.update(dct)
Exemple #23
0
class PythonTree(Tree):
    _opts = dict(init_validate=True)
    _attrs = dict(root=Attr(RootNode))

    def abstract(self):
        def op(node):
            node.lineno = None

        ret = deepcopy(self)
        ret.depth_first(op)
        return ret

    def emit(self, **kwargs):
        return self.root.emit(**kwargs)

    def to_ast(self, **kwargs):
        return self.root.to_ast(**kwargs)
Exemple #24
0
class Variable(SyntagmathonNode):
    _attrs = dict(name=Attr(STR))
    _opts = dict(args=('name', ))

    def __call__(self, *args):
        from .function import Function
        names = enum(str, max_enum=len(args))
        func = Function(self.name, [Variable(name) for name in names], [],
                        placeholder=True)
        return func(*args)

    def eval(self, env, **kwargs):
        return env[self.name]

    def to_python(self, **kwargs):
        from syn.python.b import Name
        return Name(self.name)
Exemple #25
0
 class LW3(ListWrapper):
     _attrs = dict(a=Attr(int), b=Attr(float))
Exemple #26
0
class Value(Query):
    _attrs = dict(value=Attr(None))
    _opts = dict(max_len=0, args=('value', ))

    def __call__(self, node, **kwargs):
        return self.value
Exemple #27
0
class Name(Predicate):
    _attrs = dict(name=Attr(STR), name_attr=Attr(STR, '_name'))
    _opts = dict(args=('name', ))

    def eval(self, node, **kwargs):
        return getattr(node, self.name_attr) == self.name
Exemple #28
0
class LWGT3(LWGT1):
    _attrs = dict(_list=Attr(Schema(Sequence(int, float, int))))
Exemple #29
0
class RNVTree(Tree):
    _attrs = dict(root=Attr(Root1))
Exemple #30
0
class LWPA(ListWrapper):
    _opts = dict(max_len=3, args=['a', 'b'], init_validate=True)
    _attrs = dict(a=Attr(int), b=Attr(float, default=3.2))