loop_transformer.py 27.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

import copy
16
from paddle.utils import gast
17 18 19

from collections import defaultdict
from paddle.fluid import unique_name
20 21 22
from paddle.fluid.dygraph.dygraph_to_static.static_analysis import (
    AstNodeWrapper,
)
23
from paddle.fluid.dygraph.dygraph_to_static.static_analysis import NodeVarType
24 25 26
from paddle.fluid.dygraph.dygraph_to_static.static_analysis import (
    StaticAnalysisVisitor,
)
27
from paddle.fluid.dygraph.dygraph_to_static.utils import ast_to_source_code
28
from paddle.fluid.dygraph.dygraph_to_static.utils import get_attribute_full_name
29 30 31 32 33 34 35 36
from paddle.fluid.dygraph.dygraph_to_static.utils import (
    create_nonlocal_stmt_nodes,
    create_get_args_node,
    create_set_args_node,
)
from paddle.fluid.dygraph.dygraph_to_static.utils import (
    FunctionNameLivenessAnalysis,
)
37
from .ifelse_transformer import ARGS_NAME
38 39 40 41 42 43 44 45 46 47 48 49 50
from paddle.fluid.dygraph.dygraph_to_static.base_transformer import (
    BaseTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.base_transformer import (
    ForLoopTuplePreTransformer,
)
from paddle.fluid.dygraph.dygraph_to_static.base_transformer import (
    ForNodeVisitor,
)
from paddle.fluid.dygraph.dygraph_to_static.utils import (
    GetterSetterHelper,
    create_name_str,
)
51 52 53 54 55 56

__all__ = ['LoopTransformer', 'NameVisitor']

WHILE_CONDITION_PREFIX = 'while_condition'
WHILE_BODY_PREFIX = 'while_body'

57 58 59
FOR_CONDITION_PREFIX = 'for_loop_condition'
FOR_BODY_PREFIX = 'for_loop_body'

60

61 62 63 64 65 66 67 68
def create_while_nodes(
    condition_name,
    body_name,
    loop_var_names,
    push_pop_names,
    getter_name,
    setter_name,
):
69 70 71 72 73 74 75 76 77 78 79
    """
    Returns a list of gast.Node which represents the calling of Paddle
    controlflow while_loop.

    Usually, the list just contain 1 statement such as:

    [a, b, c] = paddle.jit.dy2static.convert_while_loop(
            condition_name, body_name, [a, b, c])

    where a, b, c are in loop_var_names.

H
Huihuang Zheng 已提交
80 81
    However, if loop_var_names contains property such as foo.x, we cannot
    assign the property as output of convert_while_loop because Python
82 83 84 85 86 87 88 89 90 91 92 93
    property is a kind of read-only attribute. To handle the case, we replace
    the attributes which are output of convert_while_loop with generated
    variables, then if we know the attribute is not read-only at runtime, we
    assign the attribute. The created statements are like:

    [a, b, __attribute_variable_1] = paddle.jit.dy2static.convert_while_loop(
            condition_name, body_name, [a, b, foo.x])
    if not isinstance(getattr(type(foo), x, None), property): foo.x = __attribute_variable_1

    The number of above statements is not only 1, that's why the return type is
    a list of gast.Node.
    """
94 95 96 97 98 99
    # NOTE(liym27):
    # It's better to parse the source code into an AST node than to customize an AST node
    # including child nodes, because it is easy to mistake the ast node type when customizing the node.
    #
    # For example: loop_var_names = [a, b, foo.x], the type of `a` or `b` is gast.Name,
    # but the type of `foo.x` gast.Attribute.
100 101 102 103
    # We have to make loop_var_names and assign_loop_var_names with same order
    # set doesn't have order so we convert it to list
    loop_var_names = list(loop_var_names)
    assign_loop_var_names = []
104
    for name in loop_var_names:
105
        assign_loop_var_names.append(name)
106

107
    while_func_name = "_jst.While"
108 109 110 111 112 113 114 115 116 117 118
    while_node_str = (
        "{}({}, {}, {}, {}, return_name_ids={}, push_pop_names={})".format(
            while_func_name,
            condition_name,
            body_name,
            getter_name,
            setter_name,
            create_name_str(loop_var_names),
            create_name_str(push_pop_names),
        )
    )
119 120
    while_node = gast.parse(while_node_str).body[0]

121 122
    ret = [while_node]
    return ret
123 124 125 126 127 128 129 130


class NameVisitor(gast.NodeVisitor):
    '''
    Analysis name liveness for loop transformer
    '''

    def __init__(self, root_node):
131
        # Set of gast.Name or gast.Attribute for variables
132
        self.current_seen_vars = set()
133

134 135 136
        # List of gast.While/gast.For nodes
        self.current_loop = []

137 138 139 140
        # List of nodes that have scope of variables.
        self.nodes_with_scope = []
        self.blacklist_names = {"False", "True", "None"}

141 142
        # Mapping from gast.While/gast.For to variable nodes
        self.before_loop_body_vars = defaultdict(set)
143 144
        # NOTE: Use ordered list as dict value
        self.in_loop_vars = defaultdict(list)
145

146 147 148 149 150 151
        # Mapping from gast.While/gast.For to variable nodes which is condition
        # of loop or being modified during the loop
        self.write_in_loop = defaultdict(set)
        self.condition_vars = defaultdict(set)
        self.in_condition = False

152 153 154
        # Some names are types, we shouldn't record them as loop var names.
        self.type_vars = set()

155
        self.static_analysis_visitor = StaticAnalysisVisitor(root_node)
156 157
        self.node_to_wrapper_map = (
            self.static_analysis_visitor.get_node_to_wrapper_map()
158 159
        )

160 161 162
        self.visit(root_node)

    def get_loop_var_names(self, node):
163
        assert isinstance(
164 165
            node, (gast.While, gast.For)
        ), "Input node is not gast loop node"
166 167
        loop_var_names = set()
        create_var_names = set()
H
Huihuang Zheng 已提交
168
        read_context = {type(gast.Load()), type(gast.AugLoad())}
169

170 171 172 173 174 175
        in_loop_vars_list = self.in_loop_vars[node]

        # get dict `var_name_to_ctxs`
        var_name_to_ctxs = defaultdict(list)
        for var_node in in_loop_vars_list:
            var_name_to_ctxs[self._var_node_to_name(var_node)].append(
176 177
                var_node.ctx
            )
178 179

        in_loop_vars = set(in_loop_vars_list)
180
        in_loop_vars = self._remove_unnecessary_vars(in_loop_vars, node)
181
        in_loop_name_strs = self._var_nodes_to_names(in_loop_vars)
182

183
        before_loop_body_vars = self.before_loop_body_vars[node]
184
        before_loop_body_vars = self._remove_unnecessary_vars(
185 186
            before_loop_body_vars, node
        )
187
        before_loop_name_strs = self._var_nodes_to_names(before_loop_body_vars)
188

189 190 191
        after_loop_vars = (
            self.current_seen_vars - before_loop_body_vars - in_loop_vars
        )
192
        after_loop_vars = self._remove_unnecessary_vars(after_loop_vars, node)
193 194 195
        after_loop_name_strs = self._var_nodes_to_names(
            after_loop_vars, read_context
        )
196 197
        condition_vars = self.condition_vars[node]
        condition_names = self._var_nodes_to_names(condition_vars)
198

199 200 201 202 203 204 205
        write_vars = self.write_in_loop[node]
        write_names = self._var_nodes_to_names(write_vars)

        name_to_type = {}
        for var in in_loop_vars:
            wrapper = self.node_to_wrapper_map[var]
            name_to_type[self._var_node_to_name(var)] = wrapper.node_var_type
206 207
        for name in in_loop_name_strs:
            if name in before_loop_name_strs:
208 209 210 211 212
                # If a variable is used in loop and created before loop

                # If this var is a basic variable and read-only and not
                # condition var, it may not be loop_var else it should
                # be in loop_var as input
213
                if (name not in condition_names) and (name not in write_names):
214
                    continue
215
                loop_var_names.add(name)
216

217 218 219
            elif name in after_loop_name_strs:
                # If a variable is created in the while loop and read after
                # loop, it should be in loop_var and we should create it
220 221 222 223

                # because name in after_loop_name must be initialized in loop
                # So it is write-only, we don't have to filter read-only basic
                # vars out
224 225
                loop_var_names.add(name)
                create_var_names.add(name)
226 227 228 229 230 231 232 233 234 235 236 237 238
            else:
                # If a variable is used and created in loop, but used before created,
                # it should be in loop_var and we should create it.

                # For example, `var_a` should be in loop_var and we should create it.
                #
                #   res = 0
                #   for i, x in enumerate(x_array):
                #       if i > 2:
                #           x = func1(var_a)
                #       var_a = func2(x)
                #

239 240 241 242 243
                is_created = False
                for ctx in var_name_to_ctxs[name]:
                    if isinstance(ctx, gast.Store):
                        is_created = True

244 245 246 247
                if (
                    isinstance(var_name_to_ctxs[name][0], gast.Load)
                    and is_created
                ):
248 249
                    loop_var_names.add(name)
                    create_var_names.add(name)
250

251 252 253
        return loop_var_names, create_var_names

    def visit_Name(self, node):
254 255 256
        if self._is_call_func_name_node(node):
            self.generic_visit(node)
            return
257
        if node.id in self.blacklist_names:
258 259
            self.generic_visit(node)
            return
260

261
        self.current_seen_vars.add(node)
262
        write_context = {
263 264
            type(gast.Store()),
            type(gast.AugStore()),
265
            type(gast.Del()),
266
        }
267

268
        for loop_node in self.current_loop:
269
            self.in_loop_vars[loop_node].append(node)
270 271
            if type(node.ctx) in write_context:
                self.write_in_loop[loop_node].add(node)
272 273
        if self.in_condition:
            self.condition_vars[loop_node].add(node)
274 275
        self.generic_visit(node)

276 277 278
    def visit_FunctionDef(self, node):
        self.nodes_with_scope.append(node)
        self.blacklist_names.add(node.name)
279

280 281 282 283 284 285 286 287 288 289
        # The variables in the function are not visible to the outside scope.
        before_func_seen_vars = copy.copy(self.current_seen_vars)

        self.generic_visit(node)
        self.nodes_with_scope.pop()
        # After exiting the scope of the node, variables in this scope
        # should be removed from self.current_seen_vars.
        if self.nodes_with_scope:
            self.current_seen_vars = before_func_seen_vars

290 291 292 293 294 295 296 297 298 299
    def visit(self, node):
        method = 'visit_' + node.__class__.__name__
        visitor = getattr(self, method, self.generic_visit)
        ret = visitor(node)
        return ret

    def visit_Attribute(self, node):
        if self._is_call_func_name_node(node):
            return
        attr_full_name = get_attribute_full_name(node)
300 301 302 303 304 305 306 307 308 309
        # Class variables are not allowed to appear in the arguments list
        # of defined function under class methods in Python.
        """
        def class_func(self):
            def while_loop_body(self.x, y) # `self.x` is illegal.
        """
        # TODO: If do change the variable with `self.var`, need a better
        # way to deal with this case.
        if attr_full_name.startswith("self."):
            return
310
        self.current_seen_vars.add(node)
311

312
        for loop_node in self.current_loop:
313
            self.in_loop_vars[loop_node].append(node)
314

315 316 317
        # sub-nodes are visited during get_attribute_full_name and we shouldn't
        # visit again

318 319
    def visit_For(self, node):
        self.current_loop.append(node)
320
        self.in_condition = True
321
        self.visit(node.target)
322 323
        self.visit(node.iter)
        self.in_condition = False
324
        self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars)
