How to use the pythran.passmanager.Transformation function in pythran

To help you get started, we’ve selected a few pythran examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github serge-sans-paille / pythran / pythran / transformations / normalize_static_if.py View on Github external
if flag == LOOP_BREAK:
                ret_val.func.attr = "StaticIfBreak"
            else:
                ret_val.func.attr = "StaticIfCont"
        else:
            new_node.value.elts[0].n = flag
        return new_node

    def visit_Break(self, node):
        return self.patch_Control(node, LOOP_BREAK)

    def visit_Continue(self, node):
        return self.patch_Control(node, LOOP_CONT)


class NormalizeStaticIf(Transformation):

    def __init__(self):
        super(NormalizeStaticIf, self).__init__(StaticExpressions, Ancestors,
                                                DefUseChains)

    def visit_Module(self, node):
        self.new_functions = []
        self.funcs = []
        self.generic_visit(node)
        node.body.extend(self.new_functions)
        return node

    def escaping_ids(self, scope_stmt, stmts):
        'gather sets of identifiers defined in stmts and used out of it'
        assigned_ids = self.gather(IsAssigned, self.make_fake(stmts))
        escaping = set()
github serge-sans-paille / pythran / pythran / optimizations / pattern_transform.py View on Github external
def sub():
        return ast.Call(func=ast.Attribute(
            ast.Attribute(
                ast.Name('__builtin__', ast.Load(), None, None),
                'str',
                ast.Load()),
            'join', ast.Load()),
            args=[ast.Constant(Placeholder(1), None),
                  ast.Tuple([Placeholder(0), Placeholder(2)], ast.Load())],
            keywords=[])


know_pattern = [x for x in globals().values() if hasattr(x, "pattern")]


class PlaceholderReplace(Transformation):

    """ Helper class to replace the placeholder once value is collected. """

    def __init__(self, placeholders):
        """ Store placeholders value collected. """
        self.placeholders = placeholders
        super(PlaceholderReplace, self).__init__()

    def visit(self, node):
        """ Replace the placeholder if it is one or continue. """
        if isinstance(node, Placeholder):
            return self.placeholders[node.id]
        else:
            return super(PlaceholderReplace, self).visit(node)
github serge-sans-paille / pythran / pythran / optimizations / constant_folding.py View on Github external
dummy_module = ast.Module([s for s in node.body
                                   if not isinstance(s, ast.Import)],
                                  [])
        eval(compile(ast.gast_to_ast(dummy_module),
                     '', 'exec'),
             self.env)

        super(ConstantFolding, self).prepare(node)

    def skip(self, node):
        return node

    visit_Constant = visit_Name = skip

    visit_List = visit_Set = Transformation.generic_visit
    visit_Dict = visit_Tuple = Transformation.generic_visit

    def visit_Index(self, node):
        value = self.visit(node.value)
        if value is not node.value:
            return ast.Index(value)
        else:
            return node

    def generic_visit(self, node):
        if isinstance(node, ast.expr) and node in self.constant_expressions:
            fake_node = ast.Expression(node)
            code = compile(ast.gast_to_ast(fake_node),
                           '', 'eval')
            try:
                value = eval(code, self.env)
                new_node = to_ast(value)
github serge-sans-paille / pythran / pythran / optimizations / comprehension_patterns.py View on Github external
import gast as ast
import sys

if sys.version_info.major == 2:
    MODULE = 'itertools'
    IMAP = 'imap'
    IFILTER = 'ifilter'
else:
    MODULE = '__builtin__'
    IMAP = 'map'
    IFILTER = 'filter'
ASMODULE = mangle(MODULE)


