optimise dict(a=1,b=2,...) into {'a':1, 'b':2, ...}, also works for Py3 keyword ident...
authorStefan Behnel <scoder@users.berlios.de>
Fri, 28 Nov 2008 12:39:56 +0000 (13:39 +0100)
committerStefan Behnel <scoder@users.berlios.de>
Fri, 28 Nov 2008 12:39:56 +0000 (13:39 +0100)
Cython/Compiler/Main.py
Cython/Compiler/Optimize.py

index eeedfdcebb755c0ae1f2e427778aa41eb3f1d755..db2293c1367033423b34467d6b51a56f26213a8e 100644 (file)
@@ -83,7 +83,7 @@ class Context:
         from ParseTreeTransforms import AlignFunctionDefinitions
         from AutoDocTransforms import EmbedSignature
         from Optimize import FlattenInListTransform, SwitchTransform, DictIterTransform
-        from Optimize import FinalOptimizePhase
+        from Optimize import FlattenBuiltinTypeCreation, FinalOptimizePhase
         from Buffer import IntroduceBufferAuxiliaryVars
         from ModuleNode import check_c_declarations
 
@@ -114,6 +114,7 @@ class Context:
             IntroduceBufferAuxiliaryVars(self),
             _check_c_declarations,
             AnalyseExpressionsTransform(self),
+            FlattenBuiltinTypeCreation(),
             DictIterTransform(),
             SwitchTransform(),
             FinalOptimizePhase(self),
index c47a1989bddf1bbb8c960b71b2366b2baa80b896..a9021662bb1710d104299cb42b99b69f640c2539 100644 (file)
@@ -340,6 +340,43 @@ class FlattenInListTransform(Visitor.VisitorTransform):
         return node
 
 
+class FlattenBuiltinTypeCreation(Visitor.VisitorTransform):
+    """Optimise some common instantiation patterns for builtin types.
+    """
+    def visit_GeneralCallNode(self, node):
+        """Replace dict(a=b,c=d,...) by the underlying keyword dict
+        construction which is done anyway.
+        """
+        self.visitchildren(node)
+        if not node.function.type.is_builtin_type:
+            return node
+        if node.function.name != 'dict':
+            return node
+        if not isinstance(node.positional_args, ExprNodes.TupleNode):
+            return node
+        if len(node.positional_args.args) > 0:
+            return node
+        if not isinstance(node.keyword_args, ExprNodes.DictNode):
+            return node
+        if node.starstar_arg:
+            # we could optimise this by updating the kw dict instead
+            return node
+        return node.keyword_args
+
+    def visit_PyTypeTestNode(self, node):
+        """Flatten redundant type checks after tree changes.
+        """
+        old_arg = node.arg
+        self.visitchildren(node)
+        if old_arg is node.arg or node.arg.type != node.type:
+            return node
+        return node.arg
+
+    def visit_Node(self, node):
+        self.visitchildren(node)
+        return node
+
+
 class FinalOptimizePhase(Visitor.CythonTransform):
     """
     This visitor handles several commuting optimizations, and is run