Exemple #1
0
def cStatementToPyAst(funcEnv, c):
    body = funcEnv.getBody()
    if isinstance(c, (CVarDecl, CFunc)):
        funcEnv.registerNewVar(c.name, c)
    elif isinstance(c, CStatement):
        a, t = astAndTypeForCStatement(funcEnv, c)
        if isinstance(a, ast.expr):
            a = ast.Expr(value=a)
        body.append(a)
    elif isinstance(c, CWhileStatement):
        body.append(astForCWhile(funcEnv, c))
    elif isinstance(c, CForStatement):
        body.append(astForCFor(funcEnv, c))
    elif isinstance(c, CDoStatement):
        body.append(astForCDoWhile(funcEnv, c))
    elif isinstance(c, CIfStatement):
        body.append(astForCIf(funcEnv, c))
    elif isinstance(c, CSwitchStatement):
        body.append(astForCSwitch(funcEnv, c))
    elif isinstance(c, CReturnStatement):
        body.append(astForCReturn(funcEnv, c))
    elif isinstance(c, CBreakStatement):
        body.append(ast.Break())
    elif isinstance(c, CContinueStatement):
        body.append(ast.Continue())
    elif isinstance(c, CCodeBlock):
        funcEnv.pushScope(body)
        cCodeToPyAstList(funcEnv, c.body)
        funcEnv.popScope()
    else:
        assert False, "cannot handle " + str(c)
Exemple #2
0
    def raise_exception(self,
                        node,
                        exc=None,
                        msg='',
                        expr=None,
                        fname=None,
                        lineno=None,
                        func=None):
        "add an exception"
        if self.error is None:
            self.error = []
        if expr is None:
            expr = self.expr
        if fname is None:
            fname = self.fname
        if lineno is None:
            lineno = self.lineno

        if func is None:
            func = self.func

        if len(self.error) > 0 and not isinstance(node, ast.Module):
            msg = '%s' % msg
        err = LarchExceptionHolder(node,
                                   exc=exc,
                                   msg=msg,
                                   expr=expr,
                                   fname=fname,
                                   lineno=lineno,
                                   func=func,
                                   symtable=self.symtable)
        self._interrupt = ast.Break()
        self.error.append(err)
        self.symtable._sys.last_error = err
Exemple #3
0
    def mutate(cls, node):
        """
        Mutate break and continue statements
            1. break to continue
            2. continue to break
        """
        if node not in config.visited_nodes:
            if node.__class__ is ast.Break:
                config.mutated = True
                original_node = deepcopy(node)
                parent = config.parent_dict[node]
                del config.parent_dict[node]
                node = ast.Continue()
                config.parent_dict[node] = parent
                config.node_pairs[node] = original_node
                config.current_mutated_node = node

            elif node.__class__ is ast.Continue:
                config.mutated = True
                original_node = deepcopy(node)
                parent = config.parent_dict[node]
                del config.parent_dict[node]
                node = ast.Break()
                config.parent_dict[node] = parent
                config.node_pairs[node] = original_node
                config.current_mutated_node = node

        return node
Exemple #4
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
Exemple #5
0
def controlnode_to_ast(node):
    if node.code == "break:":
        return [ast.Break()]
    mod = ast.parse("%s\n  pass" % node.code)
    ctrl = mod.body[0]
    ctrl.body = sum([node_to_ast(x) for x in node.children], [])
    ctrl.orelse = sum([node_to_ast(x) for x in node.orelse], [])
    return [ctrl]
Exemple #6
0
 def wrap_func_body(self, flat_body):
     var_ast = ast.Assign()
     var_ast.targets = [ast.Name(id=self.gotoVarName, ctx=ast.Store())]
     var_ast.value = ast.Name(id="None", ctx=ast.Load())
     main_loop_ast = ast.While(orelse=[])
     main_loop_ast.test = ast.Name(id="True", ctx=ast.Load())
     main_loop_ast.body = self.handle_body(flat_body)
     main_loop_ast.body += [ast.Break()]
     return [var_ast, main_loop_ast]