325 326 327 328 329
        self.generic_visit(node)
        self.current_loop.pop()

    def visit_While(self, node):
        self.current_loop.append(node)
330
        self.in_condition = True
331
        self.visit(node.test)
332
        self.in_condition = False
333
        self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars)
334 335 336
        self.generic_visit(node)
        self.current_loop.pop()

337 338 339 340 341 342 343
    def visit_Call(self, node):
        # Store type var names such as "isinstance(x, some_type_names)" and
        # Remove them later
        if isinstance(node.func, gast.Name) and node.func.id == 'isinstance':
            type_node = node.args[1]
            if isinstance(type_node, gast.Tuple):
                for element in type_node.elts:
344
                    self.type_vars.add(ast_to_source_code(element).strip())
345
            else:
346
                self.type_vars.add(ast_to_source_code(type_node).strip())
347 348
        self.generic_visit(node)

349 350 351 352
    def _var_nodes_to_names(self, node_set, ctx_filter_set=None):
        ret = set()
        for node in node_set:
            if ctx_filter_set is None or type(node.ctx) in ctx_filter_set:
353
                ret.add(self._var_node_to_name(node))
354 355
        return ret

356 357 358 359 360 361 362 363
    def _var_node_to_name(self, node):
        if isinstance(node, gast.Name):
            return node.id
        elif isinstance(node, gast.Attribute):
            return get_attribute_full_name(node)

    def _node_var_type_is_basic(self, node_var_type):
        basic_types = {
364 365 366 367
            NodeVarType.BOOLEAN,
            NodeVarType.INT,
            NodeVarType.FLOAT,
            NodeVarType.STRING,
368 369 370 371 372 373
        }
        for t in node_var_type:
            if t in basic_types:
                return True
        return False

