def visit_Print(self, n):
        keywords = []
        if n.dest is not None:
            keywords.append(ast3.keyword("file", self.visit(n.dest)))

        if not n.nl:
            keywords.append(ast3.keyword("end", ast3.Str(" ", lineno=n.lineno, col_offset=-1)))

        return ast3.Expr(ast3.Call(ast3.Name("print", ast3.Load(), lineno=n.lineno, col_offset=-1),
                                   self.visit(n.values),
                                   keywords,
                                   lineno=n.lineno, col_offset=-1))
Exemplo n.º 2
0
    def visit_Print(self, n):
        keywords = []
        if n.dest is not None:
            keywords.append(ast3.keyword("file", self.visit(n.dest)))

        if not n.nl:
            keywords.append(ast3.keyword("end", ast3.Str(" ", lineno=n.lineno, col_offset=-1)))

        return ast3.Expr(ast3.Call(ast3.Name("print", ast3.Load(), lineno=n.lineno, col_offset=-1),
                                   self.visit(n.values),
                                   keywords,
                                   lineno=n.lineno, col_offset=-1))
Exemplo n.º 3
0
    def visit_Compare(self, node: ast3.Compare) -> VisitorOutput:
        "Transforms a comparision into a function call. E.g. `ABC == MNO` into `ABC.eq(MNO)`"

        assert len(
            node.ops
        ) == 1, "Pytropos only supports comparisions of two values at the time"
        self.generic_visit(node)

        op_type = type(node.ops[0])
        if op_type not in compopt:
            raise AstTransformerError(
                f"Pytropos doesn't support the comparison {type(op_type)} yet, sorry :("
            )

        op_str = compopt[op_type]

        new_v = ast3.Call(func=ast3.Attribute(value=node.left,
                                              attr=op_str,
                                              ctx=ast3.Load()),
                          args=[node.comparators[0]],
                          keywords=[
                              ast3.keyword(arg='pos',
                                           value=pos_as_tuple(node),
                                           ctx=ast3.Load())
                          ])
        return new_v
Exemplo n.º 4
0
 def visit_Cast(self, node):  # pylint: disable=invalid-name
     """Transform C cast into cast() function call."""
     to_type = self.visit(node.to_type)
     expr = self.visit(node.expr)
     _ = self.visit(node.coord)
     return typed_ast3.Call(func=typed_ast3.Name(id='cast', ctx=typed_ast3.Load()), args=[expr],
                            keywords=[typed_ast3.keyword(arg='type', value=to_type)])
Exemplo n.º 5
0
def make_numpy_constructor(function: str, arg: typed_ast3.AST,
                           data_type: typed_ast3.AST) -> typed_ast3.Call:
    return typed_ast3.Call(
        func=typed_ast3.Attribute(
            value=typed_ast3.Name(id='np', ctx=typed_ast3.Load()),
            attr=function, ctx=typed_ast3.Load()),
        args=[arg],
        keywords=[typed_ast3.keyword(arg='dtype', value=data_type)])
    def visit_Call(self, n):
        args = self.visit(n.args)
        if n.starargs is not None:
            args.append(ast3.Starred(self.visit(n.starargs), ast3.Load(), lineno=n.starargs.lineno, col_offset=n.starargs.col_offset))

        keywords = self.visit(n.keywords)
        if n.kwargs is not None:
            keywords.append(ast3.keyword(None, self.visit(n.kwargs)))

        return ast3.Call(self.visit(n.func),
                         args,
                         keywords)
Exemplo n.º 7
0
    def visit_Call(self, n):
        args = self.visit(n.args)
        if n.starargs is not None:
            args.append(ast3.Starred(self.visit(n.starargs), ast3.Load(), lineno=n.starargs.lineno, col_offset=n.starargs.col_offset))

        keywords = self.visit(n.keywords)
        if n.kwargs is not None:
            keywords.append(ast3.keyword(None, self.visit(n.kwargs)))

        return ast3.Call(self.visit(n.func),
                         args,
                         keywords)
