Пример #1
0
    def visitFor(self, forNode):  #! added Visitfor, how is desugarer called
        # from: for(VARDEF to END) BLOCK
        # to:   {VARDEF VARDEF1 while (VARDEF.ID < "end"){ BLOCK ASSIGNMENT}
        #       assignment: VARDEF.ID = VARDEF.ID + 1
        #       vardef1:    (int, "end", END)

        self.visit_children(forNode)

        endVar = self.makevar("end")

        initEnd = VarDef(Type.get('int'), endVar,
                         BinaryOp(forNode.end, Operator('-'), IntConst(1)))
        decrCount = Assignment(
            VarUse(forNode.start.name),
            (BinaryOp(VarUse(forNode.start.name), Operator('-'), IntConst(1))))

        #initEnd = VarDef(Type.get('int'), endVar, IntConst(1))

        endCheck = BinaryOp(VarUse(forNode.start.name), Operator('<'),
                            VarUse(endVar))
        incrCount = Assignment(
            VarUse(forNode.start.name),
            (BinaryOp(VarUse(forNode.start.name), Operator('+'), IntConst(1))))

        return Block([
            forNode.start, decrCount, initEnd,
            While(endCheck, Block([incrCount, forNode.body]))
        ])
Пример #2
0
    def visitFor(self, node):
        # from: for(int node.name = node.expr1 to node.expr2) { node.body }
        # to:
        # Block wrapper {
        # Assignment: int node.name = node.expr1;
        # While type:  while ( expression: node.name < node.expr2){
        # new block:
        # Block:  node.body;
        # : node.name = node.name + 1
        # }
        self.visit_children(node)

        if isinstance(node.ref, str):
            ref = VarUse(node.ref)
        initial_assignment = VarDef(Type.get('int'), str(ref), node.expr1).at(node)
        incrementation = Assignment(ref, BinaryOp(ref, Operator('+'), IntConst(1))).at(node)
        while_body = Block([node.body, incrementation]).at(node)
        while_condition = BinaryOp(ref, Operator("<"), node.expr2).at(node)
        while_statement = While(while_condition, while_body).at(node)
        while_statement.set_desugared_for(ref)
        return Block([initial_assignment, while_statement]).at(node)
Пример #3
0
def test():
    """
    Test Function 
    """
    stmt = Program([
        Function("f", [], [
            For("i", 1, 10, 1, [
                Assign("x", IntValue(3)),
                Assign("x", IntValue(4)),
                IfThenElse(BoolValue(True), []),
                While(BoolValue(True), [Return(IntValue(3))]),
                Assign("x", IntValue(5))
            ])
        ]),
        Function("g", [], [Assign("x", IntValue(3))]),
        Assign("x", IntValue(1))
    ])
    nodes, edges = gen_cfg_main(stmt)
    gen_dot(nodes, edges)
Пример #4
0
 def command(self):
     """ c ::=
     skip
     | x := e
     | if b then c1 else c2
     | while b do c
     """
     if self.current_token.type == '{':
         self.eat('{')
         c = self.comma_command()
         self.eat('}')
         return c
     if self.current_token.type == 'skip':
         self.eat('skip')
         return Skip()
     if self.current_token.type == 'if':
         self.eat('if')
         b = self.b_or()
         self.eat('then')
         c1 = self.comma_command()
         self.eat('else')
         c2 = self.comma_command()
         return If(b, c1, c2)
     if self.current_token.type == 'while':
         # print("current token:", self.current_token.type, self.current_token.value)
         self.eat('while')
         # print("current token:", self.current_token.type, self.current_token.value)
         b = self.b_or()
         # print(b, b.token, b.value)
         # print("current token:", self.current_token.type, self.current_token.value)
         self.eat('do')
         # print("current token:", self.current_token.type, self.current_token.value)
         c = self.command()
         # print(c)
         # print("current token:", self.current_token.type, self.current_token.value)
         return While(b, c)
     if self.current_token.type == VAR:
         x = Var(self.current_token.value)
         self.eat(VAR)
         self.eat(':=')
         e = self.aexp()
         return Assign(x, e)