class ComprehensionPatterns(Transformation):
    '''
    Transforms list comprehension into intrinsics.
    >>> import gast as ast
    >>> from pythran import passmanager, backend
    >>> node = ast.parse("def foo(y) : return (x for x in y)")
    >>> pm = passmanager.PassManager("test")
    >>> _, node = pm.apply(ComprehensionPatterns, node)
    >>> 'map' in pm.dump(backend.Python, node)
    True

    >>> node = ast.parse("def foo(y) : return [0 for _ in __builtin__.range(y)]")
    >>> _, node = pm.apply(ComprehensionPatterns, node)
    >>> print(pm.dump(backend.Python, node))
    def foo(y):
        return ([0] * __builtin__.len(__builtin__.range(y)))
    '''
github serge-sans-paille / pythran / pythran / transformations / normalize_method_calls.py View on Github external
""" NormalizeMethodCalls turns built in method calls into function calls. """

from pythran.analyses import Globals
from pythran.passmanager import Transformation
from pythran.syntax import PythranSyntaxError
from pythran.tables import attributes, functions, methods, MODULES
from pythran.conversion import mangle, demangle
from pythran.utils import isstr

import gast as ast
from functools import reduce


class NormalizeMethodCalls(Transformation):
    '''
    Turns built in method calls into function calls.

    >>> import gast as ast
    >>> from pythran import passmanager, backend
    >>> node = ast.parse("[].append(12)")
    >>> pm = passmanager.PassManager("test")
    >>> _, node = pm.apply(NormalizeMethodCalls, node)
    >>> print(pm.dump(backend.Python, node))
    __builtin__.list.append([], 12)
    '''

    def __init__(self):
        Transformation.__init__(self, Globals)
        self.imports = {'__builtin__': '__builtin__'}
        self.to_import = set()
github serge-sans-paille / pythran / pythran / transformations / normalize_identifiers.py View on Github external
def __init__(self):
        self.renamings = dict()
        Transformation.__init__(self, Identifiers)
github serge-sans-paille / pythran / pythran / optimizations / comprehension_patterns.py View on Github external
def __init__(self):
        Transformation.__init__(self, OptimizableComprehension)
github serge-sans-paille / pythran / pythran / transformations / remove_named_arguments.py View on Github external
from pythran.analyses import Aliases
from pythran.passmanager import Transformation
from pythran.syntax import PythranSyntaxError
from pythran.tables import MODULES

import gast as ast
from copy import deepcopy


def handle_special_calls(func_alias, node):
    if func_alias is MODULES['numpy']['arange']:
        if len(node.args) == 1:
            node.args.insert(0, ast.Constant(0, None))


class RemoveNamedArguments(Transformation):
    '''
    Replace call with named arguments to regular calls

    >>> import gast as ast
    >>> from pythran import passmanager, backend
    >>> code = 'def foo(x, y): return x + y\\ndef bar(z): return foo(y=z, x=0)'
    >>> node = ast.parse(code)
    >>> pm = passmanager.PassManager("test")
    >>> _, node = pm.apply(RemoveNamedArguments, node)
    >>> print(pm.dump(backend.Python, node))
    def foo(x, y):
        return (x + y)
    def bar(z):
        return foo(0, z)
    '''
github serge-sans-paille / pythran / pythran / optimizations / square.py View on Github external
""" Replaces **2 by a call to numpy.square. """

from pythran.passmanager import Transformation
from pythran.analyses.ast_matcher import ASTMatcher, AST_any
from pythran.conversion import mangle
from pythran.utils import isnum

import gast as ast
import copy


class Square(Transformation):

    """
    Replaces **2 by a call to numpy.square.

    >>> import gast as ast
    >>> from pythran import passmanager, backend
    >>> node = ast.parse('a**2')
    >>> pm = passmanager.PassManager("test")
    >>> _, node = pm.apply(Square, node)
    >>> print(pm.dump(backend.Python, node))
    import numpy as __pythran_import_numpy
    __pythran_import_numpy.square(a)
    >>> node = ast.parse('__pythran_import_numpy.power(a,2)')
    >>> pm = passmanager.PassManager("test")
    >>> _, node = pm.apply(Square, node)
    >>> print(pm.dump(backend.Python, node))