예제 #1
0
def translateStmt(n):
    if n.type == 's-if':
        return translateStmtIf(n)
    elif n.type == 's-return':
        return translateStmtReturn(n)
    elif n.type == 's-assert':
        return translateStmtAssert(n)
    elif n.type == 's-assign':
        return translateStmtAssign(n)
    elif n.type == 's-case':
        return translateStmtCase(n)
    elif n.type == 's-decls':
        return translateStmtDecls(n)
    elif n.type == 's-for-up':
        return ast.Pass()
    elif n.type == 's-for-down':
        return ast.Pass()
    elif n.type == 's-expr':
        return translateStmtExpr(n)
    elif n.type == 's-constant':
        return translateStmtConstant(n)
    elif n.type == 's-repeat':
        return ast.Pass()
    elif n.type == 's-while':
        return ast.Pass()
    elif n.type == 's-undefined':
        return ast.Expr(ast.Call(ast.NameConstant('UNDEFINED'), [], []))
    elif n.type == 's-implementation-defined':
        return ast.Expr(
            ast.Call(ast.NameConstant('IMPLEMENTATION_DEFINED'), [], []))
    else:
        raise Exception('unknown node type: %s' % (n, ))
예제 #2
0
        def generic_visit(self, node):
            import ast
            import sys
            ast.NodeTransformer.generic_visit(self, node)

            if isinstance(node,
                          ast.stmt) and not isinstance(node, ast.FunctionDef):
                if sys.version_info[0] == 3:
                    new_node = ast.Try(body=[node],
                                       handlers=[
                                           ast.ExceptHandler(type=None,
                                                             name=None,
                                                             body=[ast.Pass()])
                                       ],
                                       orelse=[],
                                       finalbody=[ast.Pass()])
                else:
                    new_node = ast.TryExcept(body=[node],
                                             handlers=[
                                                 ast.ExceptHandler(
                                                     type=None,
                                                     name=None,
                                                     body=[ast.Pass()])
                                             ],
                                             orelse=[])
                return ast.copy_location(new_node, node)
            return node
예제 #3
0
 def test_empty_If(self):
     if_ = ast.If(ast.Num(2), [], [])
     self._test_empty_body(if_)
     # An empty 'else' clause should be eliminated.
     if_else = ast.If(ast.Num(42), [ast.Pass()], [ast.Pass()])
     expect = ast.If(ast.Num(42), [ast.Pass()], [])
     self.check_transform(if_else, expect)
예제 #4
0
파일: interp.py 프로젝트: caioariede/be
def emit_if(cond, ifb, elseb, scope):
    cond = resolve_value(cond, scope)

    if ifb.v:
        ifb = list(eat(iter(ifb.v), [], scope))
        lastv = ifb.pop()
        if isinstance(lastv, ast.Expr):
            lastv = lastv.value
        if isinstance(lastv, ast.Assign):
            lastv.targets.append(ast.Name(id=',', ctx=ast.Store()))
            ifb.append(lastv)
        elif isinstance(lastv, ast.If):
            ifb.append(lastv)
        else:
            ifb.extend(emit_set(EId(None, ','), lastv, scope))
    else:
        ifb = [ast.Pass()]

    if elseb.v:
        elseb = list(eat(iter(elseb.v), [], scope))
        lastv = elseb.pop()
        if isinstance(lastv, ast.Expr):
            lastv = lastv.value
        if isinstance(lastv, ast.Assign):
            lastv.targets.append(ast.Name(id=',', ctx=ast.Store()))
            elseb.append(lastv)
        elif isinstance(lastv, ast.If):
            elseb.append(lastv)
        else:
            elseb.extend(emit_set(EId(None, ','), lastv, scope))
    else:
        elseb = [ast.Pass()]

    yield ast.fix_missing_locations(ast.If(cond, ifb, elseb))
예제 #5
0
 def test_Try(self):
     # try/except where 'except' is only dead code.
     exc_clause = ast.ExceptHandler(None, None,
                                     [ast.Expr(ast.Str('dead code'))])
     try_exc = ast.Try([ast.Pass()], [exc_clause], [], [])
     expect = ast.Try([ast.Pass()],
                      [ast.ExceptHandler(None, None, [ast.Pass()])], [], [])
     self.check_transform(try_exc, expect)
예제 #6
0
 def test_empty_While(self):
     while_ = ast.While(ast.Num(42), [], [])
     self._test_empty_body(while_)
     # An empty 'else' clause should be eliminated.
     while_else = ast.While(ast.Num(42), [ast.Pass()],
                            [ast.Pass()])
     expect = ast.While(ast.Num(42), [ast.Pass()], [])
     self.check_transform(while_else, expect)
예제 #7
0
 def test_deeply_nested(self):
     with_C = ast.With([self.C_clause], [ast.Pass()])
     with_B = ast.With([self.B_clause], [with_C])
     with_A = ast.With([self.A_clause], [with_B])
     new_ast = self.transform.visit(with_A)
     expect = ast.With([self.A_clause, self.B_clause, self.C_clause],
                       [ast.Pass()])
     self.assertEqual(ast.dump(new_ast), ast.dump(expect))