Пример #5
0
def empty_script_tree(project_id: str, add_main_loop: bool = True) -> Module:
    """Creates barebones of the script (empty 'main' function).

    Returns
    -------
    """

    main_body: List[stmt] = [
        Assign(
            targets=[Name(id="aps", ctx=Store())],
            value=Call(func=Name(id="ActionPoints", ctx=Load()),
                       args=[Name(id="res", ctx=Load())],
                       keywords=[]),
            type_comment=None,
        )
    ]

    if add_main_loop:
        main_body.append(
            While(test=NameConstant(value=True, kind=None),
                  body=[Pass()],
                  orelse=[]))
    else:
        """put there "pass" in order to make code valid even if there is no
        other statement (e.g. no object from resources)"""
        main_body.append(Pass())

    # TODO helper function for try ... except

    tree = Module(
        body=[
            FunctionDef(
                name="main",
                args=arguments(
                    args=[
                        arg(arg="res",
                            annotation=Name(id=RES_CLS, ctx=Load()),
                            type_comment=None)
                    ],
                    vararg=None,
                    kwonlyargs=[],
                    kw_defaults=[],
                    kwarg=None,
                    defaults=[],
                ),
                body=main_body,
                decorator_list=[],
                returns=NameConstant(value=None, kind=None),
                type_comment=None,
            ),
            If(
                test=Compare(left=Name(id="__name__", ctx=Load()),
                             ops=[Eq()],
                             comparators=[Str(s="__main__", kind="")]),
                body=[
                    Try(
                        body=[
                            With(
                                items=[
                                    withitem(
                                        context_expr=Call(
                                            func=Name(id=RES_CLS, ctx=Load()),
                                            args=[Str(s=project_id, kind="")],
                                            keywords=[],
                                        ),
                                        optional_vars=Name(id="res",
                                                           ctx=Store()),
                                    )
                                ],
                                body=[
                                    Expr(value=Call(
                                        func=Name(id="main", ctx=Load()),
                                        args=[Name(id="res", ctx=Load())],
                                        keywords=[],
                                    ))
                                ],
                                type_comment=None,
                            )
                        ],
                        handlers=[
                            ExceptHandler(
                                type=Name(id=Exception.__name__, ctx=Load()),
                                name="e",
                                body=[
                                    Expr(value=Call(
                                        func=Name(id=arcor2.exceptions.runtime.
                                                  print_exception.__name__,
                                                  ctx=Load()),
                                        args=[Name(id="e", ctx=Load())],
                                        keywords=[],
                                    ))
                                ],
                            )
                        ],
                        orelse=[],
                        finalbody=[],
                    )
                ],
                orelse=[],
            ),
        ],
        type_ignores=[],
    )

    add_import(tree, arcor2.exceptions.runtime.__name__,
               arcor2.exceptions.runtime.print_exception.__name__)
    add_import(tree, RES_MODULE, RES_CLS, try_to_import=False)
    add_import(tree, "action_points", "ActionPoints", try_to_import=False)

    return tree
Пример #6
0
 def handleWhile(p):
     return While(p[2], p[5])
Пример #7
0
 def p_while_statement(self, p):
     '''while_statement : WHILE LPAREN logical_expression RPAREN block_statement'''
     p[0] = While(p[3], p[5])
Пример #8
0
    def handle_f(self, f):
        # Do we need to use .attname here?
        # What about transforms/lookups?
        f.contains_aggregate = False
        if "__" in f.name:
            # We need to chain a bunch of attr lookups, returning None
            # if any of them give us a None, we should be returning a None.
            #

            # .  while x is not None and parts:
            # .      x = getattr(x, parts.pop(0), None)
            #   return x
            return [
                Assign(targets=[Name(id="source", **self.file_store)],
                       value=Name(id="self", **self.file),
                       **self.file),
                Assign(
                    targets=[Name(id="parts", **self.file_store)],
                    value=Call(
                        func=Attribute(value=Constant(value=f.name,
                                                      **self.file),
                                       attr="split",
                                       **self.file),
                        args=[Constant(value="__", **self.file)],
                        keywords=[],
                        kwonlyargs=[],
                        **self.file,
                    ),
                    **self.file,
                ),
                While(
                    test=BoolOp(
                        op=And(),
                        values=[
                            Compare(
                                left=Name(id="source", **self.file),
                                ops=[IsNot()],
                                comparators=[
                                    Constant(value=None, **self.file)
                                ],
                                **self.file,
                            ),
                            Name(id="parts", **self.file),
                        ],
                        **self.file,
                    ),
                    body=[
                        Assign(
                            targets=[Name(id="source", **self.file_store)],
                            value=Call(
                                func=Name(id="getattr", **self.file),
                                args=[
                                    Name(id="source", **self.file),
                                    Call(
                                        func=Attribute(value=Name(id="parts",
                                                                  **self.file),
                                                       attr="pop",
                                                       **self.file),
                                        args=[Constant(value=0, **self.file)],
                                        keywords=[],
                                        kwonlyargs=[],
                                        **self.file,
                                    ),
                                    Constant(value=None, **self.file),
                                ],
                                keywords=[],
                                kwonlyargs=[],
                                **self.file,
                            ),
                            **self.file,
                        ),
                    ],
                    orelse=[],
                    **self.file,
                ),
                Return(value=Name(id="source", **self.file), **self.file),
            ]
        return Attribute(value=Name(id="self", **self.file),
                         attr=f.name,
                         **self.file)