optimizer.py
This file
Path
jinja2/optimizer.py
68 lines · 2.2 KiB · Python
Last changed by
It's a new yearArmin Ronacherbefore adoption55494e4
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 jinja2.optimizer4 ~~~~~~~~~~~~~~~~56 The jinja optimizer is currently trying to constant fold a few expressions7 and modify the AST in place so that it should be easier to evaluate it.89 Because the AST does not contain all the scoping information and the10 compiler has to find that out, we cannot do all the optimizations we11 want. For example loop unrolling doesn't work because unrolled loops would12 have a different scoping.1314 The solution would be a second syntax tree that has the scoping rules stored.1516 :copyright: (c) 2010 by the Jinja Team.17 :license: BSD.18"""19from jinja2 import nodes20from jinja2.visitor import NodeTransformer212223def optimize(node, environment):24 """The context hint can be used to perform an static optimization25 based on the context given."""26 optimizer = Optimizer(environment)27 return optimizer.visit(node)282930class Optimizer(NodeTransformer):3132 def __init__(self, environment):33 self.environment = environment3435 def visit_If(self, node):36 """Eliminate dead code."""37 # do not optimize ifs that have a block inside so that it doesn't38 # break super().39 if node.find(nodes.Block) is not None:40 return self.generic_visit(node)41 try:42 val = self.visit(node.test).as_const()43 except nodes.Impossible:44 return self.generic_visit(node)45 if val:46 body = node.body47 else:48 body = node.else_49 result = []50 for node in body:51 result.extend(self.visit_list(node))52 return result5354 def fold(self, node):55 """Do constant folding."""56 node = self.generic_visit(node)57 try:58 return nodes.Const.from_untrusted(node.as_const(),59 lineno=node.lineno,60 environment=self.environment)61 except nodes.Impossible:62 return node6364 visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \65 visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \66 visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \67 visit_Filter = visit_Test = visit_CondExpr = fold68 del fold