374
    def _is_call_func_name_node(self, node):
375
        parent_node = self._get_parent_node(node)
376 377
        if isinstance(parent_node, gast.Call) and parent_node.func == node:
            return True
378 379
        return False

380 381 382
    def _is_global_or_nonlocal(self, node):
        return False

383 384 385 386 387 388 389 390 391
    def _is_ancestor_node(self, ancestor_node, node):
        parent_node = self._get_parent_node(node)

        while parent_node is not None:
            if parent_node == ancestor_node:
                return True
            parent_node = self._get_parent_node(parent_node)
        return False

392 393 394
    def _get_parent_node(self, node):
        wrapper_node = self.node_to_wrapper_map.get(node)
        if wrapper_node:
395 396 397
            if wrapper_node.parent:
                parent_node = wrapper_node.parent.node
                return parent_node
398 399
        return None

400
    def _remove_unnecessary_vars(self, loop_vars, loop_node):
401
        """
402 403 404
        Remove unnecessary vars from before_loop_vars, after_loop_vars or in_loop_vars about loop_node.
            1. Remove target vars of gast.For from before_loop_vars or after_loop_vars.
            2. Remove vars only in gast.comprehension.
405
            3. Remove vars that are type names, for example: "isinstance(x, var_type_name)"
406
        :param loop_vars: before_loop_vars, after_loop_vars or in_loop_vars of loop_node.
407 408 409
        :param loop_node: Current loop node.
        """

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
        def filter_name_nodes_from(root_node, target_var_names):
            """
            Filter children with gast.Name type from node.(inclusivly)
            """
            name_nodes = set()
            if isinstance(root_node, gast.Name):
                if node.id in target_var_names:
                    name_nodes.add(root_node)
            for child_node in gast.walk(root_node):
                if isinstance(child_node, gast.Name):
                    if child_node.id in target_var_names:
                        name_nodes.add(child_node)

            return name_nodes