예제 #8
0
 def test_empty_For(self):
     for_ = ast.For(ast.Name('X', ast.Store()), ast.Str('a'), [], [])
     self._test_empty_body(for_)
     # An empty 'else' clause should just go away
     for_else = ast.For(ast.Name('X', ast.Store()), ast.Str('a'),
                        [ast.Pass()], [ast.Pass()])
     expect = ast.For(ast.Name('X', ast.Store()), ast.Str('a'),
                        [ast.Pass()], [])
     self.check_transform(for_else, expect)
예제 #9
0
def translateBlock(n):
    items = []
    if n is None:
        return [ast.Pass()]

    for x in n.children:
        s = translateStmt(x)
        if not isinstance(s, list):
            s = [s]
        items += s

    if len(items) == 0:
        return [ast.Pass()]

    return items
예제 #10
0
 def get_import_code(self, node, fname='<string>'):
     """Get compiled code of all top-level import statements found in the
     AST of node."""
     self._import_nodes = []
     self.visit(node)
     body = []
     for imp_node in self._import_nodes:
         if isinstance(imp_node, ast.ImportFrom) and \
            imp_node.module == '__future__':
             # 'SyntaxError: from __future__ imports must occur at the
             # beginning of the file' is raised if a 'from __future__ import'
             # is wrapped in try-except, so use only the import statement.
             body.append(imp_node)
         else:
             body.append(
                 ast.TryExcept(body=[imp_node],
                               handlers=[
                                   ast.ExceptHandler(type=None,
                                                     name=None,
                                                     body=[ast.Pass()])
                               ],
                               orelse=[]))
     node = ast.Module(body=body)
     ast.fix_missing_locations(node)
     code = compile(node, fname, 'exec')
     return code
예제 #11
0
    def visit(self, node):

        # perform analysis on whole AST as a first phase
        # (only called once)
        if self.analysis is None:
            self.analysis = AnalyzeGeneratorFunction()
            self.analysis.visit(node)

            if self.analysis.target is None:
                raise Exception(
                    "Analysis did not find an iterable input to "
                    "the Generator. Conversion to a Coroutine cannot be done.")

            self.loopsToBeWrapped = copy.copy(self.analysis.loopsToBeConverted)
            self.moreValuesAvailableId = "moreValuesAvailable"
            while self.moreValuesAvailableId in self.analysis.loadedNames:
                self.moreValuesAvailableId += str(random.randint(0, 1000000))

        if node in self.analysis.nodesToBeDeleted:
            return ast.Pass()

        if node in self.analysis.nextCallsToBeConverted:
            return ast.Yield(value=None)

        if node in self.analysis.stopIterationsToBeConverted:
            return ast.Name(id='GeneratorExit', ctx=ast.Load())

        return super(InvertGenerator, self).visit(node)
예제 #12
0
def astForCFor(funcEnv, stmnt):
    assert isinstance(stmnt, CForStatement)
    assert len(stmnt.args) == 3
    assert isinstance(
        stmnt.args[1], CStatement
    )  # second arg is the check; we must be able to evaluate that

    # introduce dummy 'if' AST so that we have a scope for the for-loop (esp. the first statement)
    ifAst = ast.If(body=[],
                   orelse=[],
                   test=ast.Name(id="True", ctx=ast.Load()))
    funcEnv.pushScope(ifAst.body)
    cStatementToPyAst(funcEnv, stmnt.args[0])

    whileAst = ast.While(body=[],
                         orelse=[],
                         test=ast.Name(id="True", ctx=ast.Load()))
    ifAst.body.append(whileAst)

    ifTestAst = ast.If(body=[ast.Pass()], orelse=[ast.Break()])
    ifTestAst.test = getAstNode_valueFromObj(
        funcEnv.globalScope.stateStruct,
        *astAndTypeForCStatement(funcEnv, stmnt.args[1]))
    whileAst.body.append(ifTestAst)

    funcEnv.pushScope(whileAst.body)
    if stmnt.body is not None:
        cCodeToPyAstList(funcEnv, stmnt.body)
    cStatementToPyAst(funcEnv, stmnt.args[2])
    funcEnv.popScope()  # whileAst / main for-body

    funcEnv.popScope()  # ifAst
    return ifAst
예제 #13
0
    def make(cls, node: ast.AST) -> ast.AST:
        if isinstance(node, ast.ClassDef):
            ann_assigns = [
                each for each in node.body if isinstance(each, ast.AnnAssign)
                and isinstance(each.target, ast.Name)
            ]

            cons = ast.FunctionDef(
                name='__init__',
                args=ast.arguments(
                    args=[
                        ast.arg('self', None), *[
                            ast.arg(each.target.id, each.annotation)
                            for each in ann_assigns
                        ]
                    ],
                    vararg=None,
                    kwonlyargs=[],
                    kwarg=None,
                    defaults=[]),
                body=[ast.Pass()],
                decorator_list=[],
                returns=None,
            )

            node = copy.copy(node)
            lst = node.decorator_list
            lst = [
                each for each in lst
                if not check_decorator(each, cls.__name__)
            ]
            node.body.insert(0, cons)
            node.decorator_list = lst
            return node
        return node