ast_transformer.py 5.3 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 .print_transformer import (
56 57
    PrintTransformer,
)
58
from .return_transformer import (
59 60
    ReturnTransformer,
)
61
from .create_variable_transformer import (
62 63
    CreateVariableTransformer,
)
64
from .static_analysis import (
65 66
    StaticAnalysisVisitor,
)
67
from .tensor_shape_transformer import (
68 69
    TensorShapeTransformer,
)
70
from .decorator_transformer import (
71 72
    DecoratorTransformer,
)
73

74 75
from . import logging_utils
from .utils import ast_to_source_code
76

77
__all__ = ['DygraphToStaticAst']
78

79

80 81 82 83 84 85
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'
    """
86 87 88 89 90
    flag = str(os.environ.get('FLAGS_optim_transformation')) in [
        '1',
        'True',
        'true',
    ]
91 92 93 94
    if flag:
        transformers.insert(3, BreakTransformOptimizer)


95
class DygraphToStaticAst(BaseTransformer):
96 97 98 99
    """
    Main class to transform Dygraph to Static Graph
    """

100 101 102
    def __init__(self):
        self.translator_logger = logging_utils.TranslatorLogger()

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

114 115
    def _apply(self, transformer, node_wrapper, log_level):
        transformer(node_wrapper).transform()
116 117 118
        self.translator_logger.log_transformed_code(
            log_level, self.root, transformer.__name__
        )
119

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

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

145 146
        apply_optimization(transformers)

147 148 149 150
        for index, transformer in enumerate(transformers):
            self._apply(transformer, node_wrapper, log_level=index + 1)

        self.translator_logger.log_transformed_code(
151 152
            logging_utils.LOG_AllTransformer, self.root, "All Transformers"
        )
153

154 155 156
    def visit_FunctionDef(self, node):
        if self.decorate_func_name is None:
            self.decorate_func_name = node.name
157

158 159 160 161 162 163 164 165 166 167 168
        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