From: Stefan Behnel Date: Fri, 28 Nov 2008 12:39:56 +0000 (+0100) Subject: optimise dict(a=1,b=2,...) into {'a':1, 'b':2, ...}, also works for Py3 keyword ident... X-Git-Tag: 0.11-beta~188 X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=63968d47bfd2c8ffdc7a1f7935a57403500ff642;p=cython.git optimise dict(a=1,b=2,...) into {'a':1, 'b':2, ...}, also works for Py3 keyword identifiers as run/dict.pyx shows --- 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