Commit 72020fc3 authored by Stefan Behnel's avatar Stefan Behnel

fold 'x in [a,b,c]' into 'x in (a,b,c)' as tuples are more efficient than lists

parent 8445e550
...@@ -5496,6 +5496,9 @@ class ListNode(SequenceNode): ...@@ -5496,6 +5496,9 @@ class ListNode(SequenceNode):
error(self.pos, "Cannot coerce list to type '%s'" % dst_type) error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
return self return self
def as_tuple(self):
return TupleNode(self.pos, args=self.args, mult_factor=self.mult_factor)
def release_temp_result(self, env): def release_temp_result(self, env):
if self.type.is_array: if self.type.is_array:
# To be valid C++, we must allocate the memory on the stack # To be valid C++, we must allocate the memory on the stack
......
...@@ -3109,11 +3109,14 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations): ...@@ -3109,11 +3109,14 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations):
def visit_PrimaryCmpNode(self, node): def visit_PrimaryCmpNode(self, node):
self._calculate_const(node) self._calculate_const(node)
if node.constant_result is ExprNodes.not_a_constant: if node.constant_result is not ExprNodes.not_a_constant:
return node bool_result = bool(node.constant_result)
bool_result = bool(node.constant_result) return ExprNodes.BoolNode(node.pos, value=bool_result,
return ExprNodes.BoolNode(node.pos, value=bool_result, constant_result=bool_result)
constant_result=bool_result) if node.operator in ('in', 'not_in') and not node.cascade:
if isinstance(node.operand2, ExprNodes.ListNode):
node.operand2 = node.operand2.as_tuple()
return node
def visit_CondExprNode(self, node): def visit_CondExprNode(self, node):
self._calculate_const(node) self._calculate_const(node)
...@@ -3153,8 +3156,7 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations): ...@@ -3153,8 +3156,7 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations):
# iterating over a list literal? => tuples are more efficient # iterating over a list literal? => tuples are more efficient
sequence = node.iterator.sequence sequence = node.iterator.sequence
if isinstance(sequence, ExprNodes.ListNode): if isinstance(sequence, ExprNodes.ListNode):
node.iterator.sequence = ExprNodes.TupleNode( node.iterator.sequence = sequence.as_tuple()
sequence.pos, args=sequence.args, mult_factor=sequence.mult_factor)
return node return node
def _find_genexpr_yield_stat(self, node): def _find_genexpr_yield_stat(self, node):
......
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