ast_transformer.py 5.2 KB
Newer Older
1
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16 17 18
# gast is a generic AST to represent Python2 and Python3's Abstract Syntax Tree(AST).
# It provides a compatibility layer between the AST of various Python versions,
# as produced by ast.parse from the standard ast module.
# See details in https://github.com/serge-sans-paille/gast/
19

20
import os
21
from .base_transformer import (
22 23
    BaseTransformer,
)
24
from .early_return_transformer import (
25 26
    EarlyReturnTransformer,
)
27
from .assert_transformer import (
28 29
    AssertTransformer,
)
30
from .basic_api_transformer import (
31 32
    BasicApiTransformer,
)
33
from .break_continue_transformer import (
34 35 36
    BreakContinueTransformer,
    BreakTransformOptimizer,
)
37
from .call_transformer import (
38 39
    CallTransformer,
)
40
from .cast_transformer import (
41 42
    CastTransformer,
)
43
from .typehint_transformer import (
44 45
    TypeHintTransformer,
)
46
from .ifelse_transformer import (
47 48
    IfElseTransformer,
)
49
from .logical_transformer import (
50 51
    LogicalTransformer,
)
52
from .loop_transformer import (
53 54
    LoopTransformer,
)
55
from .return_transformer import (
56 57
    ReturnTransformer,
)
58
from .create_variable_transformer import (
59 60
    CreateVariableTransformer,
)
61
from .static_analysis import (
62 63
    StaticAnalysisVisitor,
)
64
from .tensor_shape_transformer import (
65 66
    TensorShapeTransformer,
)
67
from .decorator_transformer import (
68 69
    DecoratorTransformer,
)
70

71 72
from . import logging_utils
from .utils import ast_to_source_code
73

74
__all__ = []
75

76

77 78 79 80 81 82
def apply_optimization(transformers):
    """
    Judge wheter to apply optimized transformation, such as BreakTransformOptimizer.
    And not all optimized transformations are applied by default. It's controlled by
    'export FLAGS_optim_transformation=1'
    """
83 84 85 86 87
    flag = str(os.environ.get('FLAGS_optim_transformation')) in [
        '1',
        'True',
        'true',
    ]
88 89 90 91
    if flag:
        transformers.insert(3, BreakTransformOptimizer)


92
class DygraphToStaticAst(BaseTransformer):
93 94 95 96
    """
    Main class to transform Dygraph to Static Graph
    """

97 98 99
    def __init__(self):
        self.translator_logger = logging_utils.TranslatorLogger()

100
    def get_static_ast(self, root):
101
        # save root for some analysis may need global AST
102
        self.root = root
103
        self.static_analysis_visitor = StaticAnalysisVisitor(root)
104 105
        self.static_analysis_root = (
            self.static_analysis_visitor.get_node_wrapper_root()
106
        )
107
        self.decorate_func_name = None
108 109 110
        self.transfer_from_node_type(self.static_analysis_root)
        return self.static_analysis_root

111 112
    def _apply(self, transformer, node_wrapper, log_level):
        transformer(node_wrapper).transform()
113 114 115
        self.translator_logger.log_transformed_code(
            log_level, self.root, transformer.__name__
        )
116

117
    def transfer_from_node_type(self, node_wrapper):
118
        self.translator_logger.log(
119 120
            1, "Source code: \n{}".format(ast_to_source_code(self.root))
        )
121
        # Generic transformation
122
        self.visit(node_wrapper.node)
123

124
        transformers = [
125
            EarlyReturnTransformer,
126
            BasicApiTransformer,  # Basic Api
2
201716010711 已提交
127
            TensorShapeTransformer,  # Tensor.shape -> paddle.shape(Tensor)
128 129 130
            BreakContinueTransformer,  # break/continue in loops
            ReturnTransformer,  # return in functions
            LogicalTransformer,  # logical and/or/not
131
            CreateVariableTransformer,  # create undefined var for if / while / for
132 133 134 135 136
            LoopTransformer,  # for/while -> while_op
            IfElseTransformer,  # if/else -> cond_op
            AssertTransformer,  # assert statement
            CallTransformer,  # transform call recursively
            CastTransformer,  # type casting statement
137
            DecoratorTransformer,  # transform decorators to function call
138
            TypeHintTransformer,  # remove all typehint in gast.Name
139 140
        ]

141 142
        apply_optimization(transformers)

143 144 145 146
        for index, transformer in enumerate(transformers):
            self._apply(transformer, node_wrapper, log_level=index + 1)

        self.translator_logger.log_transformed_code(
147 148
            logging_utils.LOG_AllTransformer, self.root, "All Transformers"
        )
149

150 151 152
    def visit_FunctionDef(self, node):
        if self.decorate_func_name is None:
            self.decorate_func_name = node.name
153

154 155 156 157 158 159 160 161 162 163 164
        self.generic_visit(node)
        return node

    def get_module_name(self):
        """
        Return the main function name which will be used as module name
        in ast_to_func.
        """
        # Should consider BaseAPITransformer which add new module name in Yamei's PR.
        assert self.decorate_func_name, "decorate_func_name shall not be None."
        return self.decorate_func_name