Commit 63968d47 authored by Stefan Behnel's avatar Stefan Behnel

optimise dict(a=1,b=2,...) into {'a':1, 'b':2, ...}, also works for Py3...

optimise dict(a=1,b=2,...) into {'a':1, 'b':2, ...}, also works for Py3 keyword identifiers as run/dict.pyx shows
parent 4ff586a3
......@@ -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),
......
......@@ -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
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment