Пример #1
0
def as_ast(dct):
    """See https://docs.python.org/2/library/ast.html"""
    if dct['ast_type'] == "Module":
        return ast.Module(dct["body"])
    elif dct['ast_type'] == "Interactive":
        return ast.Interactive(dct["body"])
    elif dct['ast_type'] == "Expression":
        return ast.Expression(dct["body"])
    elif dct['ast_type'] == "Suite":
        return ast.Suite(dct["body"])
    elif dct['ast_type'] == "FunctionDef":
        return ast.FunctionDef(dct["name"], dct["args"], dct["body"],
                               dct["decorator_list"])
    elif dct['ast_type'] == "ClassDef":
        return ast.ClassDef(dct["name"], dct["bases"], dct["body"],
                            dct["decorator_list"])
    elif dct['ast_type'] == "Return":
        return ast.Return(dct["value"])
    elif dct['ast_type'] == "Delete":
        return ast.Delete(dct["targets"])
    elif dct['ast_type'] == "Assign":
        return ast.Assign(dct["targets"], dct["value"])
    elif dct['ast_type'] == "AugAssign":
        return ast.AugAssign(dct["target"], dct["op"], dct["value"])
    elif dct['ast_type'] == "Print":
        return ast.Print(dct["dest"], dct["values"], dct["nl"])
    elif dct['ast_type'] == "For":
        return ast.For(dct["target"], dct["iter"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "While":
        return ast.While(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "If":
        return ast.If(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "With":
        return ast.With(dct["context_expr"], dct["optional_vars"], dct["body"])
    elif dct['ast_type'] == "Raise":
        return ast.Raise(dct["type"], dct["inst"], dct["tback"])
    elif dct['ast_type'] == "TryExcept":
        return ast.TryExcept(dct["body"], dct["handlers"], dct["orelse"])
    elif dct['ast_type'] == "TryFinally":
        return ast.TryFinally(dct["body"], dct["finalbody"])
    elif dct['ast_type'] == "Assert":
        return ast.Assert(dct["test"], dct["msg"])
    elif dct['ast_type'] == "Import":
        return ast.Import(dct["names"])
    elif dct['ast_type'] == "ImportFrom":
        return ast.ImportFrom(dct["module"], dct["names"], dct["level"])
    elif dct['ast_type'] == "Exec":
        return ast.Exec(dct["body"], dct["globals"], dct["locals"])
    elif dct['ast_type'] == "Global":
        return ast.Global(dct["names"])
    elif dct['ast_type'] == "Expr":
        return ast.Expr(dct["value"])
    elif dct['ast_type'] == "Pass":
        return ast.Pass()
    elif dct['ast_type'] == "Break":
        return ast.Break()
    elif dct['ast_type'] == "Continue":
        return ast.Continue()
    elif dct['ast_type'] == "BoolOp":
        return ast.BoolOp(dct["op"], dct["values"])
    elif dct['ast_type'] == "BinOp":
        return ast.BinOp(dct["left"], dct["op"], dct["right"])
    elif dct['ast_type'] == "UnaryOp":
        return ast.UnaryOp(dct["op"], dct["operand"])
    elif dct['ast_type'] == "Lambda":
        return ast.Lambda(dct["args"], dct["body"])
    elif dct['ast_type'] == "IfExp":
        return ast.IfExp(dct["test"], dct["body"], dct["orelse"])
    elif dct['ast_type'] == "Dict":
        return ast.Dict(dct["keys"], dct["values"])
    elif dct['ast_type'] == "Set":
        return ast.Set(dct["elts"])
    elif dct['ast_type'] == "ListComp":
        return ast.ListComp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "SetComp":
        return ast.SetComp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "DictComp":
        return ast.DictComp(dct["key"], dct["value"], dct["generators"])
    elif dct['ast_type'] == "GeneratorExp":
        return ast.GeneratorExp(dct["elt"], dct["generators"])
    elif dct['ast_type'] == "Yield":
        return ast.Yield(dct["value"])
    elif dct['ast_type'] == "Compare":
        return ast.Compare(dct["left"], dct["ops"], dct["comparators"])
    elif dct['ast_type'] == "Call":
        return ast.Call(dct["func"], dct["args"], dct["keywords"],
                        dct["starargs"], dct["kwargs"])
    elif dct['ast_type'] == "Repr":
        return ast.Repr(dct["value"])
    elif dct['ast_type'] == "Num":
        return ast.Num(dct["n"])
    elif dct['ast_type'] == "Str":
        # Converting to ASCII
        return ast.Str(dct["s"].encode('ascii', 'ignore'))
    elif dct['ast_type'] == "Attribute":
        return ast.Attribute(dct["value"], dct["attr"], dct["ctx"])
    elif dct['ast_type'] == "Subscript":
        return ast.Subscript(dct["value"], dct["slice"], dct["ctx"])
    elif dct['ast_type'] == "Name":
        return ast.Name(dct["id"], dct["ctx"])
    elif dct['ast_type'] == "List":
        return ast.List(dct["elts"], dct["ctx"])
    elif dct['ast_type'] == "Tuple":
        return ast.Tuple(dct["elts"], dct["ctx"])
    elif dct['ast_type'] == "Load":
        return ast.Load()
    elif dct['ast_type'] == "Store":
        return ast.Store()
    elif dct['ast_type'] == "Del":
        return ast.Del()
    elif dct['ast_type'] == "AugLoad":
        return ast.AugLoad()
    elif dct['ast_type'] == "AugStore":
        return ast.AugStore()
    elif dct['ast_type'] == "Param":
        return ast.Param()
    elif dct['ast_type'] == "Ellipsis":
        return ast.Ellipsis()
    elif dct['ast_type'] == "Slice":
        return ast.Slice(dct["lower"], dct["upper"], dct["step"])
    elif dct['ast_type'] == "ExtSlice":
        return ast.ExtSlice(dct["dims"])
    elif dct['ast_type'] == "Index":
        return ast.Index(dct["value"])
    elif dct['ast_type'] == "And":
        return ast.And()
    elif dct['ast_type'] == "Or":
        return ast.Or()
    elif dct['ast_type'] == "Add":
        return ast.Add()
    elif dct['ast_type'] == "Sub":
        return ast.Sub()
    elif dct['ast_type'] == "Mult":
        return ast.Mult()
    elif dct['ast_type'] == "Div":
        return ast.Div()
    elif dct['ast_type'] == "Mod":
        return ast.Mod()
    elif dct['ast_type'] == "Pow":
        return ast.Pow()
    elif dct['ast_type'] == "LShift":
        return ast.LShift()
    elif dct['ast_type'] == "RShift":
        return ast.RShift()
    elif dct['ast_type'] == "BitOr":
        return ast.BitOr()
    elif dct['ast_type'] == "BitXor":
        return ast.BitXor()
    elif dct['ast_type'] == "BitAnd":
        return ast.BitAnd()
    elif dct['ast_type'] == "FloorDiv":
        return ast.FloorDiv()
    elif dct['ast_type'] == "Invert":
        return ast.Invert()
    elif dct['ast_type'] == "Not":
        return ast.Not()
    elif dct['ast_type'] == "UAdd":
        return ast.UAdd()
    elif dct['ast_type'] == "USub":
        return ast.USub()
    elif dct['ast_type'] == "Eq":
        return ast.Eq()
    elif dct['ast_type'] == "NotEq":
        return ast.NotEq()
    elif dct['ast_type'] == "Lt":
        return ast.Lt()
    elif dct['ast_type'] == "LtE":
        return ast.LtE()
    elif dct['ast_type'] == "Gt":
        return ast.Gt()
    elif dct['ast_type'] == "GtE":
        return ast.GtE()
    elif dct['ast_type'] == "Is":
        return ast.Is()
    elif dct['ast_type'] == "IsNot":
        return ast.IsNot()
    elif dct['ast_type'] == "In":
        return ast.In()
    elif dct['ast_type'] == "NotIn":
        return ast.NotIn()
    elif dct['ast_type'] == "comprehension":
        return ast.comprehension(dct["target"], dct["iter"], dct["ifs"])
    elif dct['ast_type'] == "ExceptHandler":
        return ast.ExceptHandler(dct["type"], dct["name"], dct["body"])
    elif dct['ast_type'] == "arguments":
        return ast.arguments(dct["args"], dct["vararg"], dct["kwarg"],
                             dct["defaults"])
    elif dct['ast_type'] == "keyword":
        return ast.keyword(dct["arg"], dct["value"])
    elif dct['ast_type'] == "alias":
        return ast.alias(dct["name"], dct["asname"])
    else:
        return dct
Пример #2
0
def test_hdl_expression():
    """Test expressions."""
    expr_1 = "PARAM-2"
    expr_2 = "PARAM_X+1"
    expr_3 = "a and ~b"
    hdl_expr_1 = HDLExpression(ast.parse(expr_1, mode="eval"))
    hdl_expr_2 = HDLExpression(ast.parse(expr_2, mode="eval"))
    hdl_expr_3 = HDLExpression(expr_3)
    print(hdl_expr_3.dumps())
    sum = hdl_expr_1 + hdl_expr_2
    neg = ~sum
    bool_neg = sum.bool_neg()
    bool_and = hdl_expr_1.bool_and(hdl_expr_2)
    bool_or = hdl_expr_1.bool_or(hdl_expr_2)
    print(sum.dumps())
    print(neg.dumps())
    print(bool_neg.dumps())
    print(bool_and.dumps())
    print(bool_or.dumps())

    _ = hdl_expr_1 & 0x1
    _ = 0x1 | hdl_expr_1
    _ = 0x1 & hdl_expr_1
    _ = 0x1 ^ hdl_expr_1
    _ = hdl_expr_1 ^ 0x1

    my_signal = HDLSignal("reg", "signal_a", size=2)
    _ = HDLExpression(HDLIntegerConstant(1))
    _ = HDLExpression(1)
    _ = HDLExpression(my_signal)
    _ = HDLExpression(HDLSignalSlice(my_signal, 1))
    _ = HDLExpression(my_signal[1:0])

    # test reduction
    expr_a = HDLExpression("value_a")
    expr_b = HDLExpression("value_b")
    full_expr = expr_a << 0 | expr_b << 16 | HDLExpression(0)

    case_1 = ast.BinOp(left=ast.Constant(value=0),
                       op=ast.BitOr(),
                       right=ast.Name(id="VAR"))

    case_2 = ast.BinOp(left=ast.Constant(value=1),
                       op=ast.Mult(),
                       right=ast.Name(id="VAR"))

    case_3 = ast.BinOp(left=ast.Constant(value=0),
                       op=ast.Mult(),
                       right=ast.Name(id="VAR"))

    hdl_expr = HDLExpression(ast.Expression(body=case_1))
    hdl_expr_2 = HDLExpression(ast.Expression(body=case_2))
    hdl_expr_3 = HDLExpression(ast.Expression(body=case_3))
    print(hdl_expr.dumps())
    print(hdl_expr_2.dumps())

    reduced_1 = HDLExpression._reduce_binop(case_1)
    hdl_expr = HDLExpression(ast.Expression(body=reduced_1))
    print(hdl_expr.dumps())

    reduced_2 = HDLExpression._reduce_binop(case_2)
    hdl_expr_2 = HDLExpression(ast.Expression(body=reduced_2))
    print(hdl_expr_2.dumps())

    reduced_3 = HDLExpression._reduce_binop(case_3)
    hdl_expr_3 = HDLExpression(ast.Expression(body=reduced_3))
    print(hdl_expr_3.dumps())

    print(full_expr.dumps())
    full_expr.reduce_expr()
    print(full_expr.dumps())
Пример #3
0
def expr_rewrite(head, tail):
    if tail:
        for op, each in tail:
            head = ast.BinOp(head, ast.BitOr(), each, **loc @ op)
    return head
Пример #4
0
def mk_bitor(a, b):
    return ast.BinOp(left=a, right=b, op=ast.BitOr())
Пример #5
0
class Char(object):
    def __init__(self, str, lineno=0):
        self.value = str
        self.lineno = lineno


op_ast_map = {
    '+': ast.Add(),
    '-': ast.Sub(),
    '*': ast.Mult(),
    '/': ast.Div(),
    '%': ast.Mod(),
    '**': ast.Pow(),
    '<<': ast.LShift(),
    '>>': ast.RShift(),
    '|': ast.BitOr(),
    '^^': ast.BitXor(),
    '&&': ast.BitAnd(),
    '//': ast.FloorDiv(),
    '==': ast.Eq(),
    '!=': ast.NotEq(),
    '<': ast.Lt(),
    '<=': ast.LtE(),
    '>': ast.Gt(),
    '>=': ast.GtE(),
    'is': ast.Is(),
    'is_not': ast.IsNot(),
    'in': ast.In(),
    'not_in': ast.NotIn(),
    'and': ast.And(),
    'or': ast.Or()
Пример #6
0
 "^^": ast.Pow(),
 "**": ast.Pow(),
 "pow": ast.Pow(),
 "power": ast.Pow(),
 "to the": ast.Pow(),
 "to the power": ast.Pow(),
 "to the power of": ast.Pow(),
 "%": ast.Mod(),
 "mod": ast.Mod(),
 "modulo": ast.Mod(),
 "!": ast.Not(),
 "not": ast.Not(),
 "&": ast.And(),  # BitAnd ENGLISH: a & b ~== a and b
 "&&": ast.And(),
 "and": ast.And(),
 "|": ast.BitOr(),
 "||": ast.Or(),
 "or": ast.Or(),
 "does not equal": ast.NotEq(),
 "doesn't equal": ast.NotEq(),
 "not equal": ast.NotEq(),
 "is not": ast.NotEq(),
 "isn't": ast.NotEq(),
 "isnt": ast.NotEq(),
 "!=": ast.NotEq(),
 "≠": ast.NotEq(),
 "=": ast.Eq(),
 "==": ast.Eq(),
 "===": ast.Eq(),
 "~=": ast.Eq(),
 "is": ast.Eq(),
Пример #7
0
 def mutate_BitAnd(self, node):
     return ast.BitOr()
Пример #8
0
 def bitor(self, other: Union[T, Expr[T]]) -> BinOp[T]:
     return BinOp(self, ast.BitOr(), other)
Пример #9
0
class LtnsCompiler:
    def _temp_func_name(self):
        if not hasattr(self, '_temp'):
            self._temp = 0
        self._temp += 1
        return f'_temp_func_{self._temp}'

    def _temp_var_name(self):
        if not hasattr(self, '_temp'):
            self._temp = 0
        self._temp += 1
        return f'_temp_var_{self._temp}'

    def _compile_branch(self, branch):
        result = Result()

        for x in branch[:-1]:
            res = self.compile(x)
            result.stmts += res.stmts
            result.stmts += [res.expr_statement]

        res = self.compile(branch[-1])
        result.stmts += res.stmts
        result.expr = res.expr

        return result

    def _compile_args(self, args, kwargs):
        for i, arg in enumerate(args):
            if arg == '&':
                vararg = ast.arg(str(args[i + 1], None), None)
                posarg = args[:i]
        else:
            vararg = None
            posarg = args

        return ast.arguments(
            args=[ast.arg(str(x), None) for x in posarg],
            vararg=vararg,
            kwonlyargs=[ast.arg(str(x), None) for x in kwargs],
            kwarg=None,
            defaults=[],
            kw_defaults=list(kwargs.values()),
        )

    def compile(self, node):
        return _model_compiler[type(node)](self, node)

    @model(LtnsElement)
    def compile_element(self, element):
        if element.name in _special_form_compiler:
            return _special_form_compiler[element.name](self, *element.childs,
                                                        **element.attributes)

        func = ast.parse(element.name,
                         mode='eval').body  # TODO: handle exception of parsing

        result = Result()

        args = []
        keywords = []

        for child in element.childs:
            res = self.compile(child)
            args.append(res.expr)
            result.stmts += res.stmts

        for key, value in element.attributes.items():
            res = self.compile(value)
            keywords.append(ast.keyword(arg=str(key), value=res.expr))
            result.stmts += res.stmts

        expr = ast.Call(func=func, args=args, keywords=keywords)
        result.expr = expr

        return result

    @model(LtnsSymbol)
    def compile_symbol(self, symbol):
        expr = ast.Name(id=str(symbol), ctx=ast.Load())

        return Result(expr=expr)

    @model(LtnsString)
    def compile_string(self, string):
        return Result(expr=ast.Str(str(string)))

    @model(LtnsKeyword)
    def compile_keyword(self, keyword):
        return Result(expr=ast.Call(
            func=ast.Name(id='LtnsKeyword', ctx=ast.Load()),
            args=[ast.Str(str(keyword))],
        ))

    @model(LtnsInteger)
    def compile_integer(self, integer):
        return Result(expr=ast.Num(int(integer)))

    @model(LtnsFloat)
    def compile_float_number(self, float_number):
        return Result(expr=ast.Num(float(float_number)))

    @model(LtnsComplex)
    def compile_complex_number(self, complex_number):
        return Result(expr=ast.Num(complex(complex_number)))

    @model(LtnsList)
    def compile_list(self, ltns_list):
        result = Result()

        elts = []
        for e in ltns_list:
            res = self.compile(e)
            elts.append(res.expr)
            result.stmts += res.stmts

        expr = ast.List(elts=elts, ctx=ast.Load())
        result.expr = expr

        return result

    @special('do')
    def compile_do(self, *body):
        return self._compile_branch(body)

    name_op = {
        'add*': ast.Add(),
        'sub*': ast.Sub(),
        'mul*': ast.Mult(),
        'div*': ast.Div(),
        'mod': ast.Mod(),
        'pow': ast.Pow(),
        'lshift': ast.LShift(),
        'rshift': ast.RShift(),
        'bitor': ast.BitOr(),
        'bitxor': ast.BitXor(),
        'bitand': ast.BitAnd(),
    }

    def compile_bin_op(self, a, b, name):
        result = Result()

        left = self.compile(a)
        result.stmts += left.stmts
        left = left.expr

        right = self.compile(b)
        result.stmts += right.stmts
        right = right.expr

        expr = ast.BinOp(op=self.name_op[name], left=left, right=right)
        result.expr = expr

        return result

    for name in name_op:
        _special_form_compiler[name] = partial(compile_bin_op, name=name)

    @special('if')
    def compile_if(self, test, then, orelse=None):
        result = Result()

        pred = self.compile(test)
        result.stmts += pred.stmts

        then_body = self.compile(then)

        else_body = None
        if orelse is not None:
            else_body = self.compile(orelse)

        if then_body.stmts or else_body.stmts:
            temp_func_name = self._temp_func_name()
            temp_var_name = self._temp_var_name()

            body = then_body.stmts
            body.append(
                ast.Assign(
                    targets=[ast.Name(id=temp_var_name, ctx=ast.Store())],
                    value=then_body.expr,
                ))

            orelse = else_body.stmts
            orelse.append(
                ast.Assign(
                    targets=[ast.Name(id=temp_var_name, ctx=ast.Store())],
                    value=else_body.expr,
                ))

            result.stmts.append(
                ast.FunctionDef(
                    name=temp_func_name,
                    args=ast.arguments(
                        args=[],
                        vararg=None,
                        kwonlyargs=[],
                        kw_defaults=[],
                        kwarg=None,
                        defaults=[],
                    ),
                    body=[
                        ast.If(test=pred.expr, body=body, orelse=orelse),
                        ast.Return(
                            value=ast.Name(id=temp_var_name, ctx=ast.Load())),
                    ],
                    decorator_list=[],
                    returns=None,
                ))

            result.expr = ast.Call(
                func=ast.Name(id=temp_func_name, ctx=ast.Load()),
                args=[],
                keywords=[],
            )

            return result
        else:
            result.expr = ast.IfExp(
                test=pred.expr,
                body=then_body.expr,
                orelse=else_body.expr,
            )

            return result

    @special('fn*')
    def compile_fn(self, args, *body, **kwargs):
        result = Result()

        body = self._compile_branch(body)
        args = self._compile_args(args, kwargs)

        if body.stmts:
            fdef = ast.FunctionDef()
            fdef.name = self._temp_func_name()
            fdef.args = args
            fdef.body = body.stmts + [ast.Return(body.expr)]
            fdef.decorator_list = []
            fdef.returns = None

            result.stmts += [fdef]
            result.expr = ast.Name(id=fdef.name, ctx=ast.Load())
        else:
            result.expr = ast.Lambda(args=args, body=body.expr)

        return result

    @special('def')
    def compile_def(self, *name_value, **def_dict):
        if len(name_value) % 2 != 0:
            raise ValueError("length of argument list should be even")

        result = Result()

        for name, value in def_dict.items():
            name = LtnsSymbol(name)
            name_value = name_value + (name, value)

        for i, name in enumerate(name_value[::2]):
            name = ast.Name(id=str(name), ctx=ast.Store())
            value = self.compile(name_value[i * 2 + 1])

            result.stmts += [ast.Assign(
                targets=[name],
                value=value.expr,
            )]

        result.expr = ast.Name(id='None', ctx=ast.Load())

        return result
Пример #10
0
 def visit_Or(self, node):
     self.generic_visit(node)
     return ast.BitOr()
Пример #11
0
    def test_empty_init(self):
        # Jython 2.5.0 did not allow empty constructors for many ast node types
        # but CPython ast nodes do allow this.  For the moment, I don't see a
        # reason to allow construction of the super types (like ast.AST and
        # ast.stmt) as well as the op types that are implemented as enums in
        # Jython (like boolop), but I've left them in but commented out for
        # now.  We may need them in the future since CPython allows this, but
        # it may fall under implementation detail.

        #ast.AST()
        ast.Add()
        ast.And()
        ast.Assert()
        ast.Assign()
        ast.Attribute()
        ast.AugAssign()
        ast.AugLoad()
        ast.AugStore()
        ast.BinOp()
        ast.BitAnd()
        ast.BitOr()
        ast.BitXor()
        ast.BoolOp()
        ast.Break()
        ast.Call()
        ast.ClassDef()
        ast.Compare()
        ast.Continue()
        ast.Del()
        ast.Delete()
        ast.Dict()
        ast.Div()
        ast.Ellipsis()
        ast.Eq()
        ast.Exec()
        ast.Expr()
        ast.Expression()
        ast.ExtSlice()
        ast.FloorDiv()
        ast.For()
        ast.FunctionDef()
        ast.GeneratorExp()
        ast.Global()
        ast.Gt()
        ast.GtE()
        ast.If()
        ast.IfExp()
        ast.Import()
        ast.ImportFrom()
        ast.In()
        ast.Index()
        ast.Interactive()
        ast.Invert()
        ast.Is()
        ast.IsNot()
        ast.LShift()
        ast.Lambda()
        ast.List()
        ast.ListComp()
        ast.Load()
        ast.Lt()
        ast.LtE()
        ast.Mod()
        ast.Module()
        ast.Mult()
        ast.Name()
        ast.Not()
        ast.NotEq()
        ast.NotIn()
        ast.Num()
        ast.Or()
        ast.Param()
        ast.Pass()
        ast.Pow()
        ast.Print()
        ast.RShift()
        ast.Raise()
        ast.Repr()
        ast.Return()
        ast.Slice()
        ast.Store()
        ast.Str()
        ast.Sub()
        ast.Subscript()
        ast.Suite()
        ast.TryExcept()
        ast.TryFinally()
        ast.Tuple()
        ast.UAdd()
        ast.USub()
        ast.UnaryOp()
        ast.While()
        ast.With()
        ast.Yield()
        ast.alias()
        ast.arguments()
        #ast.boolop()
        #ast.cmpop()
        ast.comprehension()
        #ast.excepthandler()
        #ast.expr()
        #ast.expr_context()
        ast.keyword()
Пример #12
0
def translateExpr(n):
    if isinstance(n, Token):
        if n.type.name == 'INTEGER':
            if n.arg > 2**63:
                return ast.NameConstant('__BIGINT__')
            return ast.Num(n.arg)
        if n.type.name == 'FLOAT':
            return ast.Num(n.arg)
        if n.type.name == 'IDENT':
            return ast.NameConstant(mungeName(n.arg))
        if n.type.name == 'FALSE':
            return ast.NameConstant('False')
        if n.type.name == 'TRUE':
            return ast.NameConstant('True')
        if n.type.name == 'BITSTRING':
            if n.arg.find('x') >= 0:
                return ast.Call(ast.NameConstant('__BITSTRING_MATCH__'),
                                [ast.Str(n.arg)], [])
            return ast.NameConstant('0b' + n.arg)
        raise Exception('q %s' % n)

    if isinstance(n, Type):
        return ast.Num(800)

    if n.type == 'e-land':
        return ast.BoolOp(
            ast.And(),
            [translateExpr(n.children[0]),
             translateExpr(n.children[1])])
    elif n.type == 'e-lor':
        return ast.BoolOp(
            ast.Or(),
            [translateExpr(n.children[0]),
             translateExpr(n.children[1])])
    elif n.type == 'e-eq':
        return ast.Compare(translateExpr(n.children[0]), [ast.Eq()],
                           [translateExpr(n.children[1])])
    elif n.type == 'e-ne':
        return ast.Compare(translateExpr(n.children[0]), [ast.NotEq()],
                           [translateExpr(n.children[1])])
    elif n.type == 'e-call':
        return ast.Call(translateExpr(n.children[0]),
                        [translateExpr(x) for x in n.children[1]], [])
    elif n.type == 'e-range':
        return ast.Subscript(translateExpr(n.children[0]),
                             translateRange(n.children[1]), None)
    elif n.type == 'e-not':
        return ast.UnaryOp(ast.Not(), translateExpr(n.children[0]))
    elif n.type == 'e-negate':
        return ast.UnaryOp(ast.USub(), translateExpr(n.children[0]))
    elif n.type == 'e-add':
        return ast.BinOp(translateExpr(n.children[0]), ast.Add(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-sub':
        return ast.BinOp(translateExpr(n.children[0]), ast.Sub(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-mul':
        return ast.BinOp(translateExpr(n.children[0]), ast.Mult(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-div':
        return ast.BinOp(translateExpr(n.children[0]), ast.FloorDiv(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-fdiv':
        return ast.BinOp(translateExpr(n.children[0]), ast.Div(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-rem':
        return ast.BinOp(translateExpr(n.children[0]), ast.Mod(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-lt':
        return ast.Compare(translateExpr(n.children[0]), [ast.Lt()],
                           [translateExpr(n.children[1])])
    elif n.type == 'e-le':
        return ast.Compare(translateExpr(n.children[0]), [ast.LtE()],
                           [translateExpr(n.children[1])])
    elif n.type == 'e-gt':
        return ast.Compare(translateExpr(n.children[0]), [ast.Gt()],
                           [translateExpr(n.children[1])])
    elif n.type == 'e-ge':
        return ast.Compare(translateExpr(n.children[0]), [ast.GtE()],
                           [translateExpr(n.children[1])])
    elif n.type == 'e-lsh':
        return ast.BinOp(translateExpr(n.children[0]), ast.LShift(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-rsh':
        return ast.BinOp(translateExpr(n.children[0]), ast.RShift(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-eor':
        return ast.BinOp(translateExpr(n.children[0]), ast.BitXor(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-or':
        return ast.BinOp(translateExpr(n.children[0]), ast.BitOr(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-and':
        return ast.BinOp(translateExpr(n.children[0]), ast.BitAnd(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-ternary':
        return ast.IfExp(translateExpr(n.children[0]),
                         translateExpr(n.children[1]),
                         translateExpr(n.children[2]))
    elif n.type == 'e-subrange':
        return ast.Num(113)
    elif n.type == 'e-lnegate':
        return ast.UnaryOp(ast.Invert(), translateExpr(n.children[0]))
    elif n.type == 'e-subscript':
        return ast.Attribute(translateExpr(n.children[0]), n.children[1].arg,
                             None)
    elif n.type == 'e-indexempty':
        return ast.Subscript(translateExpr(n.children[0]),
                             ast.Slice(None, None, None), None)
    elif n.type == 'e-implementation-defined':
        return ast.Call(ast.NameConstant('IMPLEMENTATION_DEFINED'), [], [])
    elif n.type == 'e-exp':
        return ast.BinOp(translateExpr(n.children[0]), ast.Pow(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-mod':
        return ast.BinOp(translateExpr(n.children[0]), ast.Mod(),
                         translateExpr(n.children[1]))
    elif n.type == 'e-unknown':
        return ast.Call(ast.NameConstant('UNKNOWN'), [], [])
    elif n.type == 'e-index':
        return ast.Subscript(translateExpr(n.children[0]),
                             ast.Slice(None, None, None), None)
    elif n.type == 'e-tuple':
        return ast.Tuple([translateExpr(x) for x in n.children[0]], None)
    elif n.type == 'e-set-in':
        return ast.Num(114)
    elif n.type == 'e-concat':
        return ast.Call(
            ast.NameConstant('_CONCAT_'),
            [translateExpr(n.children[0]),
             translateExpr(n.children[1])], [])
    elif n.type == 'tuple-nomatch':
        return ast.NameConstant('_')
    elif n.type == 'range':
        return ast.Num(122)  #return translateRange(n)
    else:
        raise Exception('unknown node type: %s' % (n, ))

    return ast.Num(42)
Пример #13
0
 def expr(self, p):
     return ast.BinOp(left=p.xor_expr0, op=ast.BitOr(), right=p.xor_expr1)
Пример #14
0
 def or_test(self, p):
     return ast.BinOp(left=p.and_test0, op=ast.BitOr(), right=p.and_test1)
Пример #15
0
    'RSHIFT_ASN',
    'POW_ASN',
    'FDIV_ASN',
    'NAME',
    'NUMBER',
)

Add = ast.Add()
Sub = ast.Sub()
Mult = ast.Mult()
Div = ast.Div()
Mod = ast.Mod()
Pow = ast.Pow()
LShift = ast.LShift()
RShift = ast.RShift()
BitOr = ast.BitOr()
BitAnd = ast.BitAnd()
BitXor = ast.BitXor()
FloorDiv = ast.FloorDiv()

op_dict = {
    "+": Add,
    "-": Sub,
    "*": Mult,
    "/": Div,
    "//": FloorDiv,
    "%": Mod,
    "**": Pow,
    "<<": LShift,
    ">>": RShift,
    "|": BitOr,
Пример #16
0
    class helper(object):
        def __init__(self, node):
            self.node = node

        def __ast__(self):
            return self.node

        @property
        def body(self):
            return E(self.node.body)

        @body.setter
        def body(self, e):
            self.node.body = e

        def call(self, args=None):
            self.node = ast.Call(func=self.node,
                                 args=args if args else [],
                                 keywords=[],
                                 starargs=None,
                                 kwargs=None)
            return self

        def args(self, args):
            self.node.args = args
            return self

        def subscript(self, index=None):
            self.node = ast.Subscript(value=self.node, slice=ast.Index(index))
            return self

        def attr(self, attribute):
            assert (isinstance(attribute, str))
            self.node = ast.Attribute(value=self.node, attr=attribute)
            return self

        def assign(self, value):
            self.node = ast.Assign(targets=[self.node], value=E(value))
            return self

        def init(self, value):
            self.node.init = value
            return self

        sub_assign = _aug_assign(ast.Sub())
        add_assign = _aug_assign(ast.Add())
        xor_assign = _aug_assign(ast.BitXor())
        or_assign = _aug_assign(ast.BitOr())
        mult = _bin_op(ast.Mult())
        add = _bin_op(ast.Add())
        bit_and = _bin_op(ast.BitAnd())
        bit_or = _bin_op(ast.BitOr())
        bit_xor = _bin_op(ast.BitXor())
        xor = bit_xor

        NotEq = _compare2(ast.NotEq())
        Eq = _compare2(ast.Eq())
        Gt = _compare2(ast.Gt())
        Lt = _compare2(ast.Lt())

        def ast(self):
            return self.node