425 426 427 428
        vars_of_list_generator = set()
        target_vars_of_for_node = set()

        for name_node in loop_vars:
429 430 431 432 433
            if not isinstance(name_node, gast.Name):
                continue

            parent_node = self._get_parent_node(name_node)

434 435 436 437
            # NOTE: gast.For.target or gast.comprehension.target can be gast.Tuple.
            #  For examples:
            #   1) `for i, j in enumerate(x)` has two target vars: i and j
            #   2) `[x for x,y in array]` has two target vars: x and y
438 439 440
            if isinstance(parent_node, gast.Tuple):
                parent_node = self._get_parent_node(parent_node)

441 442 443 444 445 446 447
            # 1. Get vars only in gast.comprehension.
            # For examples:
            #  1) [x for x,y in array] -> x, x, y
            #  2) [f(x) for x in array] -> x
            #  3) [func(x, y) for x in array] -> x, x
            if isinstance(parent_node, gast.comprehension):
                # 1.1 target vars in list/set comprehensions
448 449 450 451 452 453
                target_node = parent_node.target
                if isinstance(target_node, gast.Tuple):
                    target_vars = target_node.elts
                else:
                    target_vars = [target_node]

454
                vars_of_list_generator = vars_of_list_generator | set(
455 456
                    target_vars
                )
