]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
apply optimizer to all Expr nodes 1111/head
authorDavid Lord <davidism@gmail.com>
Tue, 3 Dec 2019 16:57:41 +0000 (08:57 -0800)
committerDavid Lord <davidism@gmail.com>
Tue, 3 Dec 2019 17:08:37 +0000 (09:08 -0800)
CHANGES.rst
jinja2/optimizer.py

index f5f2e7cf18b3913301627d16455daa143e12aeca..6df6d24282c188041ac230c5d3fdfa82c90e9cde 100644 (file)
@@ -88,6 +88,8 @@ Unreleased
 -   Add a ``DerivedContextReference`` node that can be used by
     extensions to get the current context and local variables such as
     ``loop``. :issue:`860`
+-   Constant folding during compilation is applied to some node types
+    that were previously overlooked. :issue:`733`
 
 
 Version 2.10.3
index 65ab3ceb71f6130e4229a8272c495a91cdea352c..7065424879d53fa5e417e15c6488e3464dcf6a8b 100644 (file)
@@ -28,22 +28,22 @@ def optimize(node, environment):
 
 
 class Optimizer(NodeTransformer):
-
     def __init__(self, environment):
         self.environment = environment
 
-    def fold(self, node, eval_ctx=None):
-        """Do constant folding."""
-        node = self.generic_visit(node)
-        try:
-            return nodes.Const.from_untrusted(node.as_const(eval_ctx),
-                                              lineno=node.lineno,
-                                              environment=self.environment)
-        except nodes.Impossible:
-            return node
-
-    visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \
-    visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \
-    visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \
-    visit_Filter = visit_Test = visit_CondExpr = fold
-    del fold
+    def generic_visit(self, node, *args, **kwargs):
+        node = super(Optimizer, self).generic_visit(node, *args, **kwargs)
+
+        # Do constant folding. Some other nodes besides Expr have
+        # as_const, but folding them causes errors later on.
+        if isinstance(node, nodes.Expr):
+            try:
+                return nodes.Const.from_untrusted(
+                    node.as_const(args[0] if args else None),
+                    lineno=node.lineno,
+                    environment=self.environment,
+                )
+            except nodes.Impossible:
+                pass
+
+        return node