optimizer.py
This file
Path
src/jinja2/optimizer.py
41 lines · 1.4 KiB · Python
Last changed by
Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
History of this fileTake it
Merge pull request #1133 from pallets/revert-renameDavid Lordbefore adoption15337f7
lines 1–41why, one step back1# -*- coding: utf-8 -*-2"""The optimizer tries to constant fold expressions and modify the AST3in place so that it should be faster to evaluate.45Because the AST does not contain all the scoping information and the6compiler has to find that out, we cannot do all the optimizations we7want. For example, loop unrolling doesn't work because unrolled loops8would have a different scope. The solution would be a second syntax tree9that stored the scoping rules.10"""11from . import nodes12from .visitor import NodeTransformer131415def optimize(node, environment):16 """The context hint can be used to perform an static optimization17 based on the context given."""18 optimizer = Optimizer(environment)19 return optimizer.visit(node)202122class Optimizer(NodeTransformer):23 def __init__(self, environment):24 self.environment = environment2526 def generic_visit(self, node, *args, **kwargs):27 node = super(Optimizer, self).generic_visit(node, *args, **kwargs)2829 # Do constant folding. Some other nodes besides Expr have30 # as_const, but folding them causes errors later on.31 if isinstance(node, nodes.Expr):32 try:33 return nodes.Const.from_untrusted(34 node.as_const(args[0] if args else None),35 lineno=node.lineno,36 environment=self.environment,37 )38 except nodes.Impossible:39 pass4041 return node