457 458 459

                # 1.2 vars from target vars used in elt_node
                target_var_names = {var.id for var in target_vars}
460 461 462 463 464 465 466 467 468
                comp_node = self._get_parent_node(parent_node)
                elt_nodes = []
                if isinstance(comp_node, gast.ListComp):
                    elt_nodes.append(comp_node.elt)
                elif isinstance(comp_node, gast.DictComp):
                    elt_nodes.extend([comp_node.key, comp_node.value])

                for node in elt_nodes:
                    vars_of_list_generator |= filter_name_nodes_from(
469 470
                        node, target_var_names
                    )
471

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
            # 2. Get target vars or vars from target vars used in for-loop but the for-loop is
            #   1) not the "loop_node" itself
            #   2) not the ancestor of the "loop_node"
            #
            # For examples:
            #   for k in range(x):   # if it's this "loop_node", i or j both should be target vars.
            #      # do something
            #
            #   for i in range(a):   # if it's this "loop_node", k or j should be in target vars but i should not.
            #     for j in range(a): # if it's this "loop_node", k should be in target_vars but i or j should not.
            #       x = i+j
            elif isinstance(parent_node, gast.For):
                if parent_node is loop_node:
                    continue
                if self._is_ancestor_node(parent_node, loop_node):
                    continue
488 489 490 491 492 493
                # 2.1 target vars in gast.For node.
                target_node = parent_node.target
                if isinstance(target_node, gast.Tuple):
                    target_vars = target_node.elts
                else:
                    target_vars = [target_node]
494

495
                target_vars_of_for_node = target_vars_of_for_node | set(
496 497
                    target_vars
                )
498

499 500 501
        # 2.2 vars from target vars used in for-loop
        target_vars_name_strs = {var.id for var in target_vars_of_for_node}
        for var in loop_vars:
502 503
            if not isinstance(var, gast.Name):
                continue
504 505 506 507
            if (
                var.id in target_vars_name_strs
                and var not in self.condition_vars[loop_node]
            ):
508
                target_vars_of_for_node.add(var)
509

510
        removed_vars = target_vars_of_for_node | vars_of_list_generator
511 512 513

        # 3. Remove var type names which are stored in self.type_vars
        for var in loop_vars:
514
            if ast_to_source_code(var).strip() in self.type_vars:
515 516
                removed_vars.add(var)

517
        return loop_vars - removed_vars
518

519

520
class LoopTransformer(BaseTransformer):
521 522 523 524 525 526 527
    """
    This class transforms python while/for statement into Static Graph Ast
    """

    def __init__(self, wrapper_root):
        assert isinstance(
            wrapper_root, AstNodeWrapper
528
        ), "Input non-AstNodeWrapper node for the initialization of LoopTransformer."
