From 63968d47bfd2c8ffdc7a1f7935a57403500ff642 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Fri, 28 Nov 2008 13:39:56 +0100 Subject: [PATCH] optimise dict(a=1,b=2,...) into {'a':1, 'b':2, ...}, also works for Py3 keyword identifiers as run/dict.pyx shows --- Cython/Compiler/Main.py | 3 ++- Cython/Compiler/Optimize.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Cython/Compiler/Main.py b/Cython/Compiler/Main.py index eeedfdce..db2293c1 100644 --- a/Cython/Compiler/Main.py +++ b/Cython/Compiler/Main.py @@ -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), diff --git a/Cython/Compiler/Optimize.py b/Cython/Compiler/Optimize.py index c47a1989..a9021662 100644 --- a/Cython/Compiler/Optimize.py +++ b/Cython/Compiler/Optimize.py @@ -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 -- 2.26.2