Exemple #7
0
 def to_node(self, stmt):
     if isinstance(stmt, Statement):
         return stmt.to_node()
     if stmt == 'pass':
         return ast.Pass()
     if stmt == 'break':
         return ast.Break()
     if stmt == 'continue':
         return ast.Continue()
Exemple #8
0
def p_jump_statement_1(p):
    '''
    jump_statement : BREAK SEMI
    '''
    if DEBUG:
        print("\njmp stmt: ", end="")
        for i in range(len(p)):
            print(i, " ", p[i], " ", end="")
    p[0] = ast.Break()
Exemple #9
0
 def test_break(self):
     assert self.run([
         ast.Assign(
             [ast_store('i')],
             ast.Num(0),
         ),
         ast.While(ast.Compare(ast_load('i'), [ast.Lt()], [ast.Num(10)]), [
             ast.Break(),
         ], [])
     ], 'i', int) == 0
Exemple #10
0
 def stop_iteration(node):
     cmp_break = ast.Compare(left=mk_name(self.flag_id),
                             ops=[ast.Eq()],
                             comparators=[mk_str(self.BREAK)])
     cmp_return = ast.Compare(left=mk_name(self.flag_id),
                              ops=[ast.Eq()],
                              comparators=[mk_str(self.RETURN)])
     test = ast.BoolOp(op=ast.Or(), values=[cmp_break, cmp_return])
     break_stmt = ast.Break()
     ifstmt = ast.If(test=test, body=[break_stmt], orelse=[])
     node.body.append(ifstmt)
        def visit_While(self, node):
            if self.done:
                return node
            if self.count != self.selection:
                self.count += 1
                return node

            self.done = True
            return ast.While(test=node.test,
                             body=node.body + [node, ast.Break()],
                             orelse=[])
Exemple #12
0
 def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None):
     "add an exception"
     if self.error is None:
         self.error = []
     if expr is None:
         expr = self.expr
     if len(self.error) > 0 and not isinstance(node, ast.Module):
         msg = '%s' % msg
     err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
     self._interrupt = ast.Break()
     self.error.append(err)
     raise RuntimeError
Exemple #13
0
    def raise_exception(self, node, msg='', expr=None):
        "add an exception"
        if self.error is None:
            self.error = []
        if expr is None:
            expr = self.expr
        if len(self.error) > 0 and not isinstance(node, ast.Module):
            msg = '%s' % msg

        etype, evalue, tback = sys.exc_info()
        err = ExceptionHolder(node, msg=msg, expr=expr, py_exc=(etype, evalue))
        self._interrupt = ast.Break()
        self.error.append(err)
Exemple #14
0
    def mutate(cls, node):
        if node not in config.visited_nodes:
            if node.__class__ in [ast.For, ast.While]:
                config.mutated = True
                original_node = deepcopy(node)
                parent = config.parent_dict[node]
                del config.parent_dict[node]
                node.body = [ast.Break()] + node.body
                config.parent_dict[node] = parent
                config.node_pairs[node] = original_node
                config.current_mutated_node = node

        return node
Exemple #15
0
def astconv_dowhile_stmt(dowhile_stmt_astc, ctx, prefix_stmts):
    [body_astc, exit_cond_astc] = dowhile_stmt_astc.get_children()
    exit_check_prefix_stmts = []
    exit_check_astpy = ast.If(test=ast.UnaryOp(op=ast.Not(),
                                               operand=astconv_expr(
                                                   exit_cond_astc, ctx,
                                                   exit_check_prefix_stmts)),
                              body=[ast.Break()],
                              orelse=[])
    return ast.While(test=ast.Name(id='True', ctx=ast.Load()),
                     body=to_stmt_list(body_astc, ctx) +
                     exit_check_prefix_stmts + [exit_check_astpy],
                     orelse=[])
    def __init__(self, base_node):
        BaseMutator.__init__(self, base_node)
        self.original_node = base_node

        # TODO - This doesn't work - AST node needs replaced
        if base_node.__class__ is ast.Break:
            self.mutations.append(
                ast.Continue(lineno=base_node.lineno,
                             col_offset=base_node.col_offset))
        # TODO - This doesn't work - AST node needs replaced
        if base_node.__class__ is ast.Continue:
            self.mutations.append(
                ast.Break(lineno=base_node.lineno,
                          col_offset=base_node.col_offset))