529 530
        self.wrapper_root = wrapper_root
        self.root = wrapper_root.node
531
        FunctionNameLivenessAnalysis(self.root)
532 533

    def transform(self):
534
        ForLoopTuplePreTransformer(self.wrapper_root).transform()
535 536
        self.visit(self.root)

537 538 539 540 541 542
    def visit_While(self, node):
        self.generic_visit(node)
        new_stmts = self.get_while_stmt_nodes(node)
        return new_stmts

    def visit_For(self, node):
543
        self.generic_visit(node)
544 545
        new_stmts = self.get_for_stmt_nodes(node)
        return new_stmts
546 547 548 549 550 551 552 553 554

    def replace_stmt_list(self, body_list):
        if not isinstance(body_list, list):
            return

        i = 0
        while i < len(body_list):
            if isinstance(body_list[i], gast.While):
                new_stmts = self.get_while_stmt_nodes(body_list[i])
555
                body_list[i : i + 1] = new_stmts
556 557
                i += len(new_stmts)
            elif isinstance(body_list[i], gast.For):
558
                new_stmts = self.get_for_stmt_nodes(body_list[i])
559
                body_list[i : i + 1] = new_stmts
560
                i += len(new_stmts)
561 562 563
            else:
                i += 1

564 565 566
    def get_for_stmt_nodes(self, node):
        # TODO: consider for - else in python

567 568
        # 1. get key statements for different cases
        # NOTE 1: three key statements:
569 570 571 572
        #   1). init_stmts: list[node], prepare nodes of for loop, may not only one
        #   2). cond_stmt: node, condition node to judge whether continue loop
        #   3). body_stmts: list[node], updated loop body, sometimes we should change
        #       the original statement in body, not just append new statement
573 574 575 576 577 578
        #
        # NOTE 2: The following `for` statements will be transformed to `while` statements:
        #   1). for x in range(*)
        #   2). for x in iter_var
        #   3). for i, x in enumerate(*)

579
        current_for_node_parser = ForNodeVisitor(node)
580 581
        stmts_tuple = current_for_node_parser.parse()
        if stmts_tuple is None:
582
            return [node]
583
        init_stmts, cond_stmt, body_stmts = stmts_tuple
584
        # 2. get original loop vars
585 586 587 588
        loop_var_names, create_var_names = (
            node.pd_scope.modified_vars(),
            node.pd_scope.created_vars(),
        )
589
        push_pop_names = list(node.pd_scope.variadic_length_vars())
590
        # TODO: Remove the bunch of code?  We have the unique format `for A in B:`
591 592 593 594
        # NOTE: in 'for x in var' or 'for i, x in enumerate(var)' cases,
        # we need append new loop var & remove useless loop var
        #   1. for x in var -> x is no need
        #   2. for i, x in enumerate(var) -> x is no need
595
        if current_for_node_parser.is_for_iter():
596 597 598
            iter_var_name = current_for_node_parser.iter_var_name
            iter_idx_name = current_for_node_parser.iter_idx_name
            loop_var_names.add(iter_idx_name)
599 600
            if current_for_node_parser.enum_idx_name is not None:
                loop_var_names.add(current_for_node_parser.enum_idx_name)
601

602
        # 3. prepare result statement list
603 604 605 606 607 608 609
        new_stmts = []
        # Python can create variable in loop and use it out of loop, E.g.
        #
        # for x in range(10):
        #     y += x
        # print(x) # x = 10
        #
610 611
        # We don't need to create static variable for them, because
        # we do this in CreateUndefinedVarTransformer
612 613 614 615 616 617 618 619

        # create non-local statement for body and cond.
        nonlocal_names = list(loop_var_names | create_var_names)
        nonlocal_names.sort()
        # TODO(dev): Need a better way to deal this.
        if ARGS_NAME in nonlocal_names:
            nonlocal_names.remove(ARGS_NAME)

620
        nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
621

622
        # 4. append init statements
623
        new_stmts.extend(init_stmts)
624

625
        # 5. create & append condition function node
626 627
        condition_func_node = gast.FunctionDef(
            name=unique_name.generate(FOR_CONDITION_PREFIX),
628 629 630 631 632 633 634 635 636
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
637
            body=nonlocal_stmt_node + [gast.Return(value=cond_stmt)],
638 639
            decorator_list=[],
            returns=None,
640 641
            type_comment=None,
        )
642 643
        new_stmts.append(condition_func_node)

644
        # 6. create & append loop body function node
645
        # append return values for loop body
646 647
        body_func_node = gast.FunctionDef(
            name=unique_name.generate(FOR_BODY_PREFIX),
648 649 650 651 652 653 654 655 656
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
657
            body=nonlocal_stmt_node + body_stmts,
658 659
            decorator_list=[],
            returns=None,
660 661
            type_comment=None,
        )
662 663
        new_stmts.append(body_func_node)

664 665 666
        helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_names)
        get_args_node = create_get_args_node(helper.union())
        set_args_node = create_set_args_node(helper.union())
667
        # 7. create & append while loop node
668 669 670 671 672 673 674 675
        while_loop_nodes = create_while_nodes(
            condition_func_node.name,
            body_func_node.name,
            nonlocal_names,
            push_pop_names,
            get_args_node.name,
            set_args_node.name,
        )
676
        new_stmts.extend([get_args_node, set_args_node])
677
        new_stmts.extend(while_loop_nodes)
678 679 680

        return new_stmts

681
    def get_while_stmt_nodes(self, node):
682 683 684 685
        loop_var_names, create_var_names = (
            node.pd_scope.modified_vars(),
            node.pd_scope.created_vars(),
        )
686
        push_pop_names = list(node.pd_scope.variadic_length_vars())
687 688
        new_stmts = []

689 690 691 692 693 694 695
        # create non-local statement for body and cond.
        nonlocal_names = list(loop_var_names | create_var_names)
        nonlocal_names.sort()
        # TODO(dev): Need a better way to deal this.
        if ARGS_NAME in nonlocal_names:
            nonlocal_names.remove(ARGS_NAME)

696
        nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
697

698 699 700 701 702 703 704
        # Python can create variable in loop and use it out of loop, E.g.
        #
        # while x < 10:
        #     x += 1
        #     y = x
        # z = y
        #
705 706
        # We don't need to create static variable for those variables, because
        # we do this in CreateUndefinedVarTransformer
707 708 709

        condition_func_node = gast.FunctionDef(
            name=unique_name.generate(WHILE_CONDITION_PREFIX),
710 711 712 713 714 715 716 717 718
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
719
            body=nonlocal_stmt_node + [gast.Return(value=node.test)],
720 721
            decorator_list=[],
            returns=None,
722 723
            type_comment=None,
        )
724

725 726 727 728 729
        new_stmts.append(condition_func_node)

        new_body = node.body
        body_func_node = gast.FunctionDef(
            name=unique_name.generate(WHILE_BODY_PREFIX),
730 731 732 733 734 735 736 737 738
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
739
            body=nonlocal_stmt_node + new_body,
740 741
            decorator_list=[],
            returns=None,
742 743
            type_comment=None,
        )
744
        new_stmts.append(body_func_node)
745 746 747 748

        helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_names)
        get_args_node = create_get_args_node(helper.union())
        set_args_node = create_set_args_node(helper.union())
749

750 751 752 753 754 755 756 757
        while_loop_nodes = create_while_nodes(
            condition_func_node.name,
            body_func_node.name,
            nonlocal_names,
            push_pop_names,
            get_args_node.name,
            set_args_node.name,
        )
758
        new_stmts.extend([get_args_node, set_args_node])
759
        new_stmts.extend(while_loop_nodes)
760
        return new_stmts