Skip to content
Myr

optimizer.py

This file

Path

src/jinja2/optimizer.py

48 lines · 1.6 KiB · Python

Last changed by

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

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"""1011import typing as t1213from . import nodes14from .visitor import NodeTransformer1516if t.TYPE_CHECKING:17    from .environment import Environment181920def optimize(node: nodes.Node, environment: "Environment") -> nodes.Node:21    """The context hint can be used to perform an static optimization22    based on the context given."""23    optimizer = Optimizer(environment)24    return t.cast(nodes.Node, optimizer.visit(node))252627class Optimizer(NodeTransformer):28    def __init__(self, environment: "Environment | None") -> None:29        self.environment = environment3031    def generic_visit(32        self, node: nodes.Node, *args: t.Any, **kwargs: t.Any33    ) -> nodes.Node:34        node = super().generic_visit(node, *args, **kwargs)3536        # Do constant folding. Some other nodes besides Expr have37        # as_const, but folding them causes errors later on.38        if isinstance(node, nodes.Expr):39            try:40                return nodes.Const.from_untrusted(41                    node.as_const(args[0] if args else None),42                    lineno=node.lineno,43                    environment=self.environment,44                )45            except nodes.Impossible:46                pass4748        return node