Exemple #17
0
    def test_simple_statements(self):
        # Simple statements can be put on a single line as long as the scope
        # has not changed.
        for body, expect in [
            (ast.Expr(ast.Num(42)), '42'),
            (ast.Import([ast.alias('a', None)]), 'import a'),
            (ast.ImportFrom('b', [ast.alias('a', None)],
                            1), 'from .b import a'),
            (ast.Break(), 'break'),
            (ast.Continue(), 'continue'),
            (ast.Pass(), 'pass'),
            (ast.Assign([ast.Name('X', ast.Store())], ast.Num(42)), 'X=42'),
            (ast.Delete([ast.Name('X', ast.Del())]), 'del X'),
            (ast.Raise(None, None), 'raise'),
            (ast.Return(None), 'return'),
            (ast.AugAssign(ast.Name('X', ast.Store()), ast.Add(),
                           ast.Num(42)), 'X+=42'),
            (ast.Assert(ast.Num(42), None), 'assert 42'),
            (ast.Global(['x']), 'global x'),
            (ast.Nonlocal(['x']), 'nonlocal x'),
        ]:
            if_simple = ast.If(ast.Num(42), [body], None)
            self.verify(if_simple, 'if 42:{}'.format(expect))

        if_multiple_simples = ast.If(ast.Num(42),
                                     [ast.Pass(), ast.Pass()], None)
        self.verify(if_multiple_simples, 'if 42:pass;pass')
        inner_if = ast.If(ast.Num(6), [ast.Pass()], None)
        funky_if = ast.If(ast.Num(42), [
            ast.Break(),
            ast.Continue(), inner_if,
            ast.Break(),
            ast.Continue()
        ], None)
        self.verify(funky_if,
                    'if 42:\n break;continue\n if 6:pass\n break;continue')
Exemple #18
0
    def statement_to_node(self, statement):
        if type(statement) is PrintStatement:
            node = self.print_to_node(statement)
        elif type(statement) is AssignmentStatement:
            node = self.assignment_to_node(statement)
        elif type(statement) is IfStatement:
            node = self.if_to_node(statement)
        elif type(statement) is WhileStatement:
            node = self.while_to_node(statement)
        elif type(statement) is BreakStatement:
            node = ast.Break()
        elif type(statement) is ContinueStatement:
            node = ast.Continue()

        else:
            raise
        return node
Exemple #19
0
 def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None):
     """Add an exception."""
     if self.error is None:
         self.error = []
     if expr is None:
         expr = self.expr
     if len(self.error) > 0 and not isinstance(node, ast.Module):
         msg = '%s' % msg
     err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
     self._interrupt = ast.Break()
     self.error.append(err)
     if self.error_msg is None:
         self.error_msg = "at expr='%s'" % (self.expr)
     elif len(msg) > 0:
         self.error_msg = msg
     if exc is None:
         try:
             exc = self.error[0].exc
         except:
             exc = RuntimeError
     raise exc(self.error_msg)
Exemple #20
0
    def _parse_jump_statement(self, env):
        """ <jump_statement>

        Parses the <jump_statement> language structure.

            jump_statement -> 'continue' ';'
                            |   'break' ';'
                            |   'return' ';'
                            |   'return' logical_expression ';'
        """

        if self._accept(lexer.Tag.CONTINUE):
            return ast.Continue()
        elif self._accept(lexer.Tag.BREAK):
            return ast.Break()
        elif self._accept(lexer.Tag.RETURN):
            exp = None
            if not self._check(';'):
                exp = self._parse_logical_expression(env)
            self._match(';')
            return ast.Return(exp)
