Skip to content
Myr

optimizer.py

This file

Path

src/jinja2/optimizer.py

47 lines · 1.6 KiB · Python

Last changed by

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

History of this file

Take it

1"""The optimizer tries to constant fold expressions and modify the AST2in place so that it should be faster to evaluate.34Because the AST does not contain all the scoping information and the5compiler has to find that out, we cannot do all the optimizations we6want. For example, loop unrolling doesn't work because unrolled loops7would have a different scope. The solution would be a second syntax tree8that stored the scoping rules.9"""10import typing as t1112from . import nodes13from .visitor import NodeTransformer1415if t.TYPE_CHECKING:16    from .environment import Environment171819def optimize(node: nodes.Node, environment: "Environment") -> nodes.Node:20    """The context hint can be used to perform an static optimization21    based on the context given."""22    optimizer = Optimizer(environment)23    return t.cast(nodes.Node, optimizer.visit(node))242526class Optimizer(NodeTransformer):27    def __init__(self, environment: "t.Optional[Environment]") -> None:28        self.environment = environment2930    def generic_visit(31        self, node: nodes.Node, *args: t.Any, **kwargs: t.Any32    ) -> nodes.Node:33        node = super().generic_visit(node, *args, **kwargs)3435        # Do constant folding. Some other nodes besides Expr have36        # as_const, but folding them causes errors later on.37        if isinstance(node, nodes.Expr):38            try:39                return nodes.Const.from_untrusted(40                    node.as_const(args[0] if args else None),41                    lineno=node.lineno,42                    environment=self.environment,43                )44            except nodes.Impossible:45                pass4647        return node