Exemplo n.º 8
0
        def visit_FunctionDef(self, node: FunctionDef) -> FunctionDef:

            if node.name == 'main':

                kw = []

                if kwargs:
                    for k, v in kwargs.items():
                        kw.append(keyword(arg=k, value=v))

                if kwargs2parse:
                    for k, v in kwargs2parse.items():
                        kw.append(keyword(arg=k, value=parse(v)))

                node.body.insert(
                    0,
                    Assign(targets=[Name(id=name, ctx=Store())],
                           value=Call(func=Name(id=cls, ctx=Load()),
                                      args=[],
                                      keywords=kw)))

            return node
 def test_ast_validator_synthetic(self):
     examples = ((typed_ast3,
                  typed_ast3.FormattedValue(typed_ast3.Str('value'), None,
                                            None)),
                 (typed_ast3,
                  typed_ast3.keyword(
                      None, typed_ast3.Name('value', typed_ast3.Load()))),
                 (typed_ast3,
                  typed_ast3.ImportFrom('pkg',
                                        [typed_ast3.alias('module', None)],
                                        None)))
     for fields_first, (ast_module, example) in itertools.product(
         (False, True), examples):
         with self.subTest(example=example):
             # tree = ast_module.Expression(example)
             validator = AstValidator[ast_module](fields_first=fields_first,
                                                  mode=None)
             validator.visit(example)
Exemplo n.º 10
0
    def visit_BinOp(self, node: ast3.BinOp) -> VisitorOutput:
        "Transforms a binary operation into a function call. E.g. `ABC == MNO` into `ABC.eq(MNO)`"

        self.generic_visit(node)
        op_type = type(node.op)
        if op_type not in operations:
            raise AstTransformerError(
                f"Pytropos doesn't support the operation {type(op_type)} yet, sorry :("
            )

        op_str = operations[op_type]

        new_v = ast3.Call(func=ast3.Attribute(value=node.left,
                                              attr=op_str,
                                              ctx=ast3.Load()),
                          args=[node.right],
                          keywords=[
                              ast3.keyword(arg='pos',
                                           value=pos_as_tuple(node),
                                           ctx=ast3.Load())
                          ])
        return new_v
Exemplo n.º 11
0
    def visit_Call(self, node: ast3.Call) -> VisitorOutput:
        """Transforms a call to be handled by Pytropos

        For example, it converts::

            func(3, b, *c, d=2)

        into::

            func.call(st, Args((pt.int(3), st['b']), st['c'], {'d': pt.int(2)}), pos=...)"""

        self.generic_visit(node)

        args = []  # type: List[ast3.expr]
        starred = None  # type: Optional[ast3.expr]
        kwargs_keys = []  # type: List[ast3.expr]
        kwargs_values = []  # type: List[ast3.expr]

        for i, v in enumerate(node.args):
            if isinstance(v, ast3.Starred):
                starred = v.value
                break
            args.append(v)
        # In case a starred expresion was found
        else:
            # If there is something after the starred expr
            if len(node.args) > 0 and i < len(node.args) - 1:
                raise AstTransformerError(
                    f"{self.filename}:{v.lineno}:{v.col_offset}: Fatal Error: "
                    "Only one expression starred is allowed when calling a function"
                )

        for val in node.keywords:
            if val.arg is None:
                raise AstTransformerError(
                    f"{self.filename}:{v.lineno}:{v.col_offset}: Fatal Error: "
                    "No kargs parameters is allowed when calling a function")
            kwargs_keys.append(ast3.Str(s=val.arg))
            kwargs_values.append(val.value)

        new_call_args = [
            ast3.Tuple(
                elts=args,
                ctx=ast3.Load(),
            ),
        ]  # type: List[ast3.expr]

        if kwargs_keys:
            new_call_args.append(
                ast3.NameConstant(value=None) if starred is None else starred)
            new_call_args.append(
                ast3.Dict(keys=kwargs_keys, values=kwargs_values))
        elif starred is not None:
            new_call_args.append(starred)

        return ast3.Call(
            func=ast3.Attribute(
                value=node.func,
                attr='call',
                ctx=ast3.Load(),
            ),
            args=[
                ast3.Name(id='st', ctx=ast3.Load()),
                ast3.Call(
                    func=ast3.Attribute(
                        value=ast3.Name(id='pt', ctx=ast3.Load()),
                        attr='Args',
                        ctx=ast3.Load(),
                    ),
                    args=new_call_args,
                    keywords=[],
                )
            ],
            keywords=[
                ast3.keyword(arg='pos',
                             value=pos_as_tuple(node),
                             ctx=ast3.Load())
            ],
        )