Exemple #21
0
 def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None):
     """add an exception"""
     if self.error is None:
         self.error = []
     if expr is None:
         expr = self.expr
     if self.error and not isinstance(node, ast.Module):
         msg = '%s' % msg
     err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
     self._interrupt = ast.Break()
     self.error.append(err)
     if self.error_msg is None:
         self.error_msg = "%s in expr='%s'" % (msg, self.expr)
     elif msg:
         self.error_msg = "%s\n %s" % (self.error_msg, msg)
     if exc is None:
         # noinspection PyBroadException
         try:
             exc = self.error[0].exc
         except:
             exc = RuntimeError
     raise exc(self.error_msg)
Exemple #22
0
 def visit_For(self, node):
     iter_sym = Symbol()
     return self.visit(ast.copy_location(ast.Expr(
         value=LetBinding(
             symbol=iter_sym,
             inner=iter_sym,
             bound_expr=ast.Call(
                 func=ast.Name(id="iter", ctx=ast.Load()),
                 args=[node.iter],
                 keywords=[]
             ),
             ex_stmts=[
                 ast.While(
                     test=ast.Constant(value=True),
                     body=[ast.Try(
                         body=[ast.Assign(
                             targets=[node.target],
                             value=ast.Call(
                                 func=ast.Name(id="next", ctx=ast.Load()),
                                 args=[iter_sym],
                                 keywords=[]
                             )
                         )],
                         handlers=[ast.ExceptHandler(
                             type=ast.Name(id="StopIteration", ctx=ast.Load()),
                             name=None,
                             body=[
                                 ast.Break()
                             ]
                         )],
                         orelse=[],
                         finalbody=[]
                     )] + node.body,
                     orelse=node.orelse
                 )
             ]
         )
     ), node))
Exemple #23
0
def astForCDoWhile(funcEnv, stmnt):
    assert isinstance(stmnt, CDoStatement)
    assert isinstance(stmnt.whilePart, CWhileStatement)
    assert stmnt.whilePart.body is None
    assert len(stmnt.args) == 0
    assert len(stmnt.whilePart.args) == 1
    assert isinstance(stmnt.whilePart.args[0], CStatement)
    whileAst = ast.While(body=[],
                         orelse=[],
                         test=ast.Name(id="True", ctx=ast.Load()))

    funcEnv.pushScope(whileAst.body)
    if stmnt.body is not None:
        cCodeToPyAstList(funcEnv, stmnt.body)
    funcEnv.popScope()

    ifAst = ast.If(body=[ast.Continue()], orelse=[ast.Break()])
    ifAst.test = getAstNode_valueFromObj(
        funcEnv.globalScope.stateStruct,
        *astAndTypeForCStatement(funcEnv, stmnt.whilePart.args[0]))
    whileAst.body.append(ifAst)

    return whileAst
    def visit_While(self, node):
        if not coloring.is_green(node):
            return node

        # testVar = not bool(...test)
        testVar = gensym.gensym("test")
        testStatement = ast.Assign(
            targets=[ast.Name(id=testVar, ctx=ast.Store())],
            value=ast.UnaryOp(op=ast.Not(),
                              operand=ast.Call(func=ast.Name(id='bool',
                                                             ctx=ast.Load()),
                                               args=[node.test],
                                               keywords=[])))
        ast.copy_location(testStatement, node)
        # TODO testStatement needs to be colored appropriately
        # based on whether test contains green calls

        # "if <testVar>: break"
        breakNode = ast.Break()
        ast.copy_location(breakNode, node)
        breakNode.color = True
        loopIf = ast.If(test=ast.Name(id=testVar, ctx=ast.Load()),
                        body=[breakNode],
                        orelse=[])
        ast.copy_location(loopIf, node)
        loopIf.color = True

        # build the new body
        newbody = []
        newbody.append(testStatement)
        newbody.append(loopIf)
        newbody.extend(node.body)
        node.body = self._transform_sequence(newbody)

        node.test = ast.copy_location(ast.NameConstant(value=True), node)

        return node
    def visit_For(self, node: For, *args, **kwargs) -> C.For:
        target = self.visit(node.target, *args, **kwargs)
        iter = self.visit(node.iter, *args, **kwargs)
        body = self.visit(node.body, *args, **kwargs)
        cond = self.visit(node.cond, *args, **kwargs)
        orelse = self.visit(node.orelse, *args, **kwargs)
        type_comment = self.visit(node.type_comment, *args, **kwargs)

        if cond is not None:
            check = C.If(
                test=C.UnaryOp(op=C.Not(), operand=cond),
                body=[C.Break()],
                orelse=[],
            )

            body = [check] + body

        return C.For(
            target=target,
            iter=iter,
            body=body,
            orelse=orelse,
            type_comment=type_comment,
        )
Exemple #26
0
 def statement(self, is_global=False):
     if self.accept(';'):
         self.advance()
         return ast.EmptyStmt()
     elif self.accept('return'):
         return self.return_()
     elif self.accept('break'):
         self.advance()
         brk = ast.Break()
         self.expect(';')
         return brk
     elif self.accept('continue'):
         self.advance()
         cont = ast.Continue()
         self.expect(';')
         return cont
     elif self.accept('{'):
         return self.block()
     elif self.accept('for'):
         return self.for_()
     elif self.accept('while'):
         return self.while_()
     elif self.accept('if'):
         return self.if_()
     elif self.is_declaration(): 
         declr = self.declaration()
         if (type(declr) == ast.Declaration and
             type(declr.typ) == ast.Function and self.accept('{')):
             return self.parse_function(declr)
         else:
             self.expect(';')
             return declr
     else:
         expr = self.expression()
         self.expect(';')
         return expr
Exemple #27
0
    def visit_While(self, node):

        breakout = ast.If(
            test=node.test,
            body=[ast.Expr(value=ast.Continue())],
            orelse=[ast.Expr(value=ast.Break())]
        )

        body_block = [i for i in node.body]
        body_block.append(breakout)

        new_node = ast.For(
            target=ast.Name("WhileLoop"),
            iter=ast.Call(func=ast.Name(id="range"),
                          ctx=ast.Load(), args=[ast.Num(n=65534)]),
            body=body_block
        )
        try:
            self.indent -= 1
            subp = self.sub_parser(new_node)
            subp.indent -= 1
            self.stack.append(subp.format())
        finally:
            self.indent += 1
Exemple #28
0
def tct(infunc):
    """ Transform a recursive call to an iteration... in some cases """
    tree = ast.parse(inspect.getsource(infunc))
    transformer = ReturnCallTransformer(infunc.func_name,
                                        ast.Continue(),
                                        tree.body[0].args)
    trans_tree = transformer.visit(tree)

    trans_tree.body[0].body = [
        ast.While(test=ast.Name(id='True', ctx=ast.Load()),
                  body=trans_tree.body[0].body + [ast.Break()],
                  orelse=[])
    ]

    # remove TCT decorator, so that we only do TCT once
    trans_tree.body[0].decorator_list = [decorator for decorator
        in trans_tree.body[0].decorator_list if decorator.id != 'tct']

    outfunc_code = compile(ast.fix_missing_locations(trans_tree),
                           inspect.getfile(infunc), 'exec')

    eval_env = globals().copy()
    eval(outfunc_code, eval_env)
    return eval_env[infunc.func_name]
Exemple #29
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
Exemple #30
0
 def p_break_statement_2(self, p):
     """break_statement : BREAK identifier SEMI
                        | BREAK identifier auto_semi
     """
     p[0] = ast.Break(p[2])