2 # Pyrex - Parse tree nodes for expressions
7 from Errors import error, warning, warn_once, InternalError
8 from Errors import hold_errors, release_errors, held_errors, report_error
9 from Code import UtilityCode
13 from Nodes import Node
15 from PyrexTypes import py_object_type, c_long_type, typecast, error_type, \
17 from Builtin import list_type, tuple_type, set_type, dict_type, \
18 unicode_type, str_type, bytes_type, type_type
22 from Cython import Utils
23 from Annotate import AnnotationItem
24 from Cython import Utils
26 from Cython.Debugging import print_call_chain
27 from DebugFlags import debug_disposal_code, debug_temp_alloc, \
33 from sets import Set as set
35 class NotConstant(object):
37 return "<NOT CONSTANT>"
39 not_a_constant = NotConstant()
40 constant_value_not_set = object()
42 # error messages when coercing from key[0] to key[1]
43 find_coercion_error = {
44 # string related errors
45 (Builtin.unicode_type, Builtin.bytes_type) : "Cannot convert Unicode string to 'bytes' implicitly, encoding required.",
46 (Builtin.unicode_type, Builtin.str_type) : "Cannot convert Unicode string to 'str' implicitly. This is not portable and requires explicit encoding.",
47 (Builtin.unicode_type, PyrexTypes.c_char_ptr_type) : "Unicode objects do not support coercion to C types.",
48 (Builtin.bytes_type, Builtin.unicode_type) : "Cannot convert 'bytes' object to unicode implicitly, decoding required",
49 (Builtin.bytes_type, Builtin.str_type) : "Cannot convert 'bytes' object to str implicitly. This is not portable to Py3.",
50 (Builtin.str_type, Builtin.unicode_type) : "str objects do not support coercion to unicode, use a unicode string literal instead (u'')",
51 (Builtin.str_type, Builtin.bytes_type) : "Cannot convert 'str' to 'bytes' implicitly. This is not portable.",
52 (Builtin.str_type, PyrexTypes.c_char_ptr_type) : "'str' objects do not support coercion to C types (use 'bytes'?).",
53 (PyrexTypes.c_char_ptr_type, Builtin.unicode_type) : "Cannot convert 'char*' to unicode implicitly, decoding required",
54 (PyrexTypes.c_uchar_ptr_type, Builtin.unicode_type) : "Cannot convert 'char*' to unicode implicitly, decoding required",
59 # subexprs [string] Class var holding names of subexpr node attrs
60 # type PyrexType Type of the result
61 # result_code string Code fragment
62 # result_ctype string C type of result_code if different from type
63 # is_temp boolean Result is in a temporary variable
64 # is_sequence_constructor
65 # boolean Is a list or tuple constructor expression
66 # is_starred boolean Is a starred expression (e.g. '*a')
68 # [ExprNode or [ExprNode or None] or None]
69 # Cached result of subexpr_nodes()
70 # use_managed_ref boolean use ref-counted temps/assignments/etc.
75 old_temp = None # error checker for multiple frees etc.
76 use_managed_ref = True # can be set by optimisation transforms
78 # The Analyse Expressions phase for expressions is split
79 # into two sub-phases:
82 # Determines the result type of the expression based
83 # on the types of its sub-expressions, and inserts
84 # coercion nodes into the expression tree where needed.
85 # Marks nodes which will need to have temporary variables
89 # Allocates temporary variables where needed, and fills
90 # in the result_code field of each node.
92 # ExprNode provides some convenience routines which
93 # perform both of the above phases. These should only
94 # be called from statement nodes, and only when no
95 # coercion nodes need to be added around the expression
96 # being analysed. In that case, the above two phases
97 # should be invoked separately.
99 # Framework code in ExprNode provides much of the common
100 # processing for the various phases. It makes use of the
101 # 'subexprs' class attribute of ExprNodes, which should
102 # contain a list of the names of attributes which can
103 # hold sub-nodes or sequences of sub-nodes.
105 # The framework makes use of a number of abstract methods.
106 # Their responsibilities are as follows.
108 # Declaration Analysis phase
110 # analyse_target_declaration
111 # Called during the Analyse Declarations phase to analyse
112 # the LHS of an assignment or argument of a del statement.
113 # Nodes which cannot be the LHS of an assignment need not
116 # Expression Analysis phase
119 # - Call analyse_types on all sub-expressions.
120 # - Check operand types, and wrap coercion nodes around
121 # sub-expressions where needed.
122 # - Set the type of this node.
123 # - If a temporary variable will be required for the
124 # result, set the is_temp flag of this node.
126 # analyse_target_types
127 # Called during the Analyse Types phase to analyse
128 # the LHS of an assignment or argument of a del
129 # statement. Similar responsibilities to analyse_types.
132 # Called by the default implementation of allocate_target_temps.
133 # Should return a C lvalue for assigning to the node. The default
134 # implementation calls calculate_result_code.
137 # - Check that this node and its subnodes form a
138 # legal constant expression. If so, do nothing,
139 # otherwise call not_const.
141 # The default implementation of check_const
142 # assumes that the expression is not constant.
145 # - Same as check_const, except check that the
146 # expression is a C lvalue whose address is
147 # constant. Otherwise, call addr_not_const.
149 # The default implementation of calc_const_addr
150 # assumes that the expression is not a constant
153 # Code Generation phase
155 # generate_evaluation_code
156 # - Call generate_evaluation_code for sub-expressions.
157 # - Perform the functions of generate_result_code
159 # - If result is temporary, call generate_disposal_code
160 # on all sub-expressions.
162 # A default implementation of generate_evaluation_code
163 # is provided which uses the following abstract methods:
165 # generate_result_code
166 # - Generate any C statements necessary to calculate
167 # the result of this node from the results of its
170 # calculate_result_code
171 # - Should return a C code fragment evaluating to the
172 # result. This is only called when the result is not
175 # generate_assignment_code
176 # Called on the LHS of an assignment.
177 # - Call generate_evaluation_code for sub-expressions.
178 # - Generate code to perform the assignment.
179 # - If the assignment absorbed a reference, call
180 # generate_post_assignment_code on the RHS,
181 # otherwise call generate_disposal_code on it.
183 # generate_deletion_code
184 # Called on an argument of a del statement.
185 # - Call generate_evaluation_code for sub-expressions.
186 # - Generate code to perform the deletion.
187 # - Call generate_disposal_code on all sub-expressions.
191 is_sequence_constructor = 0
194 saved_subexpr_nodes = None
199 constant_result = constant_value_not_set
202 _get_child_attrs = operator.attrgetter('subexprs')
203 except AttributeError:
205 def _get_child_attrs(self):
207 child_attrs = property(fget=_get_child_attrs)
209 def not_implemented(self, method_name):
210 print_call_chain(method_name, "not implemented") ###
212 "%s.%s not implemented" %
213 (self.__class__.__name__, method_name))
218 def is_ephemeral(self):
219 # An ephemeral node is one whose result is in
220 # a Python temporary and we suspect there are no
221 # other references to it. Certain operations are
222 # disallowed on such values, since they are
223 # likely to result in a dangling pointer.
224 return self.type.is_pyobject and self.is_temp
226 def subexpr_nodes(self):
227 # Extract a list of subexpression nodes based
228 # on the contents of the subexprs class attribute.
230 for name in self.subexprs:
231 item = getattr(self, name)
233 if type(item) is list:
241 return self.temp_code
243 return self.calculate_result_code()
245 def result_as(self, type = None):
246 # Return the result code cast to the specified C type.
247 return typecast(type, self.ctype(), self.result())
250 # Return the result code cast to PyObject *.
251 return self.result_as(py_object_type)
254 # Return the native C type of the result (i.e. the
255 # C type of the result_code expression).
256 return self.result_ctype or self.type
258 def get_constant_c_result_code(self):
259 # Return the constant value of this node as a result code
260 # string, or None if the node is not constant. This method
261 # can be called when the constant result code is required
262 # before the code generation phase.
264 # The return value is a string that can represent a simple C
265 # value, a constant C name or a constant C expression. If the
266 # node type depends on Python code, this must return None.
269 def calculate_constant_result(self):
270 # Calculate the constant compile time result value of this
271 # expression and store it in ``self.constant_result``. Does
272 # nothing by default, thus leaving ``self.constant_result``
273 # unknown. If valid, the result can be an arbitrary Python
276 # This must only be called when it is assured that all
277 # sub-expressions have a valid constant_result value. The
278 # ConstantFolding transform will do this.
281 def has_constant_result(self):
282 return self.constant_result is not constant_value_not_set and \
283 self.constant_result is not not_a_constant
285 def compile_time_value(self, denv):
286 # Return value of compile-time expression, or report error.
287 error(self.pos, "Invalid compile-time expression")
289 def compile_time_value_error(self, e):
290 error(self.pos, "Error in compile-time expression: %s: %s" % (
291 e.__class__.__name__, e))
293 # ------------- Declaration Analysis ----------------
295 def analyse_target_declaration(self, env):
296 error(self.pos, "Cannot assign to or delete this")
298 # ------------- Expression Analysis ----------------
300 def analyse_const_expression(self, env):
301 # Called during the analyse_declarations phase of a
302 # constant expression. Analyses the expression's type,
303 # checks whether it is a legal const expression,
304 # and determines its value.
305 self.analyse_types(env)
306 return self.check_const()
308 def analyse_expressions(self, env):
309 # Convenience routine performing both the Type
310 # Analysis and Temp Allocation phases for a whole
312 self.analyse_types(env)
314 def analyse_target_expression(self, env, rhs):
315 # Convenience routine performing both the Type
316 # Analysis and Temp Allocation phases for the LHS of
318 self.analyse_target_types(env)
320 def analyse_boolean_expression(self, env):
321 # Analyse expression and coerce to a boolean.
322 self.analyse_types(env)
323 bool = self.coerce_to_boolean(env)
326 def analyse_temp_boolean_expression(self, env):
327 # Analyse boolean expression and coerce result into
328 # a temporary. This is used when a branch is to be
329 # performed on the result and we won't have an
330 # opportunity to ensure disposal code is executed
331 # afterwards. By forcing the result into a temporary,
332 # we ensure that all disposal has been done by the
333 # time we get the result.
334 self.analyse_types(env)
335 return self.coerce_to_boolean(env).coerce_to_simple(env)
337 # --------------- Type Inference -----------------
339 def type_dependencies(self, env):
340 # Returns the list of entries whose types must be determined
341 # before the type of self can be infered.
342 if hasattr(self, 'type') and self.type is not None:
344 return sum([node.type_dependencies(env) for node in self.subexpr_nodes()], ())
346 def infer_type(self, env):
347 # Attempt to deduce the type of self.
348 # Differs from analyse_types as it avoids unnecessary
349 # analysis of subexpressions, but can assume everything
350 # in self.type_dependencies() has been resolved.
351 if hasattr(self, 'type') and self.type is not None:
353 elif hasattr(self, 'entry') and self.entry is not None:
354 return self.entry.type
356 self.not_implemented("infer_type")
358 # --------------- Type Analysis ------------------
360 def analyse_as_module(self, env):
361 # If this node can be interpreted as a reference to a
362 # cimported module, return its scope, else None.
365 def analyse_as_type(self, env):
366 # If this node can be interpreted as a reference to a
367 # type, return that type, else None.
370 def analyse_as_extension_type(self, env):
371 # If this node can be interpreted as a reference to an
372 # extension type, return its type, else None.
375 def analyse_types(self, env):
376 self.not_implemented("analyse_types")
378 def analyse_target_types(self, env):
379 self.analyse_types(env)
381 def nogil_check(self, env):
382 # By default, any expression based on Python objects is
383 # prevented in nogil environments. Subtypes must override
384 # this if they can work without the GIL.
385 if self.type.is_pyobject:
388 def gil_assignment_check(self, env):
389 if env.nogil and self.type.is_pyobject:
390 error(self.pos, "Assignment of Python object not allowed without gil")
392 def check_const(self):
397 error(self.pos, "Not allowed in a constant expression")
399 def check_const_addr(self):
400 self.addr_not_const()
403 def addr_not_const(self):
404 error(self.pos, "Address is not constant")
406 # ----------------- Result Allocation -----------------
408 def result_in_temp(self):
409 # Return true if result is in a temporary owned by
410 # this node or one of its subexpressions. Overridden
411 # by certain nodes which can share the result of
415 def target_code(self):
416 # Return code fragment for use as LHS of a C assignment.
417 return self.calculate_result_code()
419 def calculate_result_code(self):
420 self.not_implemented("calculate_result_code")
422 # def release_target_temp(self, env):
423 # # Release temporaries used by LHS of an assignment.
424 # self.release_subexpr_temps(env)
426 def allocate_temp_result(self, code):
428 raise RuntimeError("Temp allocated multiple times in %r: %r" % (self.__class__.__name__, self.pos))
432 type = PyrexTypes.py_object_type
433 self.temp_code = code.funcstate.allocate_temp(
434 type, manage_ref=self.use_managed_ref)
436 self.temp_code = None
438 def release_temp_result(self, code):
439 if not self.temp_code:
441 raise RuntimeError("temp %s released multiple times in %s" % (
442 self.old_temp, self.__class__.__name__))
444 raise RuntimeError("no temp, but release requested in %s" % (
445 self.__class__.__name__))
446 code.funcstate.release_temp(self.temp_code)
447 self.old_temp = self.temp_code
448 self.temp_code = None
450 # ---------------- Code Generation -----------------
452 def make_owned_reference(self, code):
453 # If result is a pyobject, make sure we own
455 if self.type.is_pyobject and not self.result_in_temp():
456 code.put_incref(self.result(), self.ctype())
458 def generate_evaluation_code(self, code):
459 code.mark_pos(self.pos)
461 # Generate code to evaluate this node and
462 # its sub-expressions, and dispose of any
463 # temporary results of its sub-expressions.
464 self.generate_subexpr_evaluation_code(code)
467 self.allocate_temp_result(code)
469 self.generate_result_code(code)
471 # If we are temp we do not need to wait until this node is disposed
472 # before disposing children.
473 self.generate_subexpr_disposal_code(code)
474 self.free_subexpr_temps(code)
476 def generate_subexpr_evaluation_code(self, code):
477 for node in self.subexpr_nodes():
478 node.generate_evaluation_code(code)
480 def generate_result_code(self, code):
481 self.not_implemented("generate_result_code")
483 def generate_disposal_code(self, code):
485 if self.type.is_pyobject:
486 code.put_decref_clear(self.result(), self.ctype())
488 # Already done if self.is_temp
489 self.generate_subexpr_disposal_code(code)
491 def generate_subexpr_disposal_code(self, code):
492 # Generate code to dispose of temporary results
493 # of all sub-expressions.
494 for node in self.subexpr_nodes():
495 node.generate_disposal_code(code)
497 def generate_post_assignment_code(self, code):
499 if self.type.is_pyobject:
500 code.putln("%s = 0;" % self.result())
502 self.generate_subexpr_disposal_code(code)
504 def generate_assignment_code(self, rhs, code):
505 # Stub method for nodes which are not legal as
506 # the LHS of an assignment. An error will have
507 # been reported earlier.
510 def generate_deletion_code(self, code):
511 # Stub method for nodes that are not legal as
512 # the argument of a del statement. An error
513 # will have been reported earlier.
516 def free_temps(self, code):
518 if not self.type.is_void:
519 self.release_temp_result(code)
521 self.free_subexpr_temps(code)
523 def free_subexpr_temps(self, code):
524 for sub in self.subexpr_nodes():
527 def generate_function_definitions(self, env, code):
530 # ---------------- Annotation ---------------------
532 def annotate(self, code):
533 for node in self.subexpr_nodes():
536 # ----------------- Coercion ----------------------
538 def coerce_to(self, dst_type, env):
539 # Coerce the result so that it can be assigned to
540 # something of type dst_type. If processing is necessary,
541 # wraps this node in a coercion node and returns that.
542 # Otherwise, returns this node unchanged.
544 # This method is called during the analyse_expressions
545 # phase of the src_node's processing.
547 # Note that subclasses that override this (especially
548 # ConstNodes) must not (re-)set their own .type attribute
549 # here. Since expression nodes may turn up in different
550 # places in the tree (e.g. inside of CloneNodes in cascaded
551 # assignments), this method must return a new node instance
552 # if it changes the type.
556 src_is_py_type = src_type.is_pyobject
557 dst_is_py_type = dst_type.is_pyobject
559 if self.check_for_coercion_error(dst_type):
562 if dst_type.is_reference:
563 dst_type = dst_type.ref_base_type
565 if dst_type.is_pyobject:
566 if not src.type.is_pyobject:
567 if dst_type is bytes_type and src.type.is_int:
568 src = CoerceIntToBytesNode(src, env)
570 src = CoerceToPyTypeNode(src, env)
571 if not src.type.subtype_of(dst_type):
572 if not isinstance(src, NoneNode):
573 src = PyTypeTestNode(src, dst_type, env)
574 elif src.type.is_pyobject:
575 src = CoerceFromPyTypeNode(dst_type, src, env)
576 elif (dst_type.is_complex
577 and src_type != dst_type
578 and dst_type.assignable_from(src_type)):
579 src = CoerceToComplexNode(src, dst_type, env)
580 else: # neither src nor dst are py types
581 # Added the string comparison, since for c types that
582 # is enough, but Cython gets confused when the types are
583 # in different pxi files.
584 if not (str(src.type) == str(dst_type) or dst_type.assignable_from(src_type)):
585 self.fail_assignment(dst_type)
588 def fail_assignment(self, dst_type):
589 error(self.pos, "Cannot assign type '%s' to '%s'" % (self.type, dst_type))
591 def check_for_coercion_error(self, dst_type, fail=False, default=None):
592 if fail and not default:
593 default = "Cannot assign type '%(FROM)s' to '%(TO)s'"
594 message = find_coercion_error((self.type, dst_type), default)
595 if message is not None:
596 error(self.pos, message % {'FROM': self.type, 'TO': dst_type})
599 self.fail_assignment(dst_type)
603 def coerce_to_pyobject(self, env):
604 return self.coerce_to(PyrexTypes.py_object_type, env)
606 def coerce_to_boolean(self, env):
607 # Coerce result to something acceptable as
610 # if it's constant, calculate the result now
611 if self.has_constant_result():
612 bool_value = bool(self.constant_result)
613 return BoolNode(self.pos, value=bool_value,
614 constant_result=bool_value)
617 if type.is_pyobject or type.is_ptr or type.is_float:
618 return CoerceToBooleanNode(self, env)
620 if not (type.is_int or type.is_enum or type.is_error):
622 "Type '%s' not acceptable as a boolean" % type)
625 def coerce_to_integer(self, env):
626 # If not already some C integer type, coerce to longint.
630 return self.coerce_to(PyrexTypes.c_long_type, env)
632 def coerce_to_temp(self, env):
633 # Ensure that the result is in a temporary.
634 if self.result_in_temp():
637 return CoerceToTempNode(self, env)
639 def coerce_to_simple(self, env):
640 # Ensure that the result is simple (see is_simple).
644 return self.coerce_to_temp(env)
647 # A node is simple if its result is something that can
648 # be referred to without performing any operations, e.g.
649 # a constant, local var, C global var, struct member
650 # reference, or temporary.
651 return self.result_in_temp()
653 def may_be_none(self):
654 if not self.type.is_pyobject:
656 if self.constant_result not in (not_a_constant, constant_value_not_set):
657 return self.constant_result is not None
660 def as_cython_attribute(self):
663 def as_none_safe_node(self, message, error="PyExc_TypeError"):
664 # Wraps the node in a NoneCheckNode if it is not known to be
665 # not-None (e.g. because it is a Python literal).
666 if self.may_be_none():
667 return NoneCheckNode(self, error, message)
672 class AtomicExprNode(ExprNode):
673 # Abstract base class for expression nodes which have
674 # no sub-expressions.
678 # Override to optimize -- we know we have no children
679 def generate_subexpr_evaluation_code(self, code):
681 def generate_subexpr_disposal_code(self, code):
684 class PyConstNode(AtomicExprNode):
685 # Abstract base class for constant Python values.
688 type = py_object_type
693 def may_be_none(self):
696 def analyse_types(self, env):
699 def calculate_result_code(self):
702 def generate_result_code(self, code):
706 class NoneNode(PyConstNode):
707 # The constant value None
711 constant_result = None
715 def compile_time_value(self, denv):
718 def may_be_none(self):
722 class EllipsisNode(PyConstNode):
723 # '...' in a subscript list.
725 value = "Py_Ellipsis"
727 constant_result = Ellipsis
729 def compile_time_value(self, denv):
733 class ConstNode(AtomicExprNode):
734 # Abstract base type for literal constant nodes.
736 # value string C code fragment
744 def may_be_none(self):
747 def analyse_types(self, env):
748 pass # Types are held in class variables
750 def check_const(self):
753 def get_constant_c_result_code(self):
754 return self.calculate_result_code()
756 def calculate_result_code(self):
757 return str(self.value)
759 def generate_result_code(self, code):
763 class BoolNode(ConstNode):
764 type = PyrexTypes.c_bint_type
765 # The constant value True or False
767 def calculate_constant_result(self):
768 self.constant_result = self.value
770 def compile_time_value(self, denv):
773 def calculate_result_code(self):
774 return str(int(self.value))
777 class NullNode(ConstNode):
778 type = PyrexTypes.c_null_ptr_type
782 def get_constant_c_result_code(self):
786 class CharNode(ConstNode):
787 type = PyrexTypes.c_char_type
789 def calculate_constant_result(self):
790 self.constant_result = ord(self.value)
792 def compile_time_value(self, denv):
793 return ord(self.value)
795 def calculate_result_code(self):
796 return "'%s'" % StringEncoding.escape_char(self.value)
799 class IntNode(ConstNode):
802 # longness "" or "L" or "LL"
803 # is_c_literal True/False/None creator considers this a C integer literal
807 is_c_literal = None # unknown
809 def __init__(self, pos, **kwds):
810 ExprNode.__init__(self, pos, **kwds)
811 if 'type' not in kwds:
812 self.type = self.find_suitable_type_for_value()
814 def find_suitable_type_for_value(self):
815 if self.constant_result is constant_value_not_set:
817 self.calculate_constant_result()
820 # we ignore 'is_c_literal = True' and instead map signed 32bit
821 # integers as C long values
822 if self.is_c_literal or \
823 self.constant_result in (constant_value_not_set, not_a_constant) or \
824 self.unsigned or self.longness == 'LL':
825 # clearly a C literal
826 rank = (self.longness == 'LL') and 2 or 1
827 suitable_type = PyrexTypes.modifiers_and_name_to_type[not self.unsigned, rank, "int"]
829 suitable_type = PyrexTypes.widest_numeric_type(suitable_type, self.type)
831 # C literal or Python literal - split at 32bit boundary
832 if self.constant_result >= -2**31 and self.constant_result < 2**31:
833 if self.type and self.type.is_int:
834 suitable_type = self.type
836 suitable_type = PyrexTypes.c_long_type
838 suitable_type = PyrexTypes.py_object_type
841 def coerce_to(self, dst_type, env):
842 if self.type is dst_type:
844 elif dst_type.is_float:
845 if self.constant_result is not not_a_constant:
846 float_value = float(self.constant_result)
847 return FloatNode(self.pos, value=repr(float_value), type=dst_type,
848 constant_result=float_value)
850 return FloatNode(self.pos, value=self.value, type=dst_type,
851 constant_result=not_a_constant)
852 if dst_type.is_numeric and not dst_type.is_complex:
853 node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
854 type = dst_type, is_c_literal = True,
855 unsigned=self.unsigned, longness=self.longness)
857 elif dst_type.is_pyobject:
858 node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
859 type = PyrexTypes.py_object_type, is_c_literal = False,
860 unsigned=self.unsigned, longness=self.longness)
862 # FIXME: not setting the type here to keep it working with
863 # complex numbers. Should they be special cased?
864 node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
865 unsigned=self.unsigned, longness=self.longness)
866 # We still need to perform normal coerce_to processing on the
867 # result, because we might be coercing to an extension type,
868 # in which case a type test node will be needed.
869 return ConstNode.coerce_to(node, dst_type, env)
871 def coerce_to_boolean(self, env):
873 self.pos, value=self.value,
874 type = PyrexTypes.c_bint_type,
875 unsigned=self.unsigned, longness=self.longness)
877 def generate_evaluation_code(self, code):
878 if self.type.is_pyobject:
879 # pre-allocate a Python version of the number
880 plain_integer_string = self.value_as_c_integer_string(plain_digits=True)
881 self.result_code = code.get_py_num(plain_integer_string, self.longness)
883 self.result_code = self.get_constant_c_result_code()
885 def get_constant_c_result_code(self):
886 return self.value_as_c_integer_string() + self.unsigned + self.longness
888 def value_as_c_integer_string(self, plain_digits=False):
890 if isinstance(value, basestring) and len(value) > 2:
891 # must convert C-incompatible Py3 oct/bin notations
894 value = int(value[2:], 8)
896 value = value[0] + value[2:] # '0o123' => '0123'
897 elif value[1] in 'bB':
898 value = int(value[2:], 2)
899 elif plain_digits and value[1] in 'xX':
900 value = int(value[2:], 16)
903 def calculate_result_code(self):
904 return self.result_code
906 def calculate_constant_result(self):
907 self.constant_result = Utils.str_to_number(self.value)
909 def compile_time_value(self, denv):
910 return Utils.str_to_number(self.value)
913 class FloatNode(ConstNode):
914 type = PyrexTypes.c_double_type
916 def calculate_constant_result(self):
917 self.constant_result = float(self.value)
919 def compile_time_value(self, denv):
920 return float(self.value)
922 def calculate_result_code(self):
924 assert isinstance(strval, (str, unicode))
925 cmpval = repr(float(strval))
927 return "(Py_HUGE_VAL * 0)"
928 elif cmpval == 'inf':
930 elif cmpval == '-inf':
931 return "(-Py_HUGE_VAL)"
936 class BytesNode(ConstNode):
937 # A char* or bytes literal
941 type = PyrexTypes.c_char_ptr_type
943 def compile_time_value(self, denv):
946 def analyse_as_type(self, env):
947 type = PyrexTypes.parse_basic_type(self.value)
950 from TreeFragment import TreeFragment
951 pos = (self.pos[0], self.pos[1], self.pos[2]-7)
952 declaration = TreeFragment(u"sizeof(%s)" % self.value, name=pos[0].filename, initial_pos=pos)
953 sizeof_node = declaration.root.stats[0].expr
954 sizeof_node.analyse_types(env)
955 if isinstance(sizeof_node, SizeofTypeNode):
956 return sizeof_node.arg_type
958 def can_coerce_to_char_literal(self):
959 return len(self.value) == 1
961 def coerce_to_boolean(self, env):
962 # This is special because we start off as a C char*. Testing
963 # that for truth directly would yield the wrong result.
964 return BoolNode(self.pos, value=bool(self.value))
966 def coerce_to(self, dst_type, env):
968 if not self.can_coerce_to_char_literal():
969 error(self.pos, "Only single-character string literals can be coerced into ints.")
971 if dst_type is PyrexTypes.c_py_unicode_type:
972 error(self.pos, "Bytes literals cannot coerce to Py_UNICODE, use a unicode literal instead.")
974 return CharNode(self.pos, value=self.value)
976 node = BytesNode(self.pos, value=self.value)
977 if dst_type == PyrexTypes.c_char_ptr_type:
978 node.type = PyrexTypes.c_char_ptr_type
980 elif dst_type == PyrexTypes.c_uchar_ptr_type:
981 node.type = PyrexTypes.c_char_ptr_type
982 return CastNode(node, PyrexTypes.c_uchar_ptr_type)
984 if not self.type.is_pyobject:
985 if dst_type in (py_object_type, Builtin.bytes_type):
986 node.type = Builtin.bytes_type
987 elif dst_type.is_pyobject:
988 self.fail_assignment(dst_type)
990 elif dst_type.is_pyobject and dst_type is not py_object_type:
991 self.check_for_coercion_error(dst_type, fail=True)
994 # We still need to perform normal coerce_to processing on the
995 # result, because we might be coercing to an extension type,
996 # in which case a type test node will be needed.
997 return ConstNode.coerce_to(node, dst_type, env)
999 def as_py_string_node(self, env):
1000 # Return a new BytesNode with the same value as this node
1001 # but whose type is a Python type instead of a C type.
1002 return BytesNode(self.pos, value = self.value, type = Builtin.bytes_type)
1004 def generate_evaluation_code(self, code):
1005 if self.type.is_pyobject:
1006 self.result_code = code.get_py_string_const(self.value)
1008 self.result_code = code.get_string_const(self.value)
1010 def get_constant_c_result_code(self):
1013 def calculate_result_code(self):
1014 return self.result_code
1017 class UnicodeNode(PyConstNode):
1018 # A Python unicode object
1020 # value EncodedString
1021 # bytes_value BytesLiteral the literal parsed as bytes string ('-3' unicode literals only)
1026 def coerce_to(self, dst_type, env):
1027 if dst_type is self.type:
1029 elif dst_type is PyrexTypes.c_py_unicode_type:
1030 if not self.can_coerce_to_char_literal():
1031 error(self.pos, "Only single-character Unicode string literals can be coerced into Py_UNICODE.")
1033 int_value = ord(self.value)
1034 return IntNode(self.pos, value=int_value, constant_result=int_value)
1035 elif not dst_type.is_pyobject:
1036 if dst_type.is_string and self.bytes_value is not None:
1037 # special case: '-3' enforced unicode literal used in a C char* context
1038 return BytesNode(self.pos, value=self.bytes_value).coerce_to(dst_type, env)
1039 error(self.pos, "Unicode literals do not support coercion to C types other than Py_UNICODE.")
1040 elif dst_type is not py_object_type:
1041 if not self.check_for_coercion_error(dst_type):
1042 self.fail_assignment(dst_type)
1045 def can_coerce_to_char_literal(self):
1046 return len(self.value) == 1
1048 def contains_surrogates(self):
1049 # Check if the unicode string contains surrogate code points
1050 # on a CPython platform with wide (UCS-4) or narrow (UTF-16)
1051 # Unicode, i.e. characters that would be spelled as two
1052 # separate code units on a narrow platform.
1053 for c in map(ord, self.value):
1054 if c > 65535: # can only happen on wide platforms
1056 # We only look for the first code unit (D800-DBFF) of a
1057 # surrogate pair - if we find one, the other one
1058 # (DC00-DFFF) is likely there, too. If we don't find it,
1059 # any second code unit cannot make for a surrogate pair by
1061 if c >= 0xD800 and c <= 0xDBFF:
1065 def generate_evaluation_code(self, code):
1066 self.result_code = code.get_py_string_const(self.value)
1068 def calculate_result_code(self):
1069 return self.result_code
1071 def compile_time_value(self, env):
1075 class StringNode(PyConstNode):
1076 # A Python str object, i.e. a byte string in Python 2.x and a
1077 # unicode string in Python 3.x
1079 # value BytesLiteral
1080 # unicode_value EncodedString
1081 # is_identifier boolean
1084 is_identifier = None
1085 unicode_value = None
1087 def coerce_to(self, dst_type, env):
1088 if dst_type is not py_object_type and not str_type.subtype_of(dst_type):
1089 # if dst_type is Builtin.bytes_type:
1090 # # special case: bytes = 'str literal'
1091 # return BytesNode(self.pos, value=self.value)
1092 if not dst_type.is_pyobject:
1093 return BytesNode(self.pos, value=self.value).coerce_to(dst_type, env)
1094 self.check_for_coercion_error(dst_type, fail=True)
1096 # this will be a unicode string in Py3, so make sure we can decode it
1097 if self.value.encoding:
1098 encoding = self.value.encoding
1100 self.value.decode(encoding)
1101 except UnicodeDecodeError:
1102 error(self.pos, "String decoding as '%s' failed. Consider using a byte string or unicode string explicitly, or adjust the source code encoding." % encoding)
1106 def can_coerce_to_char_literal(self):
1107 return not self.is_identifier and len(self.value) == 1
1109 def generate_evaluation_code(self, code):
1110 self.result_code = code.get_py_string_const(
1111 self.value, identifier=self.is_identifier, is_str=True)
1113 def get_constant_c_result_code(self):
1116 def calculate_result_code(self):
1117 return self.result_code
1119 def compile_time_value(self, env):
1123 class IdentifierStringNode(StringNode):
1124 # A special str value that represents an identifier (bytes in Py2,
1126 is_identifier = True
1129 class LongNode(AtomicExprNode):
1130 # Python long integer literal
1134 type = py_object_type
1136 def calculate_constant_result(self):
1137 self.constant_result = Utils.str_to_number(self.value)
1139 def compile_time_value(self, denv):
1140 return Utils.str_to_number(self.value)
1142 def analyse_types(self, env):
1145 def may_be_none(self):
1148 gil_message = "Constructing Python long int"
1150 def generate_result_code(self, code):
1152 '%s = PyLong_FromString((char *)"%s", 0, 0); %s' % (
1155 code.error_goto_if_null(self.result(), self.pos)))
1156 code.put_gotref(self.py_result())
1159 class ImagNode(AtomicExprNode):
1160 # Imaginary number literal
1162 # value float imaginary part
1164 type = PyrexTypes.c_double_complex_type
1166 def calculate_constant_result(self):
1167 self.constant_result = complex(0.0, self.value)
1169 def compile_time_value(self, denv):
1170 return complex(0.0, self.value)
1172 def analyse_types(self, env):
1173 self.type.create_declaration_utility_code(env)
1175 def may_be_none(self):
1178 def coerce_to(self, dst_type, env):
1179 if self.type is dst_type:
1181 node = ImagNode(self.pos, value=self.value)
1182 if dst_type.is_pyobject:
1184 node.type = PyrexTypes.py_object_type
1185 # We still need to perform normal coerce_to processing on the
1186 # result, because we might be coercing to an extension type,
1187 # in which case a type test node will be needed.
1188 return AtomicExprNode.coerce_to(node, dst_type, env)
1190 gil_message = "Constructing complex number"
1192 def calculate_result_code(self):
1193 if self.type.is_pyobject:
1194 return self.result()
1196 return "%s(0, %r)" % (self.type.from_parts, float(self.value))
1198 def generate_result_code(self, code):
1199 if self.type.is_pyobject:
1201 "%s = PyComplex_FromDoubles(0.0, %r); %s" % (
1204 code.error_goto_if_null(self.result(), self.pos)))
1205 code.put_gotref(self.py_result())
1208 class NewExprNode(AtomicExprNode):
1212 # cppclass node c++ class to create
1216 def infer_type(self, env):
1217 type = self.cppclass.analyse_as_type(env)
1218 if type is None or not type.is_cpp_class:
1219 error(self.pos, "new operator can only be applied to a C++ class")
1220 self.type = error_type
1223 constructor = type.scope.lookup(u'<init>')
1224 if constructor is None:
1225 return_type = PyrexTypes.CFuncType(type, [])
1226 return_type = PyrexTypes.CPtrType(return_type)
1227 type.scope.declare_cfunction(u'<init>', return_type, self.pos)
1228 constructor = type.scope.lookup(u'<init>')
1229 self.class_type = type
1230 self.entry = constructor
1231 self.type = constructor.type
1234 def analyse_types(self, env):
1235 if self.type is None:
1236 self.infer_type(env)
1238 def may_be_none(self):
1241 def generate_result_code(self, code):
1244 def calculate_result_code(self):
1245 return "new " + self.class_type.declaration_code("")
1248 class NameNode(AtomicExprNode):
1249 # Reference to a local or global variable name.
1251 # name string Python name of the variable
1252 # entry Entry Symbol table entry
1253 # type_entry Entry For extension type names, the original type entry
1256 is_cython_module = False
1257 cython_attribute = None
1258 lhs_of_first_assignment = False
1259 is_used_as_rvalue = 0
1263 def create_analysed_rvalue(pos, env, entry):
1264 node = NameNode(pos)
1265 node.analyse_types(env, entry=entry)
1268 def as_cython_attribute(self):
1269 return self.cython_attribute
1271 create_analysed_rvalue = staticmethod(create_analysed_rvalue)
1273 def type_dependencies(self, env):
1274 if self.entry is None:
1275 self.entry = env.lookup(self.name)
1276 if self.entry is not None and self.entry.type.is_unspecified:
1277 return (self.entry,)
1281 def infer_type(self, env):
1282 if self.entry is None:
1283 self.entry = env.lookup(self.name)
1284 if self.entry is None:
1285 return py_object_type
1286 elif (self.entry.type.is_extension_type or self.entry.type.is_builtin_type) and \
1287 self.name == self.entry.type.name:
1288 # Unfortunately the type attribute of type objects
1289 # is used for the pointer to the type they represent.
1292 return self.entry.type
1294 def compile_time_value(self, denv):
1296 return denv.lookup(self.name)
1298 error(self.pos, "Compile-time name '%s' not defined" % self.name)
1300 def get_constant_c_result_code(self):
1301 if not self.entry or self.entry.type.is_pyobject:
1303 return self.entry.cname
1305 def coerce_to(self, dst_type, env):
1306 # If coercing to a generic pyobject and this is a builtin
1307 # C function with a Python equivalent, manufacture a NameNode
1308 # referring to the Python builtin.
1309 #print "NameNode.coerce_to:", self.name, dst_type ###
1310 if dst_type is py_object_type:
1312 if entry and entry.is_cfunction:
1313 var_entry = entry.as_variable
1315 if var_entry.is_builtin and Options.cache_builtins:
1316 var_entry = env.declare_builtin(var_entry.name, self.pos)
1317 node = NameNode(self.pos, name = self.name)
1318 node.entry = var_entry
1319 node.analyse_rvalue_entry(env)
1321 return super(NameNode, self).coerce_to(dst_type, env)
1323 def analyse_as_module(self, env):
1324 # Try to interpret this as a reference to a cimported module.
1325 # Returns the module scope, or None.
1328 entry = env.lookup(self.name)
1329 if entry and entry.as_module:
1330 return entry.as_module
1333 def analyse_as_type(self, env):
1334 if self.cython_attribute:
1335 type = PyrexTypes.parse_basic_type(self.cython_attribute)
1337 type = PyrexTypes.parse_basic_type(self.name)
1342 entry = env.lookup(self.name)
1343 if entry and entry.is_type:
1348 def analyse_as_extension_type(self, env):
1349 # Try to interpret this as a reference to an extension type.
1350 # Returns the extension type, or None.
1353 entry = env.lookup(self.name)
1354 if entry and entry.is_type and entry.type.is_extension_type:
1359 def analyse_target_declaration(self, env):
1361 self.entry = env.lookup_here(self.name)
1363 if env.directives['warn.undeclared']:
1364 warning(self.pos, "implicit declaration of '%s'" % self.name, 1)
1365 if env.directives['infer_types'] != False:
1366 type = unspecified_type
1368 type = py_object_type
1369 self.entry = env.declare_var(self.name, type, self.pos)
1370 env.control_flow.set_state(self.pos, (self.name, 'initialized'), True)
1371 env.control_flow.set_state(self.pos, (self.name, 'source'), 'assignment')
1372 if self.entry.is_declared_generic:
1373 self.result_ctype = py_object_type
1375 def analyse_types(self, env):
1376 if self.entry is None:
1377 self.entry = env.lookup(self.name)
1379 self.entry = env.declare_builtin(self.name, self.pos)
1381 self.type = PyrexTypes.error_type
1386 if entry.type.is_buffer:
1388 Buffer.used_buffer_aux_vars(entry)
1389 if entry.utility_code:
1390 env.use_utility_code(entry.utility_code)
1391 self.analyse_rvalue_entry(env)
1393 def analyse_target_types(self, env):
1394 self.analyse_entry(env)
1395 if not self.is_lvalue():
1396 error(self.pos, "Assignment to non-lvalue '%s'"
1398 self.type = PyrexTypes.error_type
1400 if self.entry.type.is_buffer:
1402 Buffer.used_buffer_aux_vars(self.entry)
1404 def analyse_rvalue_entry(self, env):
1405 #print "NameNode.analyse_rvalue_entry:", self.name ###
1406 #print "Entry:", self.entry.__dict__ ###
1407 self.analyse_entry(env)
1409 if entry.is_declared_generic:
1410 self.result_ctype = py_object_type
1411 if entry.is_pyglobal or entry.is_builtin:
1412 if Options.cache_builtins and entry.is_builtin:
1416 env.use_utility_code(get_name_interned_utility_code)
1417 self.is_used_as_rvalue = 1
1419 def nogil_check(self, env):
1420 if self.is_used_as_rvalue:
1422 if entry.is_builtin:
1423 # if not Options.cache_builtins: # cached builtins are ok
1425 elif entry.is_pyglobal:
1428 gil_message = "Accessing Python global or builtin"
1430 def analyse_entry(self, env):
1431 #print "NameNode.analyse_entry:", self.name ###
1432 self.check_identifier_kind()
1437 def check_identifier_kind(self):
1438 # Check that this is an appropriate kind of name for use in an
1439 # expression. Also finds the variable entry associated with
1440 # an extension type.
1442 if entry.is_type and entry.type.is_extension_type:
1443 self.type_entry = entry
1444 if not (entry.is_const or entry.is_variable
1445 or entry.is_builtin or entry.is_cfunction
1446 or entry.is_cpp_class):
1447 if self.entry.as_variable:
1448 self.entry = self.entry.as_variable
1451 "'%s' is not a constant, variable or function identifier" % self.name)
1453 def is_simple(self):
1454 # If it's not a C variable, it'll be in a temp.
1457 def calculate_target_results(self, env):
1460 def check_const(self):
1462 if entry is not None and not (entry.is_const or entry.is_cfunction or entry.is_builtin):
1467 def check_const_addr(self):
1469 if not (entry.is_cglobal or entry.is_cfunction or entry.is_builtin):
1470 self.addr_not_const()
1474 def is_lvalue(self):
1475 return self.entry.is_variable and \
1476 not self.entry.type.is_array and \
1477 not self.entry.is_readonly
1479 def is_ephemeral(self):
1480 # Name nodes are never ephemeral, even if the
1481 # result is in a temporary.
1484 def calculate_result_code(self):
1487 return "<error>" # There was an error earlier
1490 def generate_result_code(self, code):
1491 assert hasattr(self, 'entry')
1494 return # There was an error earlier
1495 if entry.is_builtin and Options.cache_builtins:
1496 return # Lookup already cached
1497 elif entry.is_pyclass_attr:
1498 assert entry.type.is_pyobject, "Python global or builtin not a Python object"
1499 interned_cname = code.intern_identifier(self.entry.name)
1500 if entry.is_builtin:
1501 namespace = Naming.builtins_cname
1502 else: # entry.is_pyglobal
1503 namespace = entry.scope.namespace_cname
1505 '%s = PyObject_GetItem(%s, %s); %s' % (
1509 code.error_goto_if_null(self.result(), self.pos)))
1510 code.put_gotref(self.py_result())
1512 elif entry.is_pyglobal or entry.is_builtin:
1513 assert entry.type.is_pyobject, "Python global or builtin not a Python object"
1514 interned_cname = code.intern_identifier(self.entry.name)
1515 if entry.is_builtin:
1516 namespace = Naming.builtins_cname
1517 else: # entry.is_pyglobal
1518 namespace = entry.scope.namespace_cname
1519 code.globalstate.use_utility_code(get_name_interned_utility_code)
1521 '%s = __Pyx_GetName(%s, %s); %s' % (
1525 code.error_goto_if_null(self.result(), self.pos)))
1526 code.put_gotref(self.py_result())
1528 elif entry.is_local and False:
1529 # control flow not good enough yet
1530 assigned = entry.scope.control_flow.get_state((entry.name, 'initialized'), self.pos)
1531 if assigned is False:
1532 error(self.pos, "local variable '%s' referenced before assignment" % entry.name)
1533 elif not Options.init_local_none and assigned is None:
1534 code.putln('if (%s == 0) { PyErr_SetString(PyExc_UnboundLocalError, "%s"); %s }' %
1535 (entry.cname, entry.name, code.error_goto(self.pos)))
1536 entry.scope.control_flow.set_state(self.pos, (entry.name, 'initialized'), True)
1538 def generate_assignment_code(self, rhs, code):
1539 #print "NameNode.generate_assignment_code:", self.name ###
1542 return # There was an error earlier
1544 if (self.entry.type.is_ptr and isinstance(rhs, ListNode)
1545 and not self.lhs_of_first_assignment):
1546 error(self.pos, "Literal list must be assigned to pointer at time of declaration")
1548 # is_pyglobal seems to be True for module level-globals only.
1549 # We use this to access class->tp_dict if necessary.
1550 if entry.is_pyglobal:
1551 assert entry.type.is_pyobject, "Python global or builtin not a Python object"
1552 interned_cname = code.intern_identifier(self.entry.name)
1553 namespace = self.entry.scope.namespace_cname
1555 # if the entry is a member we have to cheat: SetAttr does not work
1556 # on types, so we create a descriptor which is then added to tp_dict
1557 code.put_error_if_neg(self.pos,
1558 'PyDict_SetItem(%s->tp_dict, %s, %s)' % (
1562 rhs.generate_disposal_code(code)
1563 rhs.free_temps(code)
1564 # in Py2.6+, we need to invalidate the method cache
1565 code.putln("PyType_Modified(%s);" %
1566 entry.scope.parent_type.typeptr_cname)
1567 elif entry.is_pyclass_attr:
1568 code.put_error_if_neg(self.pos,
1569 'PyObject_SetItem(%s, %s, %s)' % (
1573 rhs.generate_disposal_code(code)
1574 rhs.free_temps(code)
1576 code.put_error_if_neg(self.pos,
1577 'PyObject_SetAttr(%s, %s, %s)' % (
1581 if debug_disposal_code:
1582 print("NameNode.generate_assignment_code:")
1583 print("...generating disposal code for %s" % rhs)
1584 rhs.generate_disposal_code(code)
1585 rhs.free_temps(code)
1587 if self.type.is_buffer:
1588 # Generate code for doing the buffer release/acquisition.
1589 # This might raise an exception in which case the assignment (done
1590 # below) will not happen.
1592 # The reason this is not in a typetest-like node is because the
1593 # variables that the acquired buffer info is stored to is allocated
1594 # per entry and coupled with it.
1595 self.generate_acquire_buffer(rhs, code)
1597 if self.type.is_pyobject:
1598 #print "NameNode.generate_assignment_code: to", self.name ###
1599 #print "...from", rhs ###
1600 #print "...LHS type", self.type, "ctype", self.ctype() ###
1601 #print "...RHS type", rhs.type, "ctype", rhs.ctype() ###
1602 if self.use_managed_ref:
1603 rhs.make_owned_reference(code)
1604 if entry.is_cglobal:
1605 code.put_gotref(self.py_result())
1606 if not self.lhs_of_first_assignment:
1607 if entry.is_local and not Options.init_local_none:
1608 initialized = entry.scope.control_flow.get_state((entry.name, 'initialized'), self.pos)
1609 if initialized is True:
1610 code.put_decref(self.result(), self.ctype())
1611 elif initialized is None:
1612 code.put_xdecref(self.result(), self.ctype())
1614 code.put_decref(self.result(), self.ctype())
1615 if entry.is_cglobal:
1616 code.put_giveref(rhs.py_result())
1618 code.putln('%s = %s;' % (self.result(),
1619 rhs.result_as(self.ctype())))
1620 if debug_disposal_code:
1621 print("NameNode.generate_assignment_code:")
1622 print("...generating post-assignment code for %s" % rhs)
1623 rhs.generate_post_assignment_code(code)
1624 rhs.free_temps(code)
1626 def generate_acquire_buffer(self, rhs, code):
1627 # rhstmp is only used in case the rhs is a complicated expression leading to
1628 # the object, to avoid repeating the same C expression for every reference
1629 # to the rhs. It does NOT hold a reference.
1630 pretty_rhs = isinstance(rhs, NameNode) or rhs.is_temp
1632 rhstmp = rhs.result_as(self.ctype())
1634 rhstmp = code.funcstate.allocate_temp(self.entry.type, manage_ref=False)
1635 code.putln('%s = %s;' % (rhstmp, rhs.result_as(self.ctype())))
1637 buffer_aux = self.entry.buffer_aux
1638 bufstruct = buffer_aux.buffer_info_var.cname
1640 Buffer.put_assign_to_buffer(self.result(), rhstmp, buffer_aux, self.entry.type,
1641 is_initialized=not self.lhs_of_first_assignment,
1642 pos=self.pos, code=code)
1645 code.putln("%s = 0;" % rhstmp)
1646 code.funcstate.release_temp(rhstmp)
1648 def generate_deletion_code(self, code):
1649 if self.entry is None:
1650 return # There was an error earlier
1651 if not self.entry.is_pyglobal:
1652 error(self.pos, "Deletion of local or C global name not supported")
1654 if self.entry.is_pyclass_attr:
1655 namespace = self.entry.scope.namespace_cname
1656 code.put_error_if_neg(self.pos,
1657 'PyMapping_DelItemString(%s, "%s")' % (
1661 code.put_error_if_neg(self.pos,
1662 '__Pyx_DelAttrString(%s, "%s")' % (
1663 Naming.module_cname,
1666 def annotate(self, code):
1667 if hasattr(self, 'is_called') and self.is_called:
1668 pos = (self.pos[0], self.pos[1], self.pos[2] - len(self.name) - 1)
1669 if self.type.is_pyobject:
1670 code.annotate(pos, AnnotationItem('py_call', 'python function', size=len(self.name)))
1672 code.annotate(pos, AnnotationItem('c_call', 'c function', size=len(self.name)))
1674 class BackquoteNode(ExprNode):
1679 type = py_object_type
1683 def analyse_types(self, env):
1684 self.arg.analyse_types(env)
1685 self.arg = self.arg.coerce_to_pyobject(env)
1688 gil_message = "Backquote expression"
1690 def calculate_constant_result(self):
1691 self.constant_result = repr(self.arg.constant_result)
1693 def generate_result_code(self, code):
1695 "%s = PyObject_Repr(%s); %s" % (
1697 self.arg.py_result(),
1698 code.error_goto_if_null(self.result(), self.pos)))
1699 code.put_gotref(self.py_result())
1703 class ImportNode(ExprNode):
1704 # Used as part of import statement implementation.
1705 # Implements result =
1706 # __import__(module_name, globals(), None, name_list)
1708 # module_name StringNode dotted name of module
1709 # name_list ListNode or None list of names to be imported
1711 type = py_object_type
1713 subexprs = ['module_name', 'name_list']
1715 def analyse_types(self, env):
1716 self.module_name.analyse_types(env)
1717 self.module_name = self.module_name.coerce_to_pyobject(env)
1719 self.name_list.analyse_types(env)
1720 self.name_list.coerce_to_pyobject(env)
1722 env.use_utility_code(import_utility_code)
1724 gil_message = "Python import"
1726 def generate_result_code(self, code):
1728 name_list_code = self.name_list.py_result()
1730 name_list_code = "0"
1732 "%s = __Pyx_Import(%s, %s); %s" % (
1734 self.module_name.py_result(),
1736 code.error_goto_if_null(self.result(), self.pos)))
1737 code.put_gotref(self.py_result())
1740 class IteratorNode(ExprNode):
1741 # Used as part of for statement implementation.
1743 # allocate_counter_temp/release_counter_temp needs to be called
1744 # by parent (ForInStatNode)
1746 # Implements result = iter(sequence)
1750 type = py_object_type
1752 subexprs = ['sequence']
1754 def analyse_types(self, env):
1755 self.sequence.analyse_types(env)
1756 if (self.sequence.type.is_array or self.sequence.type.is_ptr) and \
1757 not self.sequence.type.is_string:
1758 # C array iteration will be transformed later on
1759 self.type = self.sequence.type
1761 self.sequence = self.sequence.coerce_to_pyobject(env)
1764 gil_message = "Iterating over Python object"
1766 def allocate_counter_temp(self, code):
1767 self.counter_cname = code.funcstate.allocate_temp(
1768 PyrexTypes.c_py_ssize_t_type, manage_ref=False)
1770 def release_counter_temp(self, code):
1771 code.funcstate.release_temp(self.counter_cname)
1773 def generate_result_code(self, code):
1774 if self.sequence.type.is_array or self.sequence.type.is_ptr:
1775 raise InternalError("for in carray slice not transformed")
1776 is_builtin_sequence = self.sequence.type is list_type or \
1777 self.sequence.type is tuple_type
1778 may_be_a_sequence = is_builtin_sequence or not self.sequence.type.is_builtin_type
1779 if is_builtin_sequence:
1781 "if (likely(%s != Py_None)) {" % self.sequence.py_result())
1782 elif may_be_a_sequence:
1784 "if (PyList_CheckExact(%s) || PyTuple_CheckExact(%s)) {" % (
1785 self.sequence.py_result(),
1786 self.sequence.py_result()))
1787 if may_be_a_sequence:
1789 "%s = 0; %s = %s; __Pyx_INCREF(%s);" % (
1792 self.sequence.py_result(),
1794 code.putln("} else {")
1795 if is_builtin_sequence:
1797 'PyErr_SetString(PyExc_TypeError, "\'NoneType\' object is not iterable"); %s' %
1798 code.error_goto(self.pos))
1800 code.putln("%s = -1; %s = PyObject_GetIter(%s); %s" % (
1803 self.sequence.py_result(),
1804 code.error_goto_if_null(self.result(), self.pos)))
1805 code.put_gotref(self.py_result())
1806 if may_be_a_sequence:
1810 class NextNode(AtomicExprNode):
1811 # Used as part of for statement implementation.
1812 # Implements result = iterator.next()
1813 # Created during analyse_types phase.
1814 # The iterator is not owned by this node.
1818 type = py_object_type
1820 def __init__(self, iterator, env):
1821 self.pos = iterator.pos
1822 self.iterator = iterator
1823 if iterator.type.is_ptr or iterator.type.is_array:
1824 self.type = iterator.type.base_type
1827 def generate_result_code(self, code):
1828 sequence_type = self.iterator.sequence.type
1829 if sequence_type is list_type:
1830 type_checks = [(list_type, "List")]
1831 elif sequence_type is tuple_type:
1832 type_checks = [(tuple_type, "Tuple")]
1833 elif not sequence_type.is_builtin_type:
1834 type_checks = [(list_type, "List"), (tuple_type, "Tuple")]
1838 for py_type, prefix in type_checks:
1839 if len(type_checks) > 1:
1841 "if (likely(Py%s_CheckExact(%s))) {" % (
1842 prefix, self.iterator.py_result()))
1844 "if (%s >= Py%s_GET_SIZE(%s)) break;" % (
1845 self.iterator.counter_cname,
1847 self.iterator.py_result()))
1849 "%s = Py%s_GET_ITEM(%s, %s); __Pyx_INCREF(%s); %s++;" % (
1852 self.iterator.py_result(),
1853 self.iterator.counter_cname,
1855 self.iterator.counter_cname))
1856 if len(type_checks) > 1:
1858 if len(type_checks) == 1:
1862 "%s = PyIter_Next(%s);" % (
1864 self.iterator.py_result()))
1868 code.putln(code.error_goto_if_PyErr(self.pos))
1869 code.putln("break;")
1871 code.put_gotref(self.py_result())
1875 class ExcValueNode(AtomicExprNode):
1876 # Node created during analyse_types phase
1877 # of an ExceptClauseNode to fetch the current
1880 type = py_object_type
1882 def __init__(self, pos, env):
1883 ExprNode.__init__(self, pos)
1885 def set_var(self, var):
1888 def calculate_result_code(self):
1891 def generate_result_code(self, code):
1894 def analyse_types(self, env):
1898 class TempNode(ExprNode):
1899 # Node created during analyse_types phase
1900 # of some nodes to hold a temporary value.
1902 # Note: One must call "allocate" and "release" on
1903 # the node during code generation to get/release the temp.
1904 # This is because the temp result is often used outside of
1905 # the regular cycle.
1909 def __init__(self, pos, type, env):
1910 ExprNode.__init__(self, pos)
1912 if type.is_pyobject:
1913 self.result_ctype = py_object_type
1916 def analyse_types(self, env):
1919 def generate_result_code(self, code):
1922 def allocate(self, code):
1923 self.temp_cname = code.funcstate.allocate_temp(self.type, manage_ref=True)
1925 def release(self, code):
1926 code.funcstate.release_temp(self.temp_cname)
1927 self.temp_cname = None
1931 return self.temp_cname
1933 assert False, "Remember to call allocate/release on TempNode"
1936 # Do not participate in normal temp alloc/dealloc:
1937 def allocate_temp_result(self, code):
1940 def release_temp_result(self, code):
1943 class PyTempNode(TempNode):
1944 # TempNode holding a Python value.
1946 def __init__(self, pos, env):
1947 TempNode.__init__(self, pos, PyrexTypes.py_object_type, env)
1949 class RawCNameExprNode(ExprNode):
1952 def __init__(self, pos, type=None):
1956 def analyse_types(self, env):
1959 def set_cname(self, cname):
1965 def generate_result_code(self, code):
1969 #-------------------------------------------------------------------
1973 #-------------------------------------------------------------------
1975 class IndexNode(ExprNode):
1976 # Sequence indexing.
1980 # indices [ExprNode]
1981 # is_buffer_access boolean Whether this is a buffer access.
1983 # indices is used on buffer access, index on non-buffer access.
1984 # The former contains a clean list of index parameters, the
1985 # latter whatever Python object is needed for index access.
1987 subexprs = ['base', 'index', 'indices']
1990 def __init__(self, pos, index, *args, **kw):
1991 ExprNode.__init__(self, pos, index=index, *args, **kw)
1994 def calculate_constant_result(self):
1995 self.constant_result = \
1996 self.base.constant_result[self.index.constant_result]
1998 def compile_time_value(self, denv):
1999 base = self.base.compile_time_value(denv)
2000 index = self.index.compile_time_value(denv)
2003 except Exception, e:
2004 self.compile_time_value_error(e)
2006 def is_ephemeral(self):
2007 return self.base.is_ephemeral()
2009 def analyse_target_declaration(self, env):
2012 def analyse_as_type(self, env):
2013 base_type = self.base.analyse_as_type(env)
2014 if base_type and not base_type.is_pyobject:
2015 if base_type.is_cpp_class:
2016 if isinstance(self.index, TupleNode):
2017 template_values = self.index.args
2019 template_values = [self.index]
2021 type_node = Nodes.TemplatedTypeNode(
2023 positional_args = template_values,
2024 keyword_args = None)
2025 return type_node.analyse(env, base_type = base_type)
2027 return PyrexTypes.CArrayType(base_type, int(self.index.compile_time_value(env)))
2030 def type_dependencies(self, env):
2031 return self.base.type_dependencies(env)
2033 def infer_type(self, env):
2034 base_type = self.base.infer_type(env)
2035 if isinstance(self.index, SliceNode):
2037 if base_type.is_string:
2038 # sliced C strings must coerce to Python
2040 elif base_type in (unicode_type, bytes_type, str_type, list_type, tuple_type):
2041 # slicing these returns the same type
2044 # TODO: Handle buffers (hopefully without too much redundancy).
2045 return py_object_type
2047 index_type = self.index.infer_type(env)
2048 if index_type and index_type.is_int or isinstance(self.index, (IntNode, LongNode)):
2050 if base_type is unicode_type:
2051 # Py_UNICODE will automatically coerce to a unicode string
2052 # if required, so this is safe. We only infer Py_UNICODE
2053 # when the index is a C integer type. Otherwise, we may
2054 # need to use normal Python item access, in which case
2055 # it's faster to return the one-char unicode string than
2056 # to receive it, throw it away, and potentially rebuild it
2057 # on a subsequent PyObject coercion.
2058 return PyrexTypes.c_py_unicode_type
2059 elif isinstance(self.base, BytesNode):
2060 #if env.global_scope().context.language_level >= 3:
2061 # # infering 'char' can be made to work in Python 3 mode
2062 # return PyrexTypes.c_char_type
2063 # Py2/3 return different types on indexing bytes objects
2064 return py_object_type
2065 elif base_type.is_ptr or base_type.is_array:
2066 return base_type.base_type
2068 # may be slicing or indexing, we don't know
2069 if base_type is unicode_type:
2070 # this type always returns its own type on Python indexing/slicing
2073 # TODO: Handle buffers (hopefully without too much redundancy).
2074 return py_object_type
2076 def analyse_types(self, env):
2077 self.analyse_base_and_index_types(env, getting = 1)
2079 def analyse_target_types(self, env):
2080 self.analyse_base_and_index_types(env, setting = 1)
2082 def analyse_base_and_index_types(self, env, getting = 0, setting = 0):
2083 # Note: This might be cleaned up by having IndexNode
2084 # parsed in a saner way and only construct the tuple if
2087 # Note that this function must leave IndexNode in a cloneable state.
2088 # For buffers, self.index is packed out on the initial analysis, and
2089 # when cloning self.indices is copied.
2090 self.is_buffer_access = False
2092 self.base.analyse_types(env)
2093 if self.base.type.is_error:
2094 # Do not visit child tree if base is undeclared to avoid confusing
2096 self.type = PyrexTypes.error_type
2099 is_slice = isinstance(self.index, SliceNode)
2100 # Potentially overflowing index value.
2101 if not is_slice and isinstance(self.index, IntNode) and Utils.long_literal(self.index.value):
2102 self.index = self.index.coerce_to_pyobject(env)
2104 # Handle the case where base is a literal char* (and we expect a string, not an int)
2105 if isinstance(self.base, BytesNode) or is_slice:
2106 if self.base.type.is_string or not (self.base.type.is_ptr or self.base.type.is_array):
2107 self.base = self.base.coerce_to_pyobject(env)
2109 skip_child_analysis = False
2110 buffer_access = False
2111 if self.base.type.is_buffer:
2113 indices = self.indices
2115 if isinstance(self.index, TupleNode):
2116 indices = self.index.args
2118 indices = [self.index]
2119 if len(indices) == self.base.type.ndim:
2120 buffer_access = True
2121 skip_child_analysis = True
2123 x.analyse_types(env)
2124 if not x.type.is_int:
2125 buffer_access = False
2127 assert hasattr(self.base, "entry") # Must be a NameNode-like node
2129 # On cloning, indices is cloned. Otherwise, unpack index into indices
2130 assert not (buffer_access and isinstance(self.index, CloneNode))
2133 self.indices = indices
2135 self.type = self.base.type.dtype
2136 self.is_buffer_access = True
2137 self.buffer_type = self.base.entry.type
2139 if getting and self.type.is_pyobject:
2142 if not self.base.entry.type.writable:
2143 error(self.pos, "Writing to readonly buffer")
2145 self.base.entry.buffer_aux.writable_needed = True
2147 base_type = self.base.type
2148 if isinstance(self.index, TupleNode):
2149 self.index.analyse_types(env, skip_children=skip_child_analysis)
2150 elif not skip_child_analysis:
2151 self.index.analyse_types(env)
2152 self.original_index_type = self.index.type
2153 if base_type is PyrexTypes.c_py_unicode_type:
2154 # we infer Py_UNICODE for unicode strings in some
2155 # cases, but indexing must still work for them
2156 if self.index.constant_result in (0, -1):
2157 # FIXME: we know that this node is redundant -
2158 # currently, this needs to get handled in Optimize.py
2160 self.base = self.base.coerce_to_pyobject(env)
2161 base_type = self.base.type
2162 if base_type.is_pyobject:
2163 if self.index.type.is_int:
2165 and (base_type in (list_type, tuple_type, unicode_type))
2166 and (not self.index.type.signed or isinstance(self.index, IntNode) and int(self.index.value) >= 0)
2167 and not env.directives['boundscheck']):
2171 self.index = self.index.coerce_to(PyrexTypes.c_py_ssize_t_type, env).coerce_to_simple(env)
2173 self.index = self.index.coerce_to_pyobject(env)
2175 if self.index.type.is_int and base_type is unicode_type:
2176 # Py_UNICODE will automatically coerce to a unicode string
2177 # if required, so this is fast and safe
2178 self.type = PyrexTypes.c_py_unicode_type
2179 elif is_slice and base_type in (bytes_type, str_type, unicode_type, list_type, tuple_type):
2180 self.type = base_type
2182 self.type = py_object_type
2184 if base_type.is_ptr or base_type.is_array:
2185 self.type = base_type.base_type
2187 self.type = base_type
2188 elif self.index.type.is_pyobject:
2189 self.index = self.index.coerce_to(
2190 PyrexTypes.c_py_ssize_t_type, env)
2191 elif not self.index.type.is_int:
2193 "Invalid index type '%s'" %
2195 elif base_type.is_cpp_class:
2196 function = env.lookup_operator("[]", [self.base, self.index])
2197 if function is None:
2198 error(self.pos, "Indexing '%s' not supported for index type '%s'" % (base_type, self.index.type))
2199 self.type = PyrexTypes.error_type
2200 self.result_code = "<error>"
2202 func_type = function.type
2203 if func_type.is_ptr:
2204 func_type = func_type.base_type
2205 self.index = self.index.coerce_to(func_type.args[0].type, env)
2206 self.type = func_type.return_type
2207 if setting and not func_type.return_type.is_reference:
2208 error(self.pos, "Can't set non-reference result '%s'" % self.type)
2211 "Attempting to index non-array type '%s'" %
2213 self.type = PyrexTypes.error_type
2215 gil_message = "Indexing Python object"
2217 def nogil_check(self, env):
2218 if self.is_buffer_access:
2219 if env.directives['boundscheck']:
2220 error(self.pos, "Cannot check buffer index bounds without gil; use boundscheck(False) directive")
2222 elif self.type.is_pyobject:
2223 error(self.pos, "Cannot access buffer with object dtype without gil")
2225 super(IndexNode, self).nogil_check(env)
2228 def check_const_addr(self):
2229 return self.base.check_const_addr() and self.index.check_const()
2231 def is_lvalue(self):
2234 def calculate_result_code(self):
2235 if self.is_buffer_access:
2236 return "(*%s)" % self.buffer_ptr_code
2237 elif self.base.type is list_type:
2238 return "PyList_GET_ITEM(%s, %s)" % (self.base.result(), self.index.result())
2239 elif self.base.type is tuple_type:
2240 return "PyTuple_GET_ITEM(%s, %s)" % (self.base.result(), self.index.result())
2241 elif self.base.type is unicode_type and self.type is PyrexTypes.c_py_unicode_type:
2242 return "PyUnicode_AS_UNICODE(%s)[%s]" % (self.base.result(), self.index.result())
2243 elif (self.type.is_ptr or self.type.is_array) and self.type == self.base.type:
2244 error(self.pos, "Invalid use of pointer slice")
2246 return "(%s[%s])" % (
2247 self.base.result(), self.index.result())
2249 def extra_index_params(self):
2250 if self.index.type.is_int:
2251 if self.original_index_type.signed:
2252 size_adjustment = ""
2254 size_adjustment = "+1"
2255 return ", sizeof(%s)%s, %s" % (self.original_index_type.declaration_code(""), size_adjustment, self.original_index_type.to_py_function)
2259 def generate_subexpr_evaluation_code(self, code):
2260 self.base.generate_evaluation_code(code)
2261 if not self.indices:
2262 self.index.generate_evaluation_code(code)
2264 for i in self.indices:
2265 i.generate_evaluation_code(code)
2267 def generate_subexpr_disposal_code(self, code):
2268 self.base.generate_disposal_code(code)
2269 if not self.indices:
2270 self.index.generate_disposal_code(code)
2272 for i in self.indices:
2273 i.generate_disposal_code(code)
2275 def free_subexpr_temps(self, code):
2276 self.base.free_temps(code)
2277 if not self.indices:
2278 self.index.free_temps(code)
2280 for i in self.indices:
2283 def generate_result_code(self, code):
2284 if self.is_buffer_access:
2285 if code.globalstate.directives['nonecheck']:
2286 self.put_nonecheck(code)
2287 self.buffer_ptr_code = self.buffer_lookup_code(code)
2288 if self.type.is_pyobject:
2289 # is_temp is True, so must pull out value and incref it.
2290 code.putln("%s = *%s;" % (self.result(), self.buffer_ptr_code))
2291 code.putln("__Pyx_INCREF((PyObject*)%s);" % self.result())
2293 if self.type.is_pyobject:
2294 if self.index.type.is_int:
2295 index_code = self.index.result()
2296 if self.base.type is list_type:
2297 function = "__Pyx_GetItemInt_List"
2298 elif self.base.type is tuple_type:
2299 function = "__Pyx_GetItemInt_Tuple"
2301 function = "__Pyx_GetItemInt"
2302 code.globalstate.use_utility_code(getitem_int_utility_code)
2304 index_code = self.index.py_result()
2305 if self.base.type is dict_type:
2306 function = "__Pyx_PyDict_GetItem"
2307 code.globalstate.use_utility_code(getitem_dict_utility_code)
2309 function = "PyObject_GetItem"
2311 "%s = %s(%s, %s%s); if (!%s) %s" % (
2314 self.base.py_result(),
2316 self.extra_index_params(),
2318 code.error_goto(self.pos)))
2319 code.put_gotref(self.py_result())
2320 elif self.type is PyrexTypes.c_py_unicode_type and self.base.type is unicode_type:
2321 assert self.index.type.is_int
2322 index_code = self.index.result()
2323 function = "__Pyx_GetItemInt_Unicode"
2324 code.globalstate.use_utility_code(getitem_int_pyunicode_utility_code)
2326 "%s = %s(%s, %s%s); if (unlikely(%s == (Py_UNICODE)-1)) %s;" % (
2329 self.base.py_result(),
2331 self.extra_index_params(),
2333 code.error_goto(self.pos)))
2335 def generate_setitem_code(self, value_code, code):
2336 if self.index.type.is_int:
2337 function = "__Pyx_SetItemInt"
2338 index_code = self.index.result()
2339 code.globalstate.use_utility_code(setitem_int_utility_code)
2341 index_code = self.index.py_result()
2342 if self.base.type is dict_type:
2343 function = "PyDict_SetItem"
2344 # It would seem that we could specialized lists/tuples, but that
2345 # shouldn't happen here.
2346 # Both PyList_SetItem PyTuple_SetItem and a Py_ssize_t as input,
2347 # not a PyObject*, and bad conversion here would give the wrong
2348 # exception. Also, tuples are supposed to be immutable, and raise
2349 # TypeErrors when trying to set their entries (PyTuple_SetItem
2350 # is for creating new tuples from).
2352 function = "PyObject_SetItem"
2354 "if (%s(%s, %s, %s%s) < 0) %s" % (
2356 self.base.py_result(),
2359 self.extra_index_params(),
2360 code.error_goto(self.pos)))
2362 def generate_buffer_setitem_code(self, rhs, code, op=""):
2363 # Used from generate_assignment_code and InPlaceAssignmentNode
2364 if code.globalstate.directives['nonecheck']:
2365 self.put_nonecheck(code)
2366 ptrexpr = self.buffer_lookup_code(code)
2367 if self.buffer_type.dtype.is_pyobject:
2368 # Must manage refcounts. Decref what is already there
2369 # and incref what we put in.
2370 ptr = code.funcstate.allocate_temp(self.buffer_type.buffer_ptr_type, manage_ref=False)
2371 rhs_code = rhs.result()
2372 code.putln("%s = %s;" % (ptr, ptrexpr))
2373 code.put_gotref("*%s" % ptr)
2374 code.putln("__Pyx_DECREF(*%s); __Pyx_INCREF(%s);" % (
2377 code.putln("*%s %s= %s;" % (ptr, op, rhs_code))
2378 code.put_giveref("*%s" % ptr)
2379 code.funcstate.release_temp(ptr)
2382 code.putln("*%s %s= %s;" % (ptrexpr, op, rhs.result()))
2384 def generate_assignment_code(self, rhs, code):
2385 self.generate_subexpr_evaluation_code(code)
2386 if self.is_buffer_access:
2387 self.generate_buffer_setitem_code(rhs, code)
2388 elif self.type.is_pyobject:
2389 self.generate_setitem_code(rhs.py_result(), code)
2393 self.result(), rhs.result()))
2394 self.generate_subexpr_disposal_code(code)
2395 self.free_subexpr_temps(code)
2396 rhs.generate_disposal_code(code)
2397 rhs.free_temps(code)
2399 def generate_deletion_code(self, code):
2400 self.generate_subexpr_evaluation_code(code)
2401 #if self.type.is_pyobject:
2402 if self.index.type.is_int:
2403 function = "__Pyx_DelItemInt"
2404 index_code = self.index.result()
2405 code.globalstate.use_utility_code(delitem_int_utility_code)
2407 index_code = self.index.py_result()
2408 if self.base.type is dict_type:
2409 function = "PyDict_DelItem"
2411 function = "PyObject_DelItem"
2413 "if (%s(%s, %s%s) < 0) %s" % (
2415 self.base.py_result(),
2417 self.extra_index_params(),
2418 code.error_goto(self.pos)))
2419 self.generate_subexpr_disposal_code(code)
2420 self.free_subexpr_temps(code)
2422 def buffer_lookup_code(self, code):
2423 # Assign indices to temps
2424 index_temps = [code.funcstate.allocate_temp(i.type, manage_ref=False) for i in self.indices]
2425 for temp, index in zip(index_temps, self.indices):
2426 code.putln("%s = %s;" % (temp, index.result()))
2427 # Generate buffer access code using these temps
2429 # The above could happen because child_attrs is wrong somewhere so that
2430 # options are not propagated.
2431 return Buffer.put_buffer_lookup_code(entry=self.base.entry,
2432 index_signeds=[i.type.signed for i in self.indices],
2433 index_cnames=index_temps,
2434 directives=code.globalstate.directives,
2435 pos=self.pos, code=code)
2437 def put_nonecheck(self, code):
2438 code.globalstate.use_utility_code(raise_noneindex_error_utility_code)
2439 code.putln("if (%s) {" % code.unlikely("%s == Py_None") % self.base.result_as(PyrexTypes.py_object_type))
2440 code.putln("__Pyx_RaiseNoneIndexingError();")
2441 code.putln(code.error_goto(self.pos))
2444 class SliceIndexNode(ExprNode):
2445 # 2-element slice indexing
2448 # start ExprNode or None
2449 # stop ExprNode or None
2451 subexprs = ['base', 'start', 'stop']
2453 def infer_type(self, env):
2454 base_type = self.base.infer_type(env)
2455 if base_type.is_string:
2457 elif base_type in (bytes_type, str_type, unicode_type,
2458 list_type, tuple_type):
2460 return py_object_type
2462 def calculate_constant_result(self):
2463 self.constant_result = self.base.constant_result[
2464 self.start.constant_result : self.stop.constant_result]
2466 def compile_time_value(self, denv):
2467 base = self.base.compile_time_value(denv)
2468 if self.start is None:
2471 start = self.start.compile_time_value(denv)
2472 if self.stop is None:
2475 stop = self.stop.compile_time_value(denv)
2477 return base[start:stop]
2478 except Exception, e:
2479 self.compile_time_value_error(e)
2481 def analyse_target_declaration(self, env):
2484 def analyse_target_types(self, env):
2485 self.analyse_types(env)
2486 # when assigning, we must accept any Python type
2487 if self.type.is_pyobject:
2488 self.type = py_object_type
2490 def analyse_types(self, env):
2491 self.base.analyse_types(env)
2493 self.start.analyse_types(env)
2495 self.stop.analyse_types(env)
2496 base_type = self.base.type
2497 if base_type.is_string:
2498 self.type = bytes_type
2499 elif base_type.is_ptr:
2500 self.type = base_type
2501 elif base_type.is_array:
2502 # we need a ptr type here instead of an array type, as
2503 # array types can result in invalid type casts in the C
2505 self.type = PyrexTypes.CPtrType(base_type.base_type)
2507 self.base = self.base.coerce_to_pyobject(env)
2508 self.type = py_object_type
2509 if base_type.is_builtin_type:
2510 # slicing builtin types returns something of the same type
2511 self.type = base_type
2512 c_int = PyrexTypes.c_py_ssize_t_type
2514 self.start = self.start.coerce_to(c_int, env)
2516 self.stop = self.stop.coerce_to(c_int, env)
2519 nogil_check = Node.gil_error
2520 gil_message = "Slicing Python object"
2522 def generate_result_code(self, code):
2523 if not self.type.is_pyobject:
2525 "Slicing is not currently supported for '%s'." % self.type)
2527 if self.base.type.is_string:
2528 if self.stop is None:
2530 "%s = PyBytes_FromString(%s + %s); %s" % (
2534 code.error_goto_if_null(self.result(), self.pos)))
2537 "%s = PyBytes_FromStringAndSize(%s + %s, %s - %s); %s" % (
2543 code.error_goto_if_null(self.result(), self.pos)))
2546 "%s = __Pyx_PySequence_GetSlice(%s, %s, %s); %s" % (
2548 self.base.py_result(),
2551 code.error_goto_if_null(self.result(), self.pos)))
2552 code.put_gotref(self.py_result())
2554 def generate_assignment_code(self, rhs, code):
2555 self.generate_subexpr_evaluation_code(code)
2556 if self.type.is_pyobject:
2557 code.put_error_if_neg(self.pos,
2558 "__Pyx_PySequence_SetSlice(%s, %s, %s, %s)" % (
2559 self.base.py_result(),
2566 start_offset = self.start_code()
2567 if start_offset == '0':
2571 if rhs.type.is_array:
2572 array_length = rhs.type.size
2573 self.generate_slice_guard_code(code, array_length)
2576 "Slice assignments from pointers are not yet supported.")
2577 # FIXME: fix the array size according to start/stop
2578 array_length = self.base.type.size
2579 for i in range(array_length):
2580 code.putln("%s[%s%s] = %s[%d];" % (
2581 self.base.result(), start_offset, i,
2583 self.generate_subexpr_disposal_code(code)
2584 self.free_subexpr_temps(code)
2585 rhs.generate_disposal_code(code)
2586 rhs.free_temps(code)
2588 def generate_deletion_code(self, code):
2589 if not self.base.type.is_pyobject:
2591 "Deleting slices is only supported for Python types, not '%s'." % self.type)
2593 self.generate_subexpr_evaluation_code(code)
2594 code.put_error_if_neg(self.pos,
2595 "__Pyx_PySequence_DelSlice(%s, %s, %s)" % (
2596 self.base.py_result(),
2599 self.generate_subexpr_disposal_code(code)
2601 def generate_slice_guard_code(self, code, target_size):
2602 if not self.base.type.is_array:
2604 slice_size = self.base.type.size
2607 stop = self.stop.result()
2611 slice_size = self.base.type.size + stop
2618 start = self.start.result()
2622 start = self.base.type.size + start
2630 error(self.pos, "Assignment to empty slice.")
2631 elif start is None and stop is None:
2632 # we know the exact slice length
2633 if target_size != slice_size:
2634 error(self.pos, "Assignment to slice of wrong length, expected %d, got %d" % (
2635 slice_size, target_size))
2636 elif start is not None:
2639 check = "(%s)-(%s)" % (stop, start)
2640 else: # stop is not None:
2643 code.putln("if (unlikely((%s) != %d)) {" % (check, target_size))
2644 code.putln('PyErr_Format(PyExc_ValueError, "Assignment to slice of wrong length, expected %%"PY_FORMAT_SIZE_T"d, got %%"PY_FORMAT_SIZE_T"d", (Py_ssize_t)%d, (Py_ssize_t)(%s));' % (
2645 target_size, check))
2646 code.putln(code.error_goto(self.pos))
2649 def start_code(self):
2651 return self.start.result()
2655 def stop_code(self):
2657 return self.stop.result()
2658 elif self.base.type.is_array:
2659 return self.base.type.size
2661 return "PY_SSIZE_T_MAX"
2663 def calculate_result_code(self):
2664 # self.result() is not used, but this method must exist
2668 class SliceNode(ExprNode):
2669 # start:stop:step in subscript list
2675 type = py_object_type
2678 def calculate_constant_result(self):
2679 self.constant_result = self.base.constant_result[
2680 self.start.constant_result : \
2681 self.stop.constant_result : \
2682 self.step.constant_result]
2684 def compile_time_value(self, denv):
2685 start = self.start.compile_time_value(denv)
2686 if self.stop is None:
2689 stop = self.stop.compile_time_value(denv)
2690 if self.step is None:
2693 step = self.step.compile_time_value(denv)
2695 return slice(start, stop, step)
2696 except Exception, e:
2697 self.compile_time_value_error(e)
2699 subexprs = ['start', 'stop', 'step']
2701 def analyse_types(self, env):
2702 self.start.analyse_types(env)
2703 self.stop.analyse_types(env)
2704 self.step.analyse_types(env)
2705 self.start = self.start.coerce_to_pyobject(env)
2706 self.stop = self.stop.coerce_to_pyobject(env)
2707 self.step = self.step.coerce_to_pyobject(env)
2709 gil_message = "Constructing Python slice object"
2711 def generate_result_code(self, code):
2713 "%s = PySlice_New(%s, %s, %s); %s" % (
2715 self.start.py_result(),
2716 self.stop.py_result(),
2717 self.step.py_result(),
2718 code.error_goto_if_null(self.result(), self.pos)))
2719 code.put_gotref(self.py_result())
2722 class CallNode(ExprNode):
2724 # allow overriding the default 'may_be_none' behaviour
2725 may_return_none = None
2727 def may_be_none(self):
2728 if self.may_return_none is not None:
2729 return self.may_return_none
2730 return ExprNode.may_be_none(self)
2732 def analyse_as_type_constructor(self, env):
2733 type = self.function.analyse_as_type(env)
2734 if type and type.is_struct_or_union:
2735 args, kwds = self.explicit_args_kwds()
2737 for arg, member in zip(args, type.scope.var_entries):
2738 items.append(DictItemNode(pos=arg.pos, key=StringNode(pos=arg.pos, value=member.name), value=arg))
2740 items += kwds.key_value_pairs
2741 self.key_value_pairs = items
2742 self.__class__ = DictNode
2743 self.analyse_types(env)
2744 self.coerce_to(type, env)
2746 elif type and type.is_cpp_class:
2747 for arg in self.args:
2748 arg.analyse_types(env)
2749 constructor = type.scope.lookup("<init>")
2750 self.function = RawCNameExprNode(self.function.pos, constructor.type)
2751 self.function.entry = constructor
2752 self.function.set_cname(type.declaration_code(""))
2753 self.analyse_c_function_call(env)
2756 def is_lvalue(self):
2757 return self.type.is_reference
2759 def nogil_check(self, env):
2760 func_type = self.function_type()
2761 if func_type.is_pyobject:
2763 elif not getattr(func_type, 'nogil', False):
2766 gil_message = "Calling gil-requiring function"
2769 class SimpleCallNode(CallNode):
2770 # Function call without keyword, * or ** args.
2774 # arg_tuple ExprNode or None used internally
2775 # self ExprNode or None used internally
2776 # coerced_self ExprNode or None used internally
2777 # wrapper_call bool used internally
2778 # has_optional_args bool used internally
2779 # nogil bool used internally
2781 subexprs = ['self', 'coerced_self', 'function', 'args', 'arg_tuple']
2786 wrapper_call = False
2787 has_optional_args = False
2791 def compile_time_value(self, denv):
2792 function = self.function.compile_time_value(denv)
2793 args = [arg.compile_time_value(denv) for arg in self.args]
2795 return function(*args)
2796 except Exception, e:
2797 self.compile_time_value_error(e)
2799 def type_dependencies(self, env):
2800 # TODO: Update when Danilo's C++ code merged in to handle the
2801 # the case of function overloading.
2802 return self.function.type_dependencies(env)
2804 def infer_type(self, env):
2805 function = self.function
2806 func_type = function.infer_type(env)
2807 if isinstance(self.function, NewExprNode):
2808 return PyrexTypes.CPtrType(self.function.class_type)
2809 if func_type.is_ptr:
2810 func_type = func_type.base_type
2811 if func_type.is_cfunction:
2812 return func_type.return_type
2813 elif func_type is type_type:
2814 if function.is_name and function.entry and function.entry.type:
2815 result_type = function.entry.type
2816 if result_type.is_extension_type:
2818 elif result_type.is_builtin_type:
2819 if function.entry.name == 'float':
2820 return PyrexTypes.c_double_type
2821 elif function.entry.name in Builtin.types_that_construct_their_instance:
2823 return py_object_type
2825 def analyse_as_type(self, env):
2826 attr = self.function.as_cython_attribute()
2827 if attr == 'pointer':
2828 if len(self.args) != 1:
2829 error(self.args.pos, "only one type allowed.")
2831 type = self.args[0].analyse_as_type(env)
2833 error(self.args[0].pos, "Unknown type")
2835 return PyrexTypes.CPtrType(type)
2837 def explicit_args_kwds(self):
2838 return self.args, None
2840 def analyse_types(self, env):
2841 if self.analyse_as_type_constructor(env):
2845 self.analysed = True
2846 function = self.function
2847 function.is_called = 1
2848 self.function.analyse_types(env)
2849 if function.is_attribute and function.entry and function.entry.is_cmethod:
2850 # Take ownership of the object from which the attribute
2851 # was obtained, because we need to pass it as 'self'.
2852 self.self = function.obj
2853 function.obj = CloneNode(self.self)
2854 func_type = self.function_type()
2855 if func_type.is_pyobject:
2856 self.arg_tuple = TupleNode(self.pos, args = self.args)
2857 self.arg_tuple.analyse_types(env)
2859 if func_type is Builtin.type_type and function.is_name and \
2860 function.entry and \
2861 function.entry.is_builtin and \
2862 function.entry.name in Builtin.types_that_construct_their_instance:
2863 # calling a builtin type that returns a specific object type
2864 if function.entry.name == 'float':
2865 # the following will come true later on in a transform
2866 self.type = PyrexTypes.c_double_type
2867 self.result_ctype = PyrexTypes.c_double_type
2869 self.type = Builtin.builtin_types[function.entry.name]
2870 self.result_ctype = py_object_type
2871 self.may_return_none = False
2872 elif function.is_name and function.type_entry:
2873 # We are calling an extension type constructor. As
2874 # long as we do not support __new__(), the result type
2876 self.type = function.type_entry.type
2877 self.result_ctype = py_object_type
2878 self.may_return_none = False
2880 self.type = py_object_type
2883 for arg in self.args:
2884 arg.analyse_types(env)
2885 if self.self and func_type.args:
2886 # Coerce 'self' to the type expected by the method.
2887 self_arg = func_type.args[0]
2888 if self_arg.not_none: # C methods must do the None test for self at *call* time
2889 self.self = self.self.as_none_safe_node(
2890 "'NoneType' object has no attribute '%s'" % self.function.entry.name,
2891 'PyExc_AttributeError')
2892 expected_type = self_arg.type
2893 self.coerced_self = CloneNode(self.self).coerce_to(
2895 # Insert coerced 'self' argument into argument list.
2896 self.args.insert(0, self.coerced_self)
2897 self.analyse_c_function_call(env)
2899 def function_type(self):
2900 # Return the type of the function being called, coercing a function
2901 # pointer to a function if necessary.
2902 func_type = self.function.type
2903 if func_type.is_ptr:
2904 func_type = func_type.base_type
2907 def analyse_c_function_call(self, env):
2908 if self.function.type is error_type:
2909 self.type = error_type
2911 if self.function.type.is_cpp_class:
2912 overloaded_entry = self.function.type.scope.lookup("operator()")
2913 if overloaded_entry is None:
2914 self.type = PyrexTypes.error_type
2915 self.result_code = "<error>"
2917 elif hasattr(self.function, 'entry'):
2918 overloaded_entry = self.function.entry
2920 overloaded_entry = None
2921 if overloaded_entry:
2922 entry = PyrexTypes.best_match(self.args, overloaded_entry.all_alternatives(), self.pos)
2924 self.type = PyrexTypes.error_type
2925 self.result_code = "<error>"
2927 self.function.entry = entry
2928 self.function.type = entry.type
2929 func_type = self.function_type()
2931 func_type = self.function_type()
2932 if not func_type.is_cfunction:
2933 error(self.pos, "Calling non-function type '%s'" % func_type)
2934 self.type = PyrexTypes.error_type
2935 self.result_code = "<error>"
2938 max_nargs = len(func_type.args)
2939 expected_nargs = max_nargs - func_type.optional_arg_count
2940 actual_nargs = len(self.args)
2941 if func_type.optional_arg_count and expected_nargs != actual_nargs:
2942 self.has_optional_args = 1
2945 for i in range(min(max_nargs, actual_nargs)):
2946 formal_type = func_type.args[i].type
2947 self.args[i] = self.args[i].coerce_to(formal_type, env)
2948 for i in range(max_nargs, actual_nargs):
2949 if self.args[i].type.is_pyobject:
2950 error(self.args[i].pos,
2951 "Python object cannot be passed as a varargs parameter")
2952 # Calc result type and code fragment
2953 if isinstance(self.function, NewExprNode):
2954 self.type = PyrexTypes.CPtrType(self.function.class_type)
2956 self.type = func_type.return_type
2957 if self.type.is_pyobject:
2958 self.result_ctype = py_object_type
2960 elif func_type.exception_value is not None \
2961 or func_type.exception_check:
2963 # Called in 'nogil' context?
2964 self.nogil = env.nogil
2966 func_type.exception_check and
2967 func_type.exception_check != '+'):
2968 env.use_utility_code(pyerr_occurred_withgil_utility_code)
2969 # C++ exception handler
2970 if func_type.exception_check == '+':
2971 if func_type.exception_value is None:
2972 env.use_utility_code(cpp_exception_utility_code)
2974 def calculate_result_code(self):
2975 return self.c_call_code()
2977 def c_call_code(self):
2978 func_type = self.function_type()
2979 if self.type is PyrexTypes.error_type or not func_type.is_cfunction:
2981 formal_args = func_type.args
2983 args = zip(formal_args, self.args)
2984 max_nargs = len(func_type.args)
2985 expected_nargs = max_nargs - func_type.optional_arg_count
2986 actual_nargs = len(self.args)
2987 for formal_arg, actual_arg in args[:expected_nargs]:
2988 arg_code = actual_arg.result_as(formal_arg.type)
2989 arg_list_code.append(arg_code)
2991 if func_type.is_overridable:
2992 arg_list_code.append(str(int(self.wrapper_call or self.function.entry.is_unbound_cmethod)))
2994 if func_type.optional_arg_count:
2995 if expected_nargs == actual_nargs:
2996 optional_args = 'NULL'
2998 optional_args = "&%s" % self.opt_arg_struct
2999 arg_list_code.append(optional_args)
3001 for actual_arg in self.args[len(formal_args):]:
3002 arg_list_code.append(actual_arg.result())
3003 result = "%s(%s)" % (self.function.result(),
3004 ', '.join(arg_list_code))
3007 def generate_result_code(self, code):
3008 func_type = self.function_type()
3009 if func_type.is_pyobject:
3010 arg_code = self.arg_tuple.py_result()
3012 "%s = PyObject_Call(%s, %s, NULL); %s" % (
3014 self.function.py_result(),
3016 code.error_goto_if_null(self.result(), self.pos)))
3017 code.put_gotref(self.py_result())
3018 elif func_type.is_cfunction:
3019 if self.has_optional_args:
3020 actual_nargs = len(self.args)
3021 expected_nargs = len(func_type.args) - func_type.optional_arg_count
3022 self.opt_arg_struct = code.funcstate.allocate_temp(
3023 func_type.op_arg_struct.base_type, manage_ref=True)
3024 code.putln("%s.%s = %s;" % (
3025 self.opt_arg_struct,
3026 Naming.pyrex_prefix + "n",
3027 len(self.args) - expected_nargs))
3028 args = zip(func_type.args, self.args)
3029 for formal_arg, actual_arg in args[expected_nargs:actual_nargs]:
3030 code.putln("%s.%s = %s;" % (
3031 self.opt_arg_struct,
3032 func_type.opt_arg_cname(formal_arg.name),
3033 actual_arg.result_as(formal_arg.type)))
3035 if self.type.is_pyobject and self.is_temp:
3036 exc_checks.append("!%s" % self.result())
3038 exc_val = func_type.exception_value
3039 exc_check = func_type.exception_check
3040 if exc_val is not None:
3041 exc_checks.append("%s == %s" % (self.result(), exc_val))
3044 exc_checks.append("__Pyx_ErrOccurredWithGIL()")
3046 exc_checks.append("PyErr_Occurred()")
3047 if self.is_temp or exc_checks:
3048 rhs = self.c_call_code()
3050 lhs = "%s = " % self.result()
3051 if self.is_temp and self.type.is_pyobject:
3052 #return_type = self.type # func_type.return_type
3053 #print "SimpleCallNode.generate_result_code: casting", rhs, \
3054 # "from", return_type, "to pyobject" ###
3055 rhs = typecast(py_object_type, self.type, rhs)
3058 if func_type.exception_check == '+':
3059 if func_type.exception_value is None:
3060 raise_py_exception = "__Pyx_CppExn2PyErr()"
3061 elif func_type.exception_value.type.is_pyobject:
3062 raise_py_exception = ' try { throw; } catch(const std::exception& exn) { PyErr_SetString(%s, exn.what()); } catch(...) { PyErr_SetNone(%s); }' % (
3063 func_type.exception_value.entry.cname,
3064 func_type.exception_value.entry.cname)
3066 raise_py_exception = '%s(); if (!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError , "Error converting c++ exception.")' % func_type.exception_value.entry.cname
3068 raise_py_exception = 'Py_BLOCK_THREADS; %s; Py_UNBLOCK_THREADS' % raise_py_exception
3070 "try {%s%s;} catch(...) {%s; %s}" % (
3074 code.error_goto(self.pos)))
3077 goto_error = code.error_goto_if(" && ".join(exc_checks), self.pos)
3080 code.putln("%s%s; %s" % (lhs, rhs, goto_error))
3081 if self.type.is_pyobject and self.result():
3082 code.put_gotref(self.py_result())
3083 if self.has_optional_args:
3084 code.funcstate.release_temp(self.opt_arg_struct)
3087 class PythonCapiFunctionNode(ExprNode):
3089 def __init__(self, pos, py_name, cname, func_type, utility_code = None):
3093 self.type = func_type
3094 self.utility_code = utility_code
3096 def analyse_types(self, env):
3099 def generate_result_code(self, code):
3100 if self.utility_code:
3101 code.globalstate.use_utility_code(self.utility_code)
3103 def calculate_result_code(self):
3106 class PythonCapiCallNode(SimpleCallNode):
3107 # Python C-API Function call (only created in transforms)
3109 # By default, we assume that the call never returns None, as this
3110 # is true for most C-API functions in CPython. If this does not
3111 # apply to a call, set the following to True (or None to inherit
3112 # the default behaviour).
3113 may_return_none = False
3115 def __init__(self, pos, function_name, func_type,
3116 utility_code = None, py_name=None, **kwargs):
3117 self.type = func_type.return_type
3118 self.result_ctype = self.type
3119 self.function = PythonCapiFunctionNode(
3120 pos, py_name, function_name, func_type,
3121 utility_code = utility_code)
3122 # call this last so that we can override the constructed
3123 # attributes above with explicit keyword arguments if required
3124 SimpleCallNode.__init__(self, pos, **kwargs)
3127 class GeneralCallNode(CallNode):
3128 # General Python function call, including keyword,
3129 # * and ** arguments.
3132 # positional_args ExprNode Tuple of positional arguments
3133 # keyword_args ExprNode or None Dict of keyword arguments
3134 # starstar_arg ExprNode or None Dict of extra keyword args
3136 type = py_object_type
3138 subexprs = ['function', 'positional_args', 'keyword_args', 'starstar_arg']
3140 nogil_check = Node.gil_error
3142 def compile_time_value(self, denv):
3143 function = self.function.compile_time_value(denv)
3144 positional_args = self.positional_args.compile_time_value(denv)
3145 keyword_args = self.keyword_args.compile_time_value(denv)
3146 starstar_arg = self.starstar_arg.compile_time_value(denv)
3148 keyword_args.update(starstar_arg)
3149 return function(*positional_args, **keyword_args)
3150 except Exception, e:
3151 self.compile_time_value_error(e)
3153 def explicit_args_kwds(self):
3154 if self.starstar_arg or not isinstance(self.positional_args, TupleNode):
3155 raise PostParseError(self.pos,
3156 'Compile-time keyword arguments must be explicit.')
3157 return self.positional_args.args, self.keyword_args
3159 def analyse_types(self, env):
3160 if self.analyse_as_type_constructor(env):
3162 self.function.analyse_types(env)
3163 self.positional_args.analyse_types(env)
3164 if self.keyword_args:
3165 self.keyword_args.analyse_types(env)
3166 if self.starstar_arg:
3167 self.starstar_arg.analyse_types(env)
3168 if not self.function.type.is_pyobject:
3169 if self.function.type.is_error:
3170 self.type = error_type
3172 if hasattr(self.function, 'entry') and not self.function.entry.as_variable:
3173 error(self.pos, "Keyword and starred arguments not allowed in cdef functions.")
3175 self.function = self.function.coerce_to_pyobject(env)
3176 self.positional_args = \
3177 self.positional_args.coerce_to_pyobject(env)
3178 if self.starstar_arg:
3179 self.starstar_arg = \
3180 self.starstar_arg.coerce_to_pyobject(env)
3181 function = self.function
3182 if function.is_name and function.type_entry:
3183 # We are calling an extension type constructor. As long
3184 # as we do not support __new__(), the result type is clear
3185 self.type = function.type_entry.type
3186 self.result_ctype = py_object_type
3187 self.may_return_none = False
3189 self.type = py_object_type
3192 def generate_result_code(self, code):
3193 if self.type.is_error: return
3194 kwargs_call_function = "PyEval_CallObjectWithKeywords"
3195 if self.keyword_args and self.starstar_arg:
3196 code.put_error_if_neg(self.pos,
3197 "PyDict_Update(%s, %s)" % (
3198 self.keyword_args.py_result(),
3199 self.starstar_arg.py_result()))
3200 keyword_code = self.keyword_args.py_result()
3201 elif self.keyword_args:
3202 keyword_code = self.keyword_args.py_result()
3203 elif self.starstar_arg:
3204 keyword_code = self.starstar_arg.py_result()
3205 if self.starstar_arg.type is not Builtin.dict_type:
3206 # CPython supports calling functions with non-dicts, so do we
3207 code.globalstate.use_utility_code(kwargs_call_utility_code)
3208 kwargs_call_function = "__Pyx_PyEval_CallObjectWithKeywords"
3211 if not keyword_code:
3212 call_code = "PyObject_Call(%s, %s, NULL)" % (
3213 self.function.py_result(),
3214 self.positional_args.py_result())
3216 call_code = "%s(%s, %s, %s)" % (
3217 kwargs_call_function,
3218 self.function.py_result(),
3219 self.positional_args.py_result(),
3225 code.error_goto_if_null(self.result(), self.pos)))
3226 code.put_gotref(self.py_result())
3229 class AsTupleNode(ExprNode):
3230 # Convert argument to tuple. Used for normalising
3231 # the * argument of a function call.
3237 def calculate_constant_result(self):
3238 self.constant_result = tuple(self.base.constant_result)
3240 def compile_time_value(self, denv):
3241 arg = self.arg.compile_time_value(denv)
3244 except Exception, e:
3245 self.compile_time_value_error(e)
3247 def analyse_types(self, env):
3248 self.arg.analyse_types(env)
3249 self.arg = self.arg.coerce_to_pyobject(env)
3250 self.type = tuple_type
3253 def may_be_none(self):
3256 nogil_check = Node.gil_error
3257 gil_message = "Constructing Python tuple"
3259 def generate_result_code(self, code):
3261 "%s = PySequence_Tuple(%s); %s" % (
3263 self.arg.py_result(),
3264 code.error_goto_if_null(self.result(), self.pos)))
3265 code.put_gotref(self.py_result())
3268 class AttributeNode(ExprNode):
3273 # needs_none_check boolean Used if obj is an extension type.
3274 # If set to True, it is known that the type is not None.
3278 # is_py_attr boolean Is a Python getattr operation
3279 # member string C name of struct member
3280 # is_called boolean Function call is being done on result
3281 # entry Entry Symbol table entry of attribute
3286 type = PyrexTypes.error_type
3289 needs_none_check = True
3291 def as_cython_attribute(self):
3292 if isinstance(self.obj, NameNode) and self.obj.is_cython_module:
3293 return self.attribute
3294 cy = self.obj.as_cython_attribute()
3296 return "%s.%s" % (cy, self.attribute)
3298 def coerce_to(self, dst_type, env):
3299 # If coercing to a generic pyobject and this is a cpdef function
3300 # we can create the corresponding attribute
3301 if dst_type is py_object_type:
3303 if entry and entry.is_cfunction and entry.as_variable:
3304 # must be a cpdef function
3306 self.entry = entry.as_variable
3307 self.analyse_as_python_attribute(env)
3309 return ExprNode.coerce_to(self, dst_type, env)
3311 def calculate_constant_result(self):
3312 attr = self.attribute
3313 if attr.startswith("__") and attr.endswith("__"):
3315 self.constant_result = getattr(self.obj.constant_result, attr)
3317 def compile_time_value(self, denv):
3318 attr = self.attribute
3319 if attr.startswith("__") and attr.endswith("__"):
3321 "Invalid attribute name '%s' in compile-time expression" % attr)
3323 obj = self.obj.compile_time_value(denv)
3325 return getattr(obj, attr)
3326 except Exception, e:
3327 self.compile_time_value_error(e)
3329 def type_dependencies(self, env):
3330 return self.obj.type_dependencies(env)
3332 def infer_type(self, env):
3333 if self.analyse_as_cimported_attribute(env, 0):
3334 return self.entry.type
3335 elif self.analyse_as_unbound_cmethod(env):
3336 return self.entry.type
3338 self.analyse_attribute(env, obj_type = self.obj.infer_type(env))
3341 def analyse_target_declaration(self, env):
3344 def analyse_target_types(self, env):
3345 self.analyse_types(env, target = 1)
3347 def analyse_types(self, env, target = 0):
3348 if self.analyse_as_cimported_attribute(env, target):
3350 if not target and self.analyse_as_unbound_cmethod(env):
3352 self.analyse_as_ordinary_attribute(env, target)
3354 def analyse_as_cimported_attribute(self, env, target):
3355 # Try to interpret this as a reference to an imported
3356 # C const, type, var or function. If successful, mutates
3357 # this node into a NameNode and returns 1, otherwise
3359 module_scope = self.obj.analyse_as_module(env)
3361 entry = module_scope.lookup_here(self.attribute)
3363 entry.is_cglobal or entry.is_cfunction
3364 or entry.is_type or entry.is_const):
3365 self.mutate_into_name_node(env, entry, target)
3369 def analyse_as_unbound_cmethod(self, env):
3370 # Try to interpret this as a reference to an unbound
3371 # C method of an extension type. If successful, mutates
3372 # this node into a NameNode and returns 1, otherwise
3374 type = self.obj.analyse_as_extension_type(env)
3376 entry = type.scope.lookup_here(self.attribute)
3377 if entry and entry.is_cmethod:
3378 # Create a temporary entry describing the C method
3379 # as an ordinary function.
3380 ubcm_entry = Symtab.Entry(entry.name,
3381 "%s->%s" % (type.vtabptr_cname, entry.cname),
3383 ubcm_entry.is_cfunction = 1
3384 ubcm_entry.func_cname = entry.func_cname
3385 ubcm_entry.is_unbound_cmethod = 1
3386 self.mutate_into_name_node(env, ubcm_entry, None)
3390 def analyse_as_type(self, env):
3391 module_scope = self.obj.analyse_as_module(env)
3393 return module_scope.lookup_type(self.attribute)
3394 if not isinstance(self.obj, (UnicodeNode, StringNode, BytesNode)):
3395 base_type = self.obj.analyse_as_type(env)
3396 if base_type and hasattr(base_type, 'scope'):
3397 return base_type.scope.lookup_type(self.attribute)
3400 def analyse_as_extension_type(self, env):
3401 # Try to interpret this as a reference to an extension type
3402 # in a cimported module. Returns the extension type, or None.
3403 module_scope = self.obj.analyse_as_module(env)
3405 entry = module_scope.lookup_here(self.attribute)
3406 if entry and entry.is_type and entry.type.is_extension_type:
3410 def analyse_as_module(self, env):
3411 # Try to interpret this as a reference to a cimported module
3412 # in another cimported module. Returns the module scope, or None.
3413 module_scope = self.obj.analyse_as_module(env)
3415 entry = module_scope.lookup_here(self.attribute)
3416 if entry and entry.as_module:
3417 return entry.as_module
3420 def mutate_into_name_node(self, env, entry, target):
3421 # Mutate this node into a NameNode and complete the
3422 # analyse_types phase.
3423 self.__class__ = NameNode
3424 self.name = self.attribute
3429 NameNode.analyse_target_types(self, env)
3431 NameNode.analyse_rvalue_entry(self, env)
3433 def analyse_as_ordinary_attribute(self, env, target):
3434 self.obj.analyse_types(env)
3435 self.analyse_attribute(env)
3436 if self.entry and self.entry.is_cmethod and not self.is_called:
3437 # error(self.pos, "C method can only be called")
3439 ## Reference to C array turns into pointer to first element.
3440 #while self.type.is_array:
3441 # self.type = self.type.element_ptr_type()
3445 self.result_ctype = py_object_type
3447 def analyse_attribute(self, env, obj_type = None):
3448 # Look up attribute and set self.type and self.member.
3450 self.member = self.attribute
3451 if obj_type is None:
3452 if self.obj.type.is_string:
3453 self.obj = self.obj.coerce_to_pyobject(env)
3454 obj_type = self.obj.type
3456 if obj_type.is_string:
3457 obj_type = py_object_type
3458 if obj_type.is_ptr or obj_type.is_array:
3459 obj_type = obj_type.base_type
3461 elif obj_type.is_extension_type:
3465 if obj_type.has_attributes:
3467 if obj_type.attributes_known():
3468 entry = obj_type.scope.lookup_here(self.attribute)
3469 if entry and entry.is_member:
3473 "Cannot select attribute of incomplete type '%s'"
3475 self.type = PyrexTypes.error_type
3479 if obj_type.is_extension_type and entry.name == "__weakref__":
3480 error(self.pos, "Illegal use of special attribute __weakref__")
3481 # methods need the normal attribute lookup
3482 # because they do not have struct entries
3483 if entry.is_variable or entry.is_cmethod:
3484 self.type = entry.type
3485 self.member = entry.cname
3488 # If it's not a variable or C method, it must be a Python
3489 # method of an extension type, so we treat it like a Python
3492 # If we get here, the base object is not a struct/union/extension
3493 # type, or it is an extension type and the attribute is either not
3494 # declared or is declared as a Python method. Treat it as a Python
3495 # attribute reference.
3496 self.analyse_as_python_attribute(env, obj_type)
3498 def analyse_as_python_attribute(self, env, obj_type = None):
3499 if obj_type is None:
3500 obj_type = self.obj.type
3501 self.member = self.attribute
3502 self.type = py_object_type
3504 if not obj_type.is_pyobject and not obj_type.is_error:
3505 if obj_type.can_coerce_to_pyobject(env):
3506 self.obj = self.obj.coerce_to_pyobject(env)
3509 "Object of type '%s' has no attribute '%s'" %
3510 (obj_type, self.attribute))
3512 def nogil_check(self, env):
3516 gil_message = "Accessing Python attribute"
3518 def is_simple(self):
3520 return self.result_in_temp() or self.obj.is_simple()
3522 return NameNode.is_simple(self)
3524 def is_lvalue(self):
3528 return NameNode.is_lvalue(self)
3530 def is_ephemeral(self):
3532 return self.obj.is_ephemeral()
3534 return NameNode.is_ephemeral(self)
3536 def calculate_result_code(self):
3537 #print "AttributeNode.calculate_result_code:", self.member ###
3538 #print "...obj node =", self.obj, "code", self.obj.result() ###
3539 #print "...obj type", self.obj.type, "ctype", self.obj.ctype() ###
3541 obj_code = obj.result_as(obj.type)
3542 #print "...obj_code =", obj_code ###
3543 if self.entry and self.entry.is_cmethod:
3544 if obj.type.is_extension_type:
3545 return "((struct %s *)%s%s%s)->%s" % (
3546 obj.type.vtabstruct_cname, obj_code, self.op,
3547 obj.type.vtabslot_cname, self.member)
3550 elif obj.type.is_complex:
3551 return "__Pyx_C%s(%s)" % (self.member.upper(), obj_code)
3553 return "%s%s%s" % (obj_code, self.op, self.member)
3555 def generate_result_code(self, code):
3556 interned_attr_cname = code.intern_identifier(self.attribute)
3559 '%s = PyObject_GetAttr(%s, %s); %s' % (
3561 self.obj.py_result(),
3562 interned_attr_cname,
3563 code.error_goto_if_null(self.result(), self.pos)))
3564 code.put_gotref(self.py_result())
3566 # result_code contains what is needed, but we may need to insert
3567 # a check and raise an exception
3568 if (self.obj.type.is_extension_type
3569 and self.needs_none_check
3570 and code.globalstate.directives['nonecheck']):
3571 self.put_nonecheck(code)
3573 def generate_assignment_code(self, rhs, code):
3574 interned_attr_cname = code.intern_identifier(self.attribute)
3575 self.obj.generate_evaluation_code(code)
3577 code.put_error_if_neg(self.pos,
3578 'PyObject_SetAttr(%s, %s, %s)' % (
3579 self.obj.py_result(),
3580 interned_attr_cname,
3582 rhs.generate_disposal_code(code)
3583 rhs.free_temps(code)
3584 elif self.obj.type.is_complex:
3585 code.putln("__Pyx_SET_C%s(%s, %s);" % (
3586 self.member.upper(),
3587 self.obj.result_as(self.obj.type),
3588 rhs.result_as(self.ctype())))
3590 if (self.obj.type.is_extension_type
3591 and self.needs_none_check
3592 and code.globalstate.directives['nonecheck']):
3593 self.put_nonecheck(code)
3595 select_code = self.result()
3596 if self.type.is_pyobject and self.use_managed_ref:
3597 rhs.make_owned_reference(code)
3598 code.put_giveref(rhs.py_result())
3599 code.put_gotref(select_code)
3600 code.put_decref(select_code, self.ctype())
3604 rhs.result_as(self.ctype())))
3606 rhs.generate_post_assignment_code(code)
3607 rhs.free_temps(code)
3608 self.obj.generate_disposal_code(code)
3609 self.obj.free_temps(code)
3611 def generate_deletion_code(self, code):
3612 interned_attr_cname = code.intern_identifier(self.attribute)
3613 self.obj.generate_evaluation_code(code)
3614 if self.is_py_attr or (isinstance(self.entry.scope, Symtab.PropertyScope)
3615 and self.entry.scope.entries.has_key(u'__del__')):
3616 code.put_error_if_neg(self.pos,
3617 'PyObject_DelAttr(%s, %s)' % (
3618 self.obj.py_result(),
3619 interned_attr_cname))
3621 error(self.pos, "Cannot delete C attribute of extension type")
3622 self.obj.generate_disposal_code(code)
3623 self.obj.free_temps(code)
3625 def annotate(self, code):
3627 code.annotate(self.pos, AnnotationItem('py_attr', 'python attribute', size=len(self.attribute)))
3629 code.annotate(self.pos, AnnotationItem('c_attr', 'c attribute', size=len(self.attribute)))
3631 def put_nonecheck(self, code):
3632 code.globalstate.use_utility_code(raise_noneattr_error_utility_code)
3633 code.putln("if (%s) {" % code.unlikely("%s == Py_None") % self.obj.result_as(PyrexTypes.py_object_type))
3634 code.putln("__Pyx_RaiseNoneAttributeError(\"%s\");" % self.attribute)
3635 code.putln(code.error_goto(self.pos))
3639 #-------------------------------------------------------------------
3643 #-------------------------------------------------------------------
3645 class StarredTargetNode(ExprNode):
3646 # A starred expression like "*a"
3648 # This is only allowed in sequence assignment targets such as
3650 # a, *b = (1,2,3,4) => a = 1 ; b = [2,3,4]
3652 # and will be removed during type analysis (or generate an error
3653 # if it's found at unexpected places).
3657 subexprs = ['target']
3659 type = py_object_type
3662 def __init__(self, pos, target):
3664 self.target = target
3666 def analyse_declarations(self, env):
3667 error(self.pos, "can use starred expression only as assignment target")
3668 self.target.analyse_declarations(env)
3670 def analyse_types(self, env):
3671 error(self.pos, "can use starred expression only as assignment target")
3672 self.target.analyse_types(env)
3673 self.type = self.target.type
3675 def analyse_target_declaration(self, env):
3676 self.target.analyse_target_declaration(env)
3678 def analyse_target_types(self, env):
3679 self.target.analyse_target_types(env)
3680 self.type = self.target.type
3682 def calculate_result_code(self):
3685 def generate_result_code(self, code):
3689 class SequenceNode(ExprNode):
3690 # Base class for list and tuple constructor nodes.
3691 # Contains common code for performing sequence unpacking.
3695 # unpacked_items [ExprNode] or None
3696 # coerced_unpacked_items [ExprNode] or None
3700 is_sequence_constructor = 1
3701 unpacked_items = None
3703 def compile_time_value_list(self, denv):
3704 return [arg.compile_time_value(denv) for arg in self.args]
3706 def replace_starred_target_node(self):
3707 # replace a starred node in the targets by the contained expression
3708 self.starred_assignment = False
3710 for arg in self.args:
3712 if self.starred_assignment:
3713 error(arg.pos, "more than 1 starred expression in assignment")
3714 self.starred_assignment = True
3716 arg.is_starred = True
3720 def analyse_target_declaration(self, env):
3721 self.replace_starred_target_node()
3722 for arg in self.args:
3723 arg.analyse_target_declaration(env)
3725 def analyse_types(self, env, skip_children=False):
3726 for i in range(len(self.args)):
3728 if not skip_children: arg.analyse_types(env)
3729 self.args[i] = arg.coerce_to_pyobject(env)
3731 # not setting self.type here, subtypes do this
3733 def may_be_none(self):
3736 def analyse_target_types(self, env):
3737 self.iterator = PyTempNode(self.pos, env)
3738 self.unpacked_items = []
3739 self.coerced_unpacked_items = []
3740 for arg in self.args:
3741 arg.analyse_target_types(env)
3743 if not arg.type.assignable_from(Builtin.list_type):
3745 "starred target must have Python object (list) type")
3746 if arg.type is py_object_type:
3747 arg.type = Builtin.list_type
3748 unpacked_item = PyTempNode(self.pos, env)
3749 coerced_unpacked_item = unpacked_item.coerce_to(arg.type, env)
3750 self.unpacked_items.append(unpacked_item)
3751 self.coerced_unpacked_items.append(coerced_unpacked_item)
3752 self.type = py_object_type
3754 def generate_result_code(self, code):
3755 self.generate_operation_code(code)
3757 def generate_assignment_code(self, rhs, code):
3758 if self.starred_assignment:
3759 self.generate_starred_assignment_code(rhs, code)
3761 self.generate_parallel_assignment_code(rhs, code)
3763 for item in self.unpacked_items:
3765 rhs.free_temps(code)
3767 def generate_parallel_assignment_code(self, rhs, code):
3768 # Need to work around the fact that generate_evaluation_code
3769 # allocates the temps in a rather hacky way -- the assignment
3770 # is evaluated twice, within each if-block.
3772 if rhs.type is tuple_type:
3773 tuple_check = "likely(%s != Py_None)"
3775 tuple_check = "PyTuple_CheckExact(%s)"
3777 "if (%s && likely(PyTuple_GET_SIZE(%s) == %s)) {" % (
3778 tuple_check % rhs.py_result(),
3781 code.putln("PyObject* tuple = %s;" % rhs.py_result())
3782 for item in self.unpacked_items:
3784 for i in range(len(self.args)):
3785 item = self.unpacked_items[i]
3787 "%s = PyTuple_GET_ITEM(tuple, %s); " % (
3790 code.put_incref(item.result(), item.ctype())
3791 value_node = self.coerced_unpacked_items[i]
3792 value_node.generate_evaluation_code(code)
3793 rhs.generate_disposal_code(code)
3795 for i in range(len(self.args)):
3796 self.args[i].generate_assignment_code(
3797 self.coerced_unpacked_items[i], code)
3799 code.putln("} else {")
3801 if rhs.type is tuple_type:
3802 code.globalstate.use_utility_code(tuple_unpacking_error_code)
3803 code.putln("__Pyx_UnpackTupleError(%s, %s);" % (
3804 rhs.py_result(), len(self.args)))
3805 code.putln(code.error_goto(self.pos))
3807 code.globalstate.use_utility_code(unpacking_utility_code)
3809 self.iterator.allocate(code)
3811 "%s = PyObject_GetIter(%s); %s" % (
3812 self.iterator.result(),
3814 code.error_goto_if_null(self.iterator.result(), self.pos)))
3815 code.put_gotref(self.iterator.py_result())
3816 rhs.generate_disposal_code(code)
3817 for i in range(len(self.args)):
3818 item = self.unpacked_items[i]
3819 unpack_code = "__Pyx_UnpackItem(%s, %d)" % (
3820 self.iterator.py_result(), i)
3824 typecast(item.ctype(), py_object_type, unpack_code),
3825 code.error_goto_if_null(item.result(), self.pos)))
3826 code.put_gotref(item.py_result())
3827 value_node = self.coerced_unpacked_items[i]
3828 value_node.generate_evaluation_code(code)
3829 code.put_error_if_neg(self.pos, "__Pyx_EndUnpack(%s, %d)" % (
3830 self.iterator.py_result(),
3832 if debug_disposal_code:
3833 print("UnpackNode.generate_assignment_code:")
3834 print("...generating disposal code for %s" % self.iterator)
3835 self.iterator.generate_disposal_code(code)
3836 self.iterator.free_temps(code)
3837 self.iterator.release(code)
3839 for i in range(len(self.args)):
3840 self.args[i].generate_assignment_code(
3841 self.coerced_unpacked_items[i], code)
3845 def generate_starred_assignment_code(self, rhs, code):
3846 code.globalstate.use_utility_code(unpacking_utility_code)
3848 for i, arg in enumerate(self.args):
3850 starred_target = self.unpacked_items[i]
3851 fixed_args_left = self.args[:i]
3852 fixed_args_right = self.args[i+1:]
3855 self.iterator.allocate(code)
3857 "%s = PyObject_GetIter(%s); %s" % (
3858 self.iterator.result(),
3860 code.error_goto_if_null(self.iterator.result(), self.pos)))
3861 code.put_gotref(self.iterator.py_result())
3862 rhs.generate_disposal_code(code)
3864 for item in self.unpacked_items:
3866 for i in range(len(fixed_args_left)):
3867 item = self.unpacked_items[i]
3868 unpack_code = "__Pyx_UnpackItem(%s, %d)" % (
3869 self.iterator.py_result(), i)
3873 typecast(item.ctype(), py_object_type, unpack_code),
3874 code.error_goto_if_null(item.result(), self.pos)))
3875 code.put_gotref(item.py_result())
3876 value_node = self.coerced_unpacked_items[i]
3877 value_node.generate_evaluation_code(code)
3879 target_list = starred_target.result()
3880 code.putln("%s = PySequence_List(%s); %s" % (
3881 target_list, self.iterator.py_result(),
3882 code.error_goto_if_null(target_list, self.pos)))
3883 code.put_gotref(target_list)
3884 if fixed_args_right:
3885 code.globalstate.use_utility_code(raise_need_more_values_to_unpack)
3886 unpacked_right_args = self.unpacked_items[-len(fixed_args_right):]
3887 code.putln("if (unlikely(PyList_GET_SIZE(%s) < %d)) {" % (
3888 (target_list, len(unpacked_right_args))))
3889 code.put("__Pyx_RaiseNeedMoreValuesError(%d+PyList_GET_SIZE(%s)); %s" % (
3890 len(fixed_args_left), target_list,
3891 code.error_goto(self.pos)))
3893 for i, (arg, coerced_arg) in enumerate(zip(unpacked_right_args[::-1],
3894 self.coerced_unpacked_items[::-1])):
3896 "%s = PyList_GET_ITEM(%s, PyList_GET_SIZE(%s)-1); " % (
3898 target_list, target_list))
3899 # resize the list the hard way
3900 code.putln("((PyVarObject*)%s)->ob_size--;" % target_list)
3901 code.put_gotref(arg.py_result())
3902 coerced_arg.generate_evaluation_code(code)
3904 self.iterator.generate_disposal_code(code)
3905 self.iterator.free_temps(code)
3906 self.iterator.release(code)
3908 for i in range(len(self.args)):
3909 self.args[i].generate_assignment_code(
3910 self.coerced_unpacked_items[i], code)
3912 def annotate(self, code):
3913 for arg in self.args:
3915 if self.unpacked_items:
3916 for arg in self.unpacked_items:
3918 for arg in self.coerced_unpacked_items:
3922 class TupleNode(SequenceNode):
3923 # Tuple constructor.
3927 gil_message = "Constructing Python tuple"
3929 def analyse_types(self, env, skip_children=False):
3930 if len(self.args) == 0:
3934 SequenceNode.analyse_types(self, env, skip_children)
3935 for child in self.args:
3936 if not child.is_literal:
3942 def calculate_result_code(self):
3943 if len(self.args) > 0:
3944 return self.result_code
3946 return Naming.empty_tuple
3948 def calculate_constant_result(self):
3949 self.constant_result = tuple([
3950 arg.constant_result for arg in self.args])
3952 def compile_time_value(self, denv):
3953 values = self.compile_time_value_list(denv)
3955 return tuple(values)
3956 except Exception, e:
3957 self.compile_time_value_error(e)
3959 def generate_operation_code(self, code):
3960 if len(self.args) == 0:
3961 # result_code is Naming.empty_tuple
3964 # non-empty cached tuple => result is global constant,
3965 # creation code goes into separate code writer
3966 self.result_code = code.get_py_const(py_object_type, 'tuple_', cleanup_level=2)
3967 code = code.get_cached_constants_writer()
3968 code.mark_pos(self.pos)
3971 "%s = PyTuple_New(%s); %s" % (
3974 code.error_goto_if_null(self.result(), self.pos)))
3975 code.put_gotref(self.py_result())
3976 for i in range(len(self.args)):
3978 if not arg.result_in_temp():
3979 code.put_incref(arg.result(), arg.ctype())
3981 "PyTuple_SET_ITEM(%s, %s, %s);" % (
3985 code.put_giveref(arg.py_result())
3987 code.put_giveref(self.py_result())
3989 def generate_subexpr_disposal_code(self, code):
3990 # We call generate_post_assignment_code here instead
3991 # of generate_disposal_code, because values were stored
3992 # in the tuple using a reference-stealing operation.
3993 for arg in self.args:
3994 arg.generate_post_assignment_code(code)
3995 # Should NOT call free_temps -- this is invoked by the default
3996 # generate_evaluation_code which will do that.
3999 class ListNode(SequenceNode):
4002 # obj_conversion_errors [PyrexError] used internally
4003 # orignial_args [ExprNode] used internally
4005 obj_conversion_errors = []
4008 gil_message = "Constructing Python list"
4010 def type_dependencies(self, env):
4013 def infer_type(self, env):
4014 # TOOD: Infer non-object list arrays.
4017 def analyse_expressions(self, env):
4018 SequenceNode.analyse_expressions(self, env)
4019 self.coerce_to_pyobject(env)
4021 def analyse_types(self, env):
4023 self.original_args = list(self.args)
4024 SequenceNode.analyse_types(self, env)
4025 self.obj_conversion_errors = held_errors()
4026 release_errors(ignore=True)
4028 def coerce_to(self, dst_type, env):
4029 if dst_type.is_pyobject:
4030 for err in self.obj_conversion_errors:
4032 self.obj_conversion_errors = []
4033 if not self.type.subtype_of(dst_type):
4034 error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
4035 elif dst_type.is_ptr:
4036 base_type = dst_type.base_type
4037 self.type = PyrexTypes.CArrayType(base_type, len(self.args))
4038 for i in range(len(self.original_args)):
4040 if isinstance(arg, CoerceToPyTypeNode):
4042 self.args[i] = arg.coerce_to(base_type, env)
4043 elif dst_type.is_struct:
4044 if len(self.args) > len(dst_type.scope.var_entries):
4045 error(self.pos, "Too may members for '%s'" % dst_type)
4047 if len(self.args) < len(dst_type.scope.var_entries):
4048 warning(self.pos, "Too few members for '%s'" % dst_type, 1)
4049 for i, (arg, member) in enumerate(zip(self.original_args, dst_type.scope.var_entries)):
4050 if isinstance(arg, CoerceToPyTypeNode):
4052 self.args[i] = arg.coerce_to(member.type, env)
4053 self.type = dst_type
4055 self.type = error_type
4056 error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
4059 def release_temp(self, env):
4060 if self.type.is_array:
4061 # To be valid C++, we must allocate the memory on the stack
4062 # manually and be sure not to reuse it for something else.
4065 SequenceNode.release_temp(self, env)
4067 def calculate_constant_result(self):
4068 self.constant_result = [
4069 arg.constant_result for arg in self.args]
4071 def compile_time_value(self, denv):
4072 return self.compile_time_value_list(denv)
4074 def generate_operation_code(self, code):
4075 if self.type.is_pyobject:
4076 for err in self.obj_conversion_errors:
4078 code.putln("%s = PyList_New(%s); %s" %
4081 code.error_goto_if_null(self.result(), self.pos)))
4082 code.put_gotref(self.py_result())
4083 for i in range(len(self.args)):
4085 #if not arg.is_temp:
4086 if not arg.result_in_temp():
4087 code.put_incref(arg.result(), arg.ctype())
4088 code.putln("PyList_SET_ITEM(%s, %s, %s);" %
4092 code.put_giveref(arg.py_result())
4093 elif self.type.is_array:
4094 for i, arg in enumerate(self.args):
4095 code.putln("%s[%s] = %s;" % (
4099 elif self.type.is_struct:
4100 for arg, member in zip(self.args, self.type.scope.var_entries):
4101 code.putln("%s.%s = %s;" % (
4106 raise InternalError("List type never specified")
4108 def generate_subexpr_disposal_code(self, code):
4109 # We call generate_post_assignment_code here instead
4110 # of generate_disposal_code, because values were stored
4111 # in the list using a reference-stealing operation.
4112 for arg in self.args:
4113 arg.generate_post_assignment_code(code)
4114 # Should NOT call free_temps -- this is invoked by the default
4115 # generate_evaluation_code which will do that.
4118 class ScopedExprNode(ExprNode):
4119 # Abstract base class for ExprNodes that have their own local
4120 # scope, such as generator expressions.
4122 # expr_scope Scope the inner scope of the expression
4127 def analyse_types(self, env):
4128 # nothing to do here, the children will be analysed separately
4131 def analyse_expressions(self, env):
4132 # nothing to do here, the children will be analysed separately
4135 def analyse_scoped_expressions(self, env):
4136 # this is called with the expr_scope as env
4139 def init_scope(self, outer_scope, expr_scope=None):
4140 self.expr_scope = expr_scope
4143 class ComprehensionNode(ScopedExprNode):
4144 subexprs = ["target"]
4145 child_attrs = ["loop", "append"]
4147 # leak loop variables or not? non-leaking Py3 behaviour is
4148 # default, except for list comprehensions where the behaviour
4149 # differs in Py2 and Py3 (see Parsing.py)
4150 has_local_scope = True
4152 def infer_type(self, env):
4153 return self.target.infer_type(env)
4155 def analyse_declarations(self, env):
4156 self.append.target = self # this is used in the PyList_Append of the inner loop
4157 self.init_scope(env)
4158 self.loop.analyse_declarations(self.expr_scope or env)
4160 def init_scope(self, outer_scope, expr_scope=None):
4161 if expr_scope is not None:
4162 self.expr_scope = expr_scope
4163 elif self.has_local_scope:
4164 self.expr_scope = Symtab.GeneratorExpressionScope(outer_scope)
4166 self.expr_scope = None
4168 def analyse_types(self, env):
4169 self.target.analyse_expressions(env)
4170 self.type = self.target.type
4171 if not self.has_local_scope:
4172 self.loop.analyse_expressions(env)
4174 def analyse_expressions(self, env):
4175 self.analyse_types(env)
4177 def analyse_scoped_expressions(self, env):
4178 if self.has_local_scope:
4179 self.loop.analyse_expressions(env)
4181 def may_be_none(self):
4184 def calculate_result_code(self):
4185 return self.target.result()
4187 def generate_result_code(self, code):
4188 self.generate_operation_code(code)
4190 def generate_operation_code(self, code):
4191 self.loop.generate_execution_code(code)
4193 def annotate(self, code):
4194 self.loop.annotate(code)
4197 class ComprehensionAppendNode(Node):
4198 # Need to be careful to avoid infinite recursion:
4199 # target must not be in child_attrs/subexprs
4201 child_attrs = ['expr']
4203 type = PyrexTypes.c_int_type
4205 def analyse_expressions(self, env):
4206 self.expr.analyse_expressions(env)
4207 if not self.expr.type.is_pyobject:
4208 self.expr = self.expr.coerce_to_pyobject(env)
4210 def generate_execution_code(self, code):
4211 if self.target.type is list_type:
4212 function = "PyList_Append"
4213 elif self.target.type is set_type:
4214 function = "PySet_Add"
4216 raise InternalError(
4217 "Invalid type for comprehension node: %s" % self.target.type)
4219 self.expr.generate_evaluation_code(code)
4220 code.putln(code.error_goto_if("%s(%s, (PyObject*)%s)" % (
4222 self.target.result(),
4225 self.expr.generate_disposal_code(code)
4226 self.expr.free_temps(code)
4228 def generate_function_definitions(self, env, code):
4229 self.expr.generate_function_definitions(env, code)
4231 def annotate(self, code):
4232 self.expr.annotate(code)
4234 class DictComprehensionAppendNode(ComprehensionAppendNode):
4235 child_attrs = ['key_expr', 'value_expr']
4237 def analyse_expressions(self, env):
4238 self.key_expr.analyse_expressions(env)
4239 if not self.key_expr.type.is_pyobject:
4240 self.key_expr = self.key_expr.coerce_to_pyobject(env)
4241 self.value_expr.analyse_expressions(env)
4242 if not self.value_expr.type.is_pyobject:
4243 self.value_expr = self.value_expr.coerce_to_pyobject(env)
4245 def generate_execution_code(self, code):
4246 self.key_expr.generate_evaluation_code(code)
4247 self.value_expr.generate_evaluation_code(code)
4248 code.putln(code.error_goto_if("PyDict_SetItem(%s, (PyObject*)%s, (PyObject*)%s)" % (
4249 self.target.result(),
4250 self.key_expr.result(),
4251 self.value_expr.result()
4253 self.key_expr.generate_disposal_code(code)
4254 self.key_expr.free_temps(code)
4255 self.value_expr.generate_disposal_code(code)
4256 self.value_expr.free_temps(code)
4258 def generate_function_definitions(self, env, code):
4259 self.key_expr.generate_function_definitions(env, code)
4260 self.value_expr.generate_function_definitions(env, code)
4262 def annotate(self, code):
4263 self.key_expr.annotate(code)
4264 self.value_expr.annotate(code)
4267 class GeneratorExpressionNode(ScopedExprNode):
4268 # A generator expression, e.g. (i for i in range(10))
4270 # Result is a generator.
4272 # loop ForStatNode the for-loop, containing a YieldExprNode
4274 child_attrs = ["loop"]
4276 type = py_object_type
4278 def analyse_declarations(self, env):
4279 self.init_scope(env)
4280 self.loop.analyse_declarations(self.expr_scope)
4282 def init_scope(self, outer_scope, expr_scope=None):
4283 if expr_scope is not None:
4284 self.expr_scope = expr_scope
4286 self.expr_scope = Symtab.GeneratorExpressionScope(outer_scope)
4288 def analyse_types(self, env):
4291 def analyse_scoped_expressions(self, env):
4292 self.loop.analyse_expressions(env)
4294 def may_be_none(self):
4297 def annotate(self, code):
4298 self.loop.annotate(code)
4301 class InlinedGeneratorExpressionNode(GeneratorExpressionNode):
4302 # An inlined generator expression for which the result is
4303 # calculated inside of the loop. This will only be created by
4304 # transforms when replacing builtin calls on generator
4307 # loop ForStatNode the for-loop, not containing any YieldExprNodes
4308 # result_node ResultRefNode the reference to the result value temp
4309 # orig_func String the name of the builtin function this node replaces
4311 child_attrs = ["loop"]
4313 def analyse_types(self, env):
4314 self.type = self.result_node.type
4317 def coerce_to(self, dst_type, env):
4318 if self.orig_func == 'sum' and dst_type.is_numeric:
4319 # we can optimise by dropping the aggregation variable into C
4320 self.result_node.type = self.type = dst_type
4322 return GeneratorExpressionNode.coerce_to(self, dst_type, env)
4324 def generate_result_code(self, code):
4325 self.result_node.result_code = self.result()
4326 self.loop.generate_execution_code(code)
4329 class SetNode(ExprNode):
4336 gil_message = "Constructing Python set"
4338 def analyse_types(self, env):
4339 for i in range(len(self.args)):
4341 arg.analyse_types(env)
4342 self.args[i] = arg.coerce_to_pyobject(env)
4343 self.type = set_type
4346 def may_be_none(self):
4349 def calculate_constant_result(self):
4350 self.constant_result = set([
4351 arg.constant_result for arg in self.args])
4353 def compile_time_value(self, denv):
4354 values = [arg.compile_time_value(denv) for arg in self.args]
4357 except Exception, e:
4358 self.compile_time_value_error(e)
4360 def generate_evaluation_code(self, code):
4361 code.globalstate.use_utility_code(Builtin.py23_set_utility_code)
4362 self.allocate_temp_result(code)
4364 "%s = PySet_New(0); %s" % (
4366 code.error_goto_if_null(self.result(), self.pos)))
4367 code.put_gotref(self.py_result())
4368 for arg in self.args:
4369 arg.generate_evaluation_code(code)
4371 code.error_goto_if_neg(
4372 "PySet_Add(%s, %s)" % (self.result(), arg.py_result()),
4374 arg.generate_disposal_code(code)
4375 arg.free_temps(code)
4378 class DictNode(ExprNode):
4379 # Dictionary constructor.
4381 # key_value_pairs [DictItemNode]
4383 # obj_conversion_errors [PyrexError] used internally
4385 subexprs = ['key_value_pairs']
4389 obj_conversion_errors = []
4391 def calculate_constant_result(self):
4392 self.constant_result = dict([
4393 item.constant_result for item in self.key_value_pairs])
4395 def compile_time_value(self, denv):
4396 pairs = [(item.key.compile_time_value(denv), item.value.compile_time_value(denv))
4397 for item in self.key_value_pairs]
4400 except Exception, e:
4401 self.compile_time_value_error(e)
4403 def type_dependencies(self, env):
4406 def infer_type(self, env):
4407 # TOOD: Infer struct constructors.
4410 def analyse_types(self, env):
4412 for item in self.key_value_pairs:
4413 item.analyse_types(env)
4414 self.obj_conversion_errors = held_errors()
4415 release_errors(ignore=True)
4417 def may_be_none(self):
4420 def coerce_to(self, dst_type, env):
4421 if dst_type.is_pyobject:
4422 self.release_errors()
4423 if not self.type.subtype_of(dst_type):
4424 error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
4425 elif dst_type.is_struct_or_union:
4426 self.type = dst_type
4427 if not dst_type.is_struct and len(self.key_value_pairs) != 1:
4428 error(self.pos, "Exactly one field must be specified to convert to union '%s'" % dst_type)
4429 elif dst_type.is_struct and len(self.key_value_pairs) < len(dst_type.scope.var_entries):
4430 warning(self.pos, "Not all members given for struct '%s'" % dst_type, 1)
4431 for item in self.key_value_pairs:
4432 if isinstance(item.key, CoerceToPyTypeNode):
4433 item.key = item.key.arg
4434 if not isinstance(item.key, (UnicodeNode, StringNode, BytesNode)):
4435 error(item.key.pos, "Invalid struct field identifier")
4436 item.key = StringNode(item.key.pos, value="<error>")
4438 key = str(item.key.value) # converts string literals to unicode in Py3
4439 member = dst_type.scope.lookup_here(key)
4441 error(item.key.pos, "struct '%s' has no field '%s'" % (dst_type, key))
4444 if isinstance(value, CoerceToPyTypeNode):
4446 item.value = value.coerce_to(member.type, env)
4448 self.type = error_type
4449 error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
4452 def release_errors(self):
4453 for err in self.obj_conversion_errors:
4455 self.obj_conversion_errors = []
4457 gil_message = "Constructing Python dict"
4459 def generate_evaluation_code(self, code):
4460 # Custom method used here because key-value
4461 # pairs are evaluated and used one at a time.
4462 code.mark_pos(self.pos)
4463 self.allocate_temp_result(code)
4464 if self.type.is_pyobject:
4465 self.release_errors()
4467 "%s = PyDict_New(); %s" % (
4469 code.error_goto_if_null(self.result(), self.pos)))
4470 code.put_gotref(self.py_result())
4471 for item in self.key_value_pairs:
4472 item.generate_evaluation_code(code)
4473 if self.type.is_pyobject:
4474 code.put_error_if_neg(self.pos,
4475 "PyDict_SetItem(%s, %s, %s)" % (
4477 item.key.py_result(),
4478 item.value.py_result()))
4480 code.putln("%s.%s = %s;" % (
4483 item.value.result()))
4484 item.generate_disposal_code(code)
4485 item.free_temps(code)
4487 def annotate(self, code):
4488 for item in self.key_value_pairs:
4491 class DictItemNode(ExprNode):
4492 # Represents a single item in a DictNode
4496 subexprs = ['key', 'value']
4498 nogil_check = None # Parent DictNode takes care of it
4500 def calculate_constant_result(self):
4501 self.constant_result = (
4502 self.key.constant_result, self.value.constant_result)
4504 def analyse_types(self, env):
4505 self.key.analyse_types(env)
4506 self.value.analyse_types(env)
4507 self.key = self.key.coerce_to_pyobject(env)
4508 self.value = self.value.coerce_to_pyobject(env)
4510 def generate_evaluation_code(self, code):
4511 self.key.generate_evaluation_code(code)
4512 self.value.generate_evaluation_code(code)
4514 def generate_disposal_code(self, code):
4515 self.key.generate_disposal_code(code)
4516 self.value.generate_disposal_code(code)
4518 def free_temps(self, code):
4519 self.key.free_temps(code)
4520 self.value.free_temps(code)
4523 return iter([self.key, self.value])
4525 class ModuleNameMixin(object):
4526 def set_mod_name(self, env):
4527 self.module_name = env.global_scope().qualified_name
4529 def get_py_mod_name(self, code):
4530 return code.get_py_string_const(
4531 self.module_name, identifier=True)
4533 class ClassNode(ExprNode, ModuleNameMixin):
4534 # Helper class used in the implementation of Python
4535 # class definitions. Constructs a class object given
4536 # a name, tuple of bases and class dictionary.
4538 # name EncodedString Name of the class
4539 # bases ExprNode Base class tuple
4540 # dict ExprNode Class dict (not owned by this node)
4541 # doc ExprNode or None Doc string
4542 # module_name EncodedString Name of defining module
4544 subexprs = ['bases', 'doc']
4546 def analyse_types(self, env):
4547 self.bases.analyse_types(env)
4549 self.doc.analyse_types(env)
4550 self.doc = self.doc.coerce_to_pyobject(env)
4551 self.type = py_object_type
4553 env.use_utility_code(create_class_utility_code);
4554 #TODO(craig,haoyu) This should be moved to a better place
4555 self.set_mod_name(env)
4557 def may_be_none(self):
4560 gil_message = "Constructing Python class"
4562 def generate_result_code(self, code):
4563 cname = code.intern_identifier(self.name)
4566 code.put_error_if_neg(self.pos,
4567 'PyDict_SetItemString(%s, "__doc__", %s)' % (
4568 self.dict.py_result(),
4569 self.doc.py_result()))
4570 py_mod_name = self.get_py_mod_name(code)
4572 '%s = __Pyx_CreateClass(%s, %s, %s, %s); %s' % (
4574 self.bases.py_result(),
4575 self.dict.py_result(),
4578 code.error_goto_if_null(self.result(), self.pos)))
4579 code.put_gotref(self.py_result())
4582 class Py3ClassNode(ExprNode):
4583 # Helper class used in the implementation of Python3+
4584 # class definitions. Constructs a class object given
4585 # a name, tuple of bases and class dictionary.
4587 # name EncodedString Name of the class
4588 # dict ExprNode Class dict (not owned by this node)
4589 # module_name EncodedString Name of defining module
4593 def analyse_types(self, env):
4594 self.type = py_object_type
4597 def may_be_none(self):
4600 gil_message = "Constructing Python class"
4602 def generate_result_code(self, code):
4603 code.globalstate.use_utility_code(create_py3class_utility_code)
4604 cname = code.intern_identifier(self.name)
4606 '%s = __Pyx_Py3ClassCreate(%s, %s, %s, %s, %s); %s' % (
4608 self.metaclass.result(),
4610 self.bases.py_result(),
4611 self.dict.py_result(),
4612 self.mkw.py_result(),
4613 code.error_goto_if_null(self.result(), self.pos)))
4614 code.put_gotref(self.py_result())
4616 class KeywordArgsNode(ExprNode):
4617 # Helper class for keyword arguments
4619 # keyword_args ExprNode or None Keyword arguments
4620 # starstar_arg ExprNode or None Extra arguments
4622 subexprs = ['keyword_args', 'starstar_arg']
4624 def analyse_types(self, env):
4625 if self.keyword_args:
4626 self.keyword_args.analyse_types(env)
4627 if self.starstar_arg:
4628 self.starstar_arg.analyse_types(env)
4629 # make sure we have a Python object as **kwargs mapping
4630 self.starstar_arg = \
4631 self.starstar_arg.coerce_to_pyobject(env)
4632 self.type = py_object_type
4635 gil_message = "Constructing Keyword Args"
4637 def generate_result_code(self, code):
4638 if self.keyword_args and self.starstar_arg:
4639 code.put_error_if_neg(self.pos,
4640 "PyDict_Update(%s, %s)" % (
4641 self.keyword_args.py_result(),
4642 self.starstar_arg.py_result()))
4643 if self.keyword_args:
4644 code.putln("%s = %s;" % (self.result(), self.keyword_args.result()))
4645 code.put_incref(self.keyword_args.result(), self.keyword_args.ctype())
4646 elif self.starstar_arg:
4648 "%s = PyDict_Copy(%s); %s" % (
4650 self.starstar_arg.py_result(),
4651 code.error_goto_if_null(self.result(), self.pos)))
4652 code.put_gotref(self.py_result())
4655 "%s = PyDict_New(); %s" % (
4657 code.error_goto_if_null(self.result(), self.pos)))
4658 code.put_gotref(self.py_result())
4660 class PyClassMetaclassNode(ExprNode):
4661 # Helper class holds Python3 metaclass object
4663 # bases ExprNode Base class tuple (not owned by this node)
4664 # mkw ExprNode Class keyword arguments (not owned by this node)
4668 def analyse_types(self, env):
4669 self.type = py_object_type
4672 def may_be_none(self):
4675 def generate_result_code(self, code):
4677 "%s = __Pyx_Py3MetaclassGet(%s, %s); %s" % (
4679 self.bases.result(),
4681 code.error_goto_if_null(self.result(), self.pos)))
4682 code.put_gotref(self.py_result())
4684 class PyClassNamespaceNode(ExprNode, ModuleNameMixin):
4685 # Helper class holds Python3 namespace object
4687 # All this are not owned by this node
4688 # metaclass ExprNode Metaclass object
4689 # bases ExprNode Base class tuple
4690 # mkw ExprNode Class keyword arguments
4691 # doc ExprNode or None Doc string (owned)
4695 def analyse_types(self, env):
4696 self.bases.analyse_types(env)
4698 self.doc.analyse_types(env)
4699 self.doc = self.doc.coerce_to_pyobject(env)
4700 self.type = py_object_type
4702 #TODO(craig,haoyu) This should be moved to a better place
4703 self.set_mod_name(env)
4705 def may_be_none(self):
4708 def generate_result_code(self, code):
4709 cname = code.intern_identifier(self.name)
4710 py_mod_name = self.get_py_mod_name(code)
4712 doc_code = self.doc.result()
4714 doc_code = '(PyObject *) NULL'
4716 "%s = __Pyx_Py3MetaclassPrepare(%s, %s, %s, %s, %s, %s); %s" % (
4718 self.metaclass.result(),
4719 self.bases.result(),
4724 code.error_goto_if_null(self.result(), self.pos)))
4725 code.put_gotref(self.py_result())
4727 class BoundMethodNode(ExprNode):
4728 # Helper class used in the implementation of Python
4729 # class definitions. Constructs an bound method
4730 # object from a class and a function.
4732 # function ExprNode Function object
4733 # self_object ExprNode self object
4735 subexprs = ['function']
4737 def analyse_types(self, env):
4738 self.function.analyse_types(env)
4739 self.type = py_object_type
4742 gil_message = "Constructing an bound method"
4744 def generate_result_code(self, code):
4746 "%s = PyMethod_New(%s, %s, (PyObject*)%s->ob_type); %s" % (
4748 self.function.py_result(),
4749 self.self_object.py_result(),
4750 self.self_object.py_result(),
4751 code.error_goto_if_null(self.result(), self.pos)))
4752 code.put_gotref(self.py_result())
4754 class UnboundMethodNode(ExprNode):
4755 # Helper class used in the implementation of Python
4756 # class definitions. Constructs an unbound method
4757 # object from a class and a function.
4759 # function ExprNode Function object
4761 type = py_object_type
4764 subexprs = ['function']
4766 def analyse_types(self, env):
4767 self.function.analyse_types(env)
4769 def may_be_none(self):
4772 gil_message = "Constructing an unbound method"
4774 def generate_result_code(self, code):
4775 class_cname = code.pyclass_stack[-1].classobj.result()
4777 "%s = PyMethod_New(%s, 0, %s); %s" % (
4779 self.function.py_result(),
4781 code.error_goto_if_null(self.result(), self.pos)))
4782 code.put_gotref(self.py_result())
4785 class PyCFunctionNode(ExprNode, ModuleNameMixin):
4786 # Helper class used in the implementation of Python
4787 # class definitions. Constructs a PyCFunction object
4788 # from a PyMethodDef struct.
4790 # pymethdef_cname string PyMethodDef structure
4791 # self_object ExprNode or None
4793 # module_name EncodedString Name of defining module
4799 type = py_object_type
4802 def analyse_types(self, env):
4804 env.use_utility_code(binding_cfunc_utility_code)
4806 #TODO(craig,haoyu) This should be moved to a better place
4807 self.set_mod_name(env)
4809 def may_be_none(self):
4812 gil_message = "Constructing Python function"
4814 def self_result_code(self):
4815 if self.self_object is None:
4816 self_result = "NULL"
4818 self_result = self.self_object.py_result()
4821 def generate_result_code(self, code):
4823 constructor = "%s_NewEx" % Naming.binding_cfunc
4825 constructor = "PyCFunction_NewEx"
4826 py_mod_name = self.get_py_mod_name(code)
4828 '%s = %s(&%s, %s, %s); %s' % (
4831 self.pymethdef_cname,
4832 self.self_result_code(),
4834 code.error_goto_if_null(self.result(), self.pos)))
4835 code.put_gotref(self.py_result())
4837 class InnerFunctionNode(PyCFunctionNode):
4838 # Special PyCFunctionNode that depends on a closure class
4842 def self_result_code(self):
4843 return "((PyObject*)%s)" % Naming.cur_scope_cname
4845 class LambdaNode(InnerFunctionNode):
4846 # Lambda expression node (only used as a function reference)
4848 # args [CArgDeclNode] formal arguments
4849 # star_arg PyArgDeclNode or None * argument
4850 # starstar_arg PyArgDeclNode or None ** argument
4851 # lambda_name string a module-globally unique lambda name
4852 # result_expr ExprNode
4853 # def_node DefNode the underlying function 'def' node
4855 child_attrs = ['def_node']
4858 name = StringEncoding.EncodedString('<lambda>')
4860 def analyse_declarations(self, env):
4861 #self.def_node.needs_closure = self.needs_closure
4862 self.def_node.analyse_declarations(env)
4863 self.pymethdef_cname = self.def_node.entry.pymethdef_cname
4864 env.add_lambda_def(self.def_node)
4866 class YieldExprNode(ExprNode):
4867 # Yield expression node
4869 # arg ExprNode the value to return from the generator
4870 # label_name string name of the C label used for this yield
4873 type = py_object_type
4875 def analyse_types(self, env):
4877 if self.arg is not None:
4878 self.arg.analyse_types(env)
4879 if not self.arg.type.is_pyobject:
4880 self.arg = self.arg.coerce_to_pyobject(env)
4881 error(self.pos, "Generators are not supported")
4883 def generate_result_code(self, code):
4884 self.label_name = code.new_label('resume_from_yield')
4885 code.use_label(self.label_name)
4886 code.putln("/* FIXME: save temporary variables */")
4887 code.putln("/* FIXME: return from function, yielding value */")
4888 code.put_label(self.label_name)
4889 code.putln("/* FIXME: restore temporary variables and */")
4890 code.putln("/* FIXME: extract sent value from closure */")
4893 #-------------------------------------------------------------------
4895 # Unary operator nodes
4897 #-------------------------------------------------------------------
4899 compile_time_unary_operators = {
4900 'not': operator.not_,
4906 class UnopNode(ExprNode):
4910 # Processing during analyse_expressions phase:
4912 # analyse_c_operation
4913 # Called when the operand is not a pyobject.
4914 # - Check operand type and coerce if needed.
4915 # - Determine result type and result code fragment.
4916 # - Allocate temporary for result if needed.
4918 subexprs = ['operand']
4921 def calculate_constant_result(self):
4922 func = compile_time_unary_operators[self.operator]
4923 self.constant_result = func(self.operand.constant_result)
4925 def compile_time_value(self, denv):
4926 func = compile_time_unary_operators.get(self.operator)
4929 "Unary '%s' not supported in compile-time expression"
4931 operand = self.operand.compile_time_value(denv)
4933 return func(operand)
4934 except Exception, e:
4935 self.compile_time_value_error(e)
4937 def infer_type(self, env):
4938 operand_type = self.operand.infer_type(env)
4939 if operand_type.is_pyobject:
4940 return py_object_type
4944 def analyse_types(self, env):
4945 self.operand.analyse_types(env)
4946 if self.is_py_operation():
4947 self.coerce_operand_to_pyobject(env)
4948 self.type = py_object_type
4950 elif self.is_cpp_operation():
4951 self.analyse_cpp_operation(env)
4953 self.analyse_c_operation(env)
4955 def check_const(self):
4956 return self.operand.check_const()
4958 def is_py_operation(self):
4959 return self.operand.type.is_pyobject
4961 def nogil_check(self, env):
4962 if self.is_py_operation():
4965 def is_cpp_operation(self):
4966 type = self.operand.type
4967 return type.is_cpp_class
4969 def coerce_operand_to_pyobject(self, env):
4970 self.operand = self.operand.coerce_to_pyobject(env)
4972 def generate_result_code(self, code):
4973 if self.operand.type.is_pyobject:
4974 self.generate_py_operation_code(code)
4976 def generate_py_operation_code(self, code):
4977 function = self.py_operation_function()
4979 "%s = %s(%s); %s" % (
4982 self.operand.py_result(),
4983 code.error_goto_if_null(self.result(), self.pos)))
4984 code.put_gotref(self.py_result())
4986 def type_error(self):
4987 if not self.operand.type.is_error:
4988 error(self.pos, "Invalid operand type for '%s' (%s)" %
4989 (self.operator, self.operand.type))
4990 self.type = PyrexTypes.error_type
4992 def analyse_cpp_operation(self, env):
4993 type = self.operand.type
4995 type = type.base_type
4996 function = type.scope.lookup("operator%s" % self.operator)
4998 error(self.pos, "'%s' operator not defined for %s"
4999 % (self.operator, type))
5002 func_type = function.type
5003 if func_type.is_ptr:
5004 func_type = func_type.base_type
5005 self.type = func_type.return_type
5008 class NotNode(ExprNode):
5013 type = PyrexTypes.c_bint_type
5015 subexprs = ['operand']
5017 def calculate_constant_result(self):
5018 self.constant_result = not self.operand.constant_result
5020 def compile_time_value(self, denv):
5021 operand = self.operand.compile_time_value(denv)
5024 except Exception, e:
5025 self.compile_time_value_error(e)
5027 def infer_type(self, env):
5028 return PyrexTypes.c_bint_type
5030 def analyse_types(self, env):
5031 self.operand.analyse_types(env)
5032 self.operand = self.operand.coerce_to_boolean(env)
5034 def calculate_result_code(self):
5035 return "(!%s)" % self.operand.result()
5037 def generate_result_code(self, code):
5041 class UnaryPlusNode(UnopNode):
5042 # unary '+' operator
5046 def analyse_c_operation(self, env):
5047 self.type = self.operand.type
5049 def py_operation_function(self):
5050 return "PyNumber_Positive"
5052 def calculate_result_code(self):
5053 if self.is_cpp_operation():
5054 return "(+%s)" % self.operand.result()
5056 return self.operand.result()
5059 class UnaryMinusNode(UnopNode):
5060 # unary '-' operator
5064 def analyse_c_operation(self, env):
5065 if self.operand.type.is_numeric:
5066 self.type = self.operand.type
5069 if self.type.is_complex:
5072 def py_operation_function(self):
5073 return "PyNumber_Negative"
5075 def calculate_result_code(self):
5077 return "(-%s)" % self.operand.result()
5079 return "%s(%s)" % (self.operand.type.unary_op('-'), self.operand.result())
5081 def get_constant_c_result_code(self):
5082 value = self.operand.get_constant_c_result_code()
5084 return "(-%s)" % (value)
5086 class TildeNode(UnopNode):
5087 # unary '~' operator
5089 def analyse_c_operation(self, env):
5090 if self.operand.type.is_int:
5091 self.type = self.operand.type
5095 def py_operation_function(self):
5096 return "PyNumber_Invert"
5098 def calculate_result_code(self):
5099 return "(~%s)" % self.operand.result()
5102 class CUnopNode(UnopNode):
5104 def is_py_operation(self):
5107 class DereferenceNode(CUnopNode):
5112 def analyse_c_operation(self, env):
5113 if self.operand.type.is_ptr:
5114 self.type = self.operand.type.base_type
5118 def calculate_result_code(self):
5119 return "(*%s)" % self.operand.result()
5122 class DecrementIncrementNode(CUnopNode):
5123 # unary ++/-- operator
5125 def analyse_c_operation(self, env):
5126 if self.operand.type.is_ptr or self.operand.type.is_numeric:
5127 self.type = self.operand.type
5131 def calculate_result_code(self):
5133 return "(%s%s)" % (self.operator, self.operand.result())
5135 return "(%s%s)" % (self.operand.result(), self.operator)
5137 def inc_dec_constructor(is_prefix, operator):
5138 return lambda pos, **kwds: DecrementIncrementNode(pos, is_prefix=is_prefix, operator=operator, **kwds)
5141 class AmpersandNode(ExprNode):
5142 # The C address-of operator.
5146 subexprs = ['operand']
5148 def infer_type(self, env):
5149 return PyrexTypes.c_ptr_type(self.operand.infer_type(env))
5151 def analyse_types(self, env):
5152 self.operand.analyse_types(env)
5153 argtype = self.operand.type
5154 if not (argtype.is_cfunction or self.operand.is_lvalue()):
5155 self.error("Taking address of non-lvalue")
5157 if argtype.is_pyobject:
5158 self.error("Cannot take address of Python variable")
5160 self.type = PyrexTypes.c_ptr_type(argtype)
5162 def check_const(self):
5163 return self.operand.check_const_addr()
5165 def error(self, mess):
5166 error(self.pos, mess)
5167 self.type = PyrexTypes.error_type
5168 self.result_code = "<error>"
5170 def calculate_result_code(self):
5171 return "(&%s)" % self.operand.result()
5173 def generate_result_code(self, code):
5177 unop_node_classes = {
5179 "-": UnaryMinusNode,
5183 def unop_node(pos, operator, operand):
5184 # Construct unnop node of appropriate class for
5186 if isinstance(operand, IntNode) and operator == '-':
5187 return IntNode(pos = operand.pos, value = str(-Utils.str_to_number(operand.value)))
5188 elif isinstance(operand, UnopNode) and operand.operator == operator:
5189 warning(pos, "Python has no increment/decrement operator: %s%sx = %s(%sx) = x" % ((operator,)*4), 5)
5190 return unop_node_classes[operator](pos,
5191 operator = operator,
5195 class TypecastNode(ExprNode):
5199 # base_type CBaseTypeNode
5200 # declarator CDeclaratorNode
5202 # If used from a transform, one can if wanted specify the attribute
5203 # "type" directly and leave base_type and declarator to None
5205 subexprs = ['operand']
5206 base_type = declarator = type = None
5208 def type_dependencies(self, env):
5211 def infer_type(self, env):
5212 if self.type is None:
5213 base_type = self.base_type.analyse(env)
5214 _, self.type = self.declarator.analyse(base_type, env)
5217 def analyse_types(self, env):
5218 if self.type is None:
5219 base_type = self.base_type.analyse(env)
5220 _, self.type = self.declarator.analyse(base_type, env)
5221 if self.type.is_cfunction:
5223 "Cannot cast to a function type")
5224 self.type = PyrexTypes.error_type
5225 self.operand.analyse_types(env)
5226 to_py = self.type.is_pyobject
5227 from_py = self.operand.type.is_pyobject
5228 if from_py and not to_py and self.operand.is_ephemeral() and not self.type.is_numeric:
5229 error(self.pos, "Casting temporary Python object to non-numeric non-Python type")
5230 if to_py and not from_py:
5231 if self.type is bytes_type and self.operand.type.is_int:
5232 # FIXME: the type cast node isn't needed in this case
5233 # and can be dropped once analyse_types() can return a
5235 self.operand = CoerceIntToBytesNode(self.operand, env)
5236 elif self.operand.type.can_coerce_to_pyobject(env):
5237 self.result_ctype = py_object_type
5238 self.operand = self.operand.coerce_to_pyobject(env)
5240 if self.operand.type.is_ptr:
5241 if not (self.operand.type.base_type.is_void or self.operand.type.base_type.is_struct):
5242 error(self.pos, "Python objects cannot be cast from pointers of primitive types")
5244 # Should this be an error?
5245 warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.operand.type, self.type))
5246 self.operand = self.operand.coerce_to_simple(env)
5247 elif from_py and not to_py:
5248 if self.type.create_from_py_utility_code(env):
5249 self.operand = self.operand.coerce_to(self.type, env)
5250 elif self.type.is_ptr:
5251 if not (self.type.base_type.is_void or self.type.base_type.is_struct):
5252 error(self.pos, "Python objects cannot be cast to pointers of primitive types")
5254 warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.type, self.operand.type))
5255 elif from_py and to_py:
5256 if self.typecheck and self.type.is_extension_type:
5257 self.operand = PyTypeTestNode(self.operand, self.type, env, notnone=True)
5258 elif self.type.is_complex and self.operand.type.is_complex:
5259 self.operand = self.operand.coerce_to_simple(env)
5261 def nogil_check(self, env):
5262 if self.type and self.type.is_pyobject and self.is_temp:
5265 def check_const(self):
5266 return self.operand.check_const()
5268 def calculate_constant_result(self):
5269 # we usually do not know the result of a type cast at code
5273 def calculate_result_code(self):
5274 if self.type.is_complex:
5275 operand_result = self.operand.result()
5276 if self.operand.type.is_complex:
5277 real_part = self.type.real_type.cast_code("__Pyx_CREAL(%s)" % operand_result)
5278 imag_part = self.type.real_type.cast_code("__Pyx_CIMAG(%s)" % operand_result)
5280 real_part = self.type.real_type.cast_code(operand_result)
5282 return "%s(%s, %s)" % (
5283 self.type.from_parts,
5287 return self.type.cast_code(self.operand.result())
5289 def get_constant_c_result_code(self):
5290 operand_result = self.operand.get_constant_c_result_code()
5292 return self.type.cast_code(operand_result)
5294 def result_as(self, type):
5295 if self.type.is_pyobject and not self.is_temp:
5296 # Optimise away some unnecessary casting
5297 return self.operand.result_as(type)
5299 return ExprNode.result_as(self, type)
5301 def generate_result_code(self, code):
5304 "%s = (PyObject *)%s;" % (
5306 self.operand.result()))
5307 code.put_incref(self.result(), self.ctype())
5310 class SizeofNode(ExprNode):
5311 # Abstract base class for sizeof(x) expression nodes.
5313 type = PyrexTypes.c_size_t_type
5315 def check_const(self):
5318 def generate_result_code(self, code):
5322 class SizeofTypeNode(SizeofNode):
5323 # C sizeof function applied to a type
5325 # base_type CBaseTypeNode
5326 # declarator CDeclaratorNode
5331 def analyse_types(self, env):
5332 # we may have incorrectly interpreted a dotted name as a type rather than an attribute
5333 # this could be better handled by more uniformly treating types as runtime-available objects
5334 if 0 and self.base_type.module_path:
5335 path = self.base_type.module_path
5336 obj = env.lookup(path[0])
5337 if obj.as_module is None:
5338 operand = NameNode(pos=self.pos, name=path[0])
5339 for attr in path[1:]:
5340 operand = AttributeNode(pos=self.pos, obj=operand, attribute=attr)
5341 operand = AttributeNode(pos=self.pos, obj=operand, attribute=self.base_type.name)
5342 self.operand = operand
5343 self.__class__ = SizeofVarNode
5344 self.analyse_types(env)
5346 if self.arg_type is None:
5347 base_type = self.base_type.analyse(env)
5348 _, arg_type = self.declarator.analyse(base_type, env)
5349 self.arg_type = arg_type
5352 def check_type(self):
5353 arg_type = self.arg_type
5354 if arg_type.is_pyobject and not arg_type.is_extension_type:
5355 error(self.pos, "Cannot take sizeof Python object")
5356 elif arg_type.is_void:
5357 error(self.pos, "Cannot take sizeof void")
5358 elif not arg_type.is_complete():
5359 error(self.pos, "Cannot take sizeof incomplete type '%s'" % arg_type)
5361 def calculate_result_code(self):
5362 if self.arg_type.is_extension_type:
5363 # the size of the pointer is boring
5364 # we want the size of the actual struct
5365 arg_code = self.arg_type.declaration_code("", deref=1)
5367 arg_code = self.arg_type.declaration_code("")
5368 return "(sizeof(%s))" % arg_code
5371 class SizeofVarNode(SizeofNode):
5372 # C sizeof function applied to a variable
5376 subexprs = ['operand']
5378 def analyse_types(self, env):
5379 # We may actually be looking at a type rather than a variable...
5380 # If we are, traditional analysis would fail...
5381 operand_as_type = self.operand.analyse_as_type(env)
5383 self.arg_type = operand_as_type
5384 self.__class__ = SizeofTypeNode
5387 self.operand.analyse_types(env)
5389 def calculate_result_code(self):
5390 return "(sizeof(%s))" % self.operand.result()
5392 def generate_result_code(self, code):
5395 class TypeofNode(ExprNode):
5396 # Compile-time type of an expression, as a string.
5399 # literal StringNode # internal
5402 type = py_object_type
5404 subexprs = ['literal'] # 'operand' will be ignored after type analysis!
5406 def analyse_types(self, env):
5407 self.operand.analyse_types(env)
5408 self.literal = StringNode(
5409 self.pos, value=StringEncoding.EncodedString(str(self.operand.type)))
5410 self.literal.analyse_types(env)
5411 self.literal = self.literal.coerce_to_pyobject(env)
5413 def may_be_none(self):
5416 def generate_evaluation_code(self, code):
5417 self.literal.generate_evaluation_code(code)
5419 def calculate_result_code(self):
5420 return self.literal.calculate_result_code()
5422 #-------------------------------------------------------------------
5424 # Binary operator nodes
5426 #-------------------------------------------------------------------
5428 def _not_in(x, seq):
5431 compile_time_binary_operators = {
5439 'is_not': operator.is_not,
5442 '/': operator.truediv,
5443 '//': operator.floordiv,
5444 '<<': operator.lshift,
5449 '>>': operator.rshift,
5452 'in': operator.contains,
5456 def get_compile_time_binop(node):
5457 func = compile_time_binary_operators.get(node.operator)
5460 "Binary '%s' not supported in compile-time expression"
5464 class BinopNode(ExprNode):
5469 # Processing during analyse_expressions phase:
5471 # analyse_c_operation
5472 # Called when neither operand is a pyobject.
5473 # - Check operand types and coerce if needed.
5474 # - Determine result type and result code fragment.
5475 # - Allocate temporary for result if needed.
5477 subexprs = ['operand1', 'operand2']
5480 def calculate_constant_result(self):
5481 func = compile_time_binary_operators[self.operator]
5482 self.constant_result = func(
5483 self.operand1.constant_result,
5484 self.operand2.constant_result)
5486 def compile_time_value(self, denv):
5487 func = get_compile_time_binop(self)
5488 operand1 = self.operand1.compile_time_value(denv)
5489 operand2 = self.operand2.compile_time_value(denv)
5491 return func(operand1, operand2)
5492 except Exception, e:
5493 self.compile_time_value_error(e)
5495 def infer_type(self, env):
5496 return self.result_type(self.operand1.infer_type(env),
5497 self.operand2.infer_type(env))
5499 def analyse_types(self, env):
5500 self.operand1.analyse_types(env)
5501 self.operand2.analyse_types(env)
5502 self.analyse_operation(env)
5504 def analyse_operation(self, env):
5505 if self.is_py_operation():
5506 self.coerce_operands_to_pyobjects(env)
5507 self.type = self.result_type(self.operand1.type,
5509 assert self.type.is_pyobject
5511 elif self.is_cpp_operation():
5512 self.analyse_cpp_operation(env)
5514 self.analyse_c_operation(env)
5516 def is_py_operation(self):
5517 return self.is_py_operation_types(self.operand1.type, self.operand2.type)
5519 def is_py_operation_types(self, type1, type2):
5520 return type1.is_pyobject or type2.is_pyobject
5522 def is_cpp_operation(self):
5523 return (self.operand1.type.is_cpp_class
5524 or self.operand2.type.is_cpp_class)
5526 def analyse_cpp_operation(self, env):
5527 type1 = self.operand1.type
5528 type2 = self.operand2.type
5529 entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
5533 func_type = entry.type
5534 if func_type.is_ptr:
5535 func_type = func_type.base_type
5536 if len(func_type.args) == 1:
5537 self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
5539 self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
5540 self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
5541 self.type = func_type.return_type
5543 def result_type(self, type1, type2):
5544 if self.is_py_operation_types(type1, type2):
5546 type2 = Builtin.bytes_type
5548 type1 = Builtin.bytes_type
5549 elif self.operator == '%' \
5550 and type1 in (Builtin.str_type, Builtin.unicode_type):
5551 # note that b'%s' % b'abc' doesn't work in Py3
5553 if type1.is_builtin_type:
5555 if self.operator in '**%+|&^':
5556 # FIXME: at least these operators should be safe - others?
5558 elif self.operator == '*':
5559 if type1 in (Builtin.bytes_type, Builtin.str_type, Builtin.unicode_type):
5561 # multiplication of containers/numbers with an
5562 # integer value always (?) returns the same type
5565 elif type2.is_builtin_type and type1.is_int and self.operator == '*':
5566 # multiplication of containers/numbers with an
5567 # integer value always (?) returns the same type
5569 return py_object_type
5571 return self.compute_c_result_type(type1, type2)
5573 def nogil_check(self, env):
5574 if self.is_py_operation():
5577 def coerce_operands_to_pyobjects(self, env):
5578 self.operand1 = self.operand1.coerce_to_pyobject(env)
5579 self.operand2 = self.operand2.coerce_to_pyobject(env)
5581 def check_const(self):
5582 return self.operand1.check_const() and self.operand2.check_const()
5584 def generate_result_code(self, code):
5585 #print "BinopNode.generate_result_code:", self.operand1, self.operand2 ###
5586 if self.operand1.type.is_pyobject:
5587 function = self.py_operation_function()
5588 if self.operator == '**':
5589 extra_args = ", Py_None"
5593 "%s = %s(%s, %s%s); %s" % (
5596 self.operand1.py_result(),
5597 self.operand2.py_result(),
5599 code.error_goto_if_null(self.result(), self.pos)))
5600 code.put_gotref(self.py_result())
5602 def type_error(self):
5603 if not (self.operand1.type.is_error
5604 or self.operand2.type.is_error):
5605 error(self.pos, "Invalid operand types for '%s' (%s; %s)" %
5606 (self.operator, self.operand1.type,
5607 self.operand2.type))
5608 self.type = PyrexTypes.error_type
5611 class CBinopNode(BinopNode):
5613 def analyse_types(self, env):
5614 BinopNode.analyse_types(self, env)
5615 if self.is_py_operation():
5616 self.type = PyrexTypes.error_type
5618 def py_operation_function():
5621 def calculate_result_code(self):
5622 return "(%s %s %s)" % (
5623 self.operand1.result(),
5625 self.operand2.result())
5628 def c_binop_constructor(operator):
5629 def make_binop_node(pos, **operands):
5630 return CBinopNode(pos, operator=operator, **operands)
5631 return make_binop_node
5633 class NumBinopNode(BinopNode):
5634 # Binary operation taking numeric arguments.
5638 def analyse_c_operation(self, env):
5639 type1 = self.operand1.type
5640 type2 = self.operand2.type
5641 self.type = self.compute_c_result_type(type1, type2)
5645 if self.type.is_complex:
5647 if not self.infix or (type1.is_numeric and type2.is_numeric):
5648 self.operand1 = self.operand1.coerce_to(self.type, env)
5649 self.operand2 = self.operand2.coerce_to(self.type, env)
5651 def compute_c_result_type(self, type1, type2):
5652 if self.c_types_okay(type1, type2):
5653 return PyrexTypes.widest_numeric_type(type1, type2)
5657 def get_constant_c_result_code(self):
5658 value1 = self.operand1.get_constant_c_result_code()
5659 value2 = self.operand2.get_constant_c_result_code()
5660 if value1 and value2:
5661 return "(%s %s %s)" % (value1, self.operator, value2)
5665 def c_types_okay(self, type1, type2):
5666 #print "NumBinopNode.c_types_okay:", type1, type2 ###
5667 return (type1.is_numeric or type1.is_enum) \
5668 and (type2.is_numeric or type2.is_enum)
5670 def calculate_result_code(self):
5672 return "(%s %s %s)" % (
5673 self.operand1.result(),
5675 self.operand2.result())
5677 func = self.type.binary_op(self.operator)
5679 error(self.pos, "binary operator %s not supported for %s" % (self.operator, self.type))
5680 return "%s(%s, %s)" % (
5682 self.operand1.result(),
5683 self.operand2.result())
5685 def is_py_operation_types(self, type1, type2):
5686 return (type1 is PyrexTypes.c_py_unicode_type or
5687 type2 is PyrexTypes.c_py_unicode_type or
5688 BinopNode.is_py_operation_types(self, type1, type2))
5690 def py_operation_function(self):
5691 fuction = self.py_functions[self.operator]
5693 fuction = fuction.replace('PyNumber_', 'PyNumber_InPlace')
5698 "^": "PyNumber_Xor",
5699 "&": "PyNumber_And",
5700 "<<": "PyNumber_Lshift",
5701 ">>": "PyNumber_Rshift",
5702 "+": "PyNumber_Add",
5703 "-": "PyNumber_Subtract",
5704 "*": "PyNumber_Multiply",
5705 "/": "__Pyx_PyNumber_Divide",
5706 "//": "PyNumber_FloorDivide",
5707 "%": "PyNumber_Remainder",
5708 "**": "PyNumber_Power"
5711 class IntBinopNode(NumBinopNode):
5712 # Binary operation taking integer arguments.
5714 def c_types_okay(self, type1, type2):
5715 #print "IntBinopNode.c_types_okay:", type1, type2 ###
5716 return (type1.is_int or type1.is_enum) \
5717 and (type2.is_int or type2.is_enum)
5720 class AddNode(NumBinopNode):
5723 def is_py_operation_types(self, type1, type2):
5724 if type1.is_string and type2.is_string:
5727 return NumBinopNode.is_py_operation_types(self, type1, type2)
5729 def compute_c_result_type(self, type1, type2):
5730 #print "AddNode.compute_c_result_type:", type1, self.operator, type2 ###
5731 if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
5733 elif (type2.is_ptr or type2.is_array) and (type1.is_int or type1.is_enum):
5736 return NumBinopNode.compute_c_result_type(
5740 class SubNode(NumBinopNode):
5743 def compute_c_result_type(self, type1, type2):
5744 if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
5746 elif (type1.is_ptr or type1.is_array) and (type2.is_ptr or type2.is_array):
5747 return PyrexTypes.c_int_type
5749 return NumBinopNode.compute_c_result_type(
5753 class MulNode(NumBinopNode):
5756 def is_py_operation_types(self, type1, type2):
5757 if (type1.is_string and type2.is_int) \
5758 or (type2.is_string and type1.is_int):
5761 return NumBinopNode.is_py_operation_types(self, type1, type2)
5764 class DivNode(NumBinopNode):
5765 # '/' or '//' operator.
5768 truedivision = None # == "unknown" if operator == '/'
5769 ctruedivision = False
5770 cdivision_warnings = False
5771 zerodivision_check = None
5773 def find_compile_time_binary_operator(self, op1, op2):
5774 func = compile_time_binary_operators[self.operator]
5775 if self.operator == '/' and self.truedivision is None:
5776 # => true div for floats, floor div for integers
5777 if isinstance(op1, (int,long)) and isinstance(op2, (int,long)):
5778 func = compile_time_binary_operators['//']
5781 def calculate_constant_result(self):
5782 op1 = self.operand1.constant_result
5783 op2 = self.operand2.constant_result
5784 func = self.find_compile_time_binary_operator(op1, op2)
5785 self.constant_result = func(
5786 self.operand1.constant_result,
5787 self.operand2.constant_result)
5789 def compile_time_value(self, denv):
5790 operand1 = self.operand1.compile_time_value(denv)
5791 operand2 = self.operand2.compile_time_value(denv)
5793 func = self.find_compile_time_binary_operator(
5794 self, operand1, operand2)
5795 return func(operand1, operand2)
5796 except Exception, e:
5797 self.compile_time_value_error(e)
5799 def analyse_operation(self, env):
5800 if self.cdivision or env.directives['cdivision']:
5801 self.ctruedivision = False
5803 self.ctruedivision = self.truedivision
5804 NumBinopNode.analyse_operation(self, env)
5805 if self.is_cpp_operation():
5806 self.cdivision = True
5807 if not self.type.is_pyobject:
5808 self.zerodivision_check = (
5809 self.cdivision is None and not env.directives['cdivision']
5810 and (not self.operand2.has_constant_result() or
5811 self.operand2.constant_result == 0))
5812 if self.zerodivision_check or env.directives['cdivision_warnings']:
5813 # Need to check ahead of time to warn or raise zero division error
5814 self.operand1 = self.operand1.coerce_to_simple(env)
5815 self.operand2 = self.operand2.coerce_to_simple(env)
5817 error(self.pos, "Pythonic division not allowed without gil, consider using cython.cdivision(True)")
5819 def compute_c_result_type(self, type1, type2):
5820 if self.operator == '/' and self.ctruedivision:
5821 if not type1.is_float and not type2.is_float:
5822 widest_type = PyrexTypes.widest_numeric_type(type1, PyrexTypes.c_double_type)
5823 widest_type = PyrexTypes.widest_numeric_type(type2, widest_type)
5825 return NumBinopNode.compute_c_result_type(self, type1, type2)
5827 def zero_division_message(self):
5828 if self.type.is_int:
5829 return "integer division or modulo by zero"
5831 return "float division"
5833 def generate_evaluation_code(self, code):
5834 if not self.type.is_pyobject and not self.type.is_complex:
5835 if self.cdivision is None:
5836 self.cdivision = (code.globalstate.directives['cdivision']
5837 or not self.type.signed
5838 or self.type.is_float)
5839 if not self.cdivision:
5840 code.globalstate.use_utility_code(div_int_utility_code.specialize(self.type))
5841 NumBinopNode.generate_evaluation_code(self, code)
5842 self.generate_div_warning_code(code)
5844 def generate_div_warning_code(self, code):
5845 if not self.type.is_pyobject:
5846 if self.zerodivision_check:
5848 zero_test = "%s(%s)" % (self.type.unary_op('zero'), self.operand2.result())
5850 zero_test = "%s == 0" % self.operand2.result()
5851 code.putln("if (unlikely(%s)) {" % zero_test)
5852 code.putln('PyErr_Format(PyExc_ZeroDivisionError, "%s");' % self.zero_division_message())
5853 code.putln(code.error_goto(self.pos))
5855 if self.type.is_int and self.type.signed and self.operator != '%':
5856 code.globalstate.use_utility_code(division_overflow_test_code)
5857 code.putln("else if (sizeof(%s) == sizeof(long) && unlikely(%s == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(%s))) {" % (
5858 self.type.declaration_code(''),
5859 self.operand2.result(),
5860 self.operand1.result()))
5861 code.putln('PyErr_Format(PyExc_OverflowError, "value too large to perform division");')
5862 code.putln(code.error_goto(self.pos))
5864 if code.globalstate.directives['cdivision_warnings'] and self.operator != '/':
5865 code.globalstate.use_utility_code(cdivision_warning_utility_code)
5866 code.putln("if ((%s < 0) ^ (%s < 0)) {" % (
5867 self.operand1.result(),
5868 self.operand2.result()))
5869 code.putln(code.set_error_info(self.pos));
5870 code.put("if (__Pyx_cdivision_warning()) ")
5871 code.put_goto(code.error_label)
5874 def calculate_result_code(self):
5875 if self.type.is_complex:
5876 return NumBinopNode.calculate_result_code(self)
5877 elif self.type.is_float and self.operator == '//':
5878 return "floor(%s / %s)" % (
5879 self.operand1.result(),
5880 self.operand2.result())
5881 elif self.truedivision or self.cdivision:
5882 op1 = self.operand1.result()
5883 op2 = self.operand2.result()
5884 if self.truedivision:
5885 if self.type != self.operand1.type:
5886 op1 = self.type.cast_code(op1)
5887 if self.type != self.operand2.type:
5888 op2 = self.type.cast_code(op2)
5889 return "(%s / %s)" % (op1, op2)
5891 return "__Pyx_div_%s(%s, %s)" % (
5892 self.type.specialization_name(),
5893 self.operand1.result(),
5894 self.operand2.result())
5897 class ModNode(DivNode):
5900 def is_py_operation_types(self, type1, type2):
5901 return (type1.is_string
5903 or NumBinopNode.is_py_operation_types(self, type1, type2))
5905 def zero_division_message(self):
5906 if self.type.is_int:
5907 return "integer division or modulo by zero"
5909 return "float divmod()"
5911 def generate_evaluation_code(self, code):
5912 if not self.type.is_pyobject:
5913 if self.cdivision is None:
5914 self.cdivision = code.globalstate.directives['cdivision'] or not self.type.signed
5915 if not self.cdivision:
5916 if self.type.is_int:
5917 code.globalstate.use_utility_code(mod_int_utility_code.specialize(self.type))
5919 code.globalstate.use_utility_code(
5920 mod_float_utility_code.specialize(self.type, math_h_modifier=self.type.math_h_modifier))
5921 NumBinopNode.generate_evaluation_code(self, code)
5922 self.generate_div_warning_code(code)
5924 def calculate_result_code(self):
5926 if self.type.is_float:
5927 return "fmod%s(%s, %s)" % (
5928 self.type.math_h_modifier,
5929 self.operand1.result(),
5930 self.operand2.result())
5932 return "(%s %% %s)" % (
5933 self.operand1.result(),
5934 self.operand2.result())
5936 return "__Pyx_mod_%s(%s, %s)" % (
5937 self.type.specialization_name(),
5938 self.operand1.result(),
5939 self.operand2.result())
5941 class PowNode(NumBinopNode):
5944 def analyse_c_operation(self, env):
5945 NumBinopNode.analyse_c_operation(self, env)
5946 if self.type.is_complex:
5947 if self.type.real_type.is_float:
5948 self.operand1 = self.operand1.coerce_to(self.type, env)
5949 self.operand2 = self.operand2.coerce_to(self.type, env)
5950 self.pow_func = "__Pyx_c_pow" + self.type.real_type.math_h_modifier
5952 error(self.pos, "complex int powers not supported")
5953 self.pow_func = "<error>"
5954 elif self.type.is_float:
5955 self.pow_func = "pow" + self.type.math_h_modifier
5957 self.pow_func = "__Pyx_pow_%s" % self.type.declaration_code('').replace(' ', '_')
5958 env.use_utility_code(
5959 int_pow_utility_code.specialize(func_name=self.pow_func,
5960 type=self.type.declaration_code('')))
5962 def calculate_result_code(self):
5963 # Work around MSVC overloading ambiguity.
5964 def typecast(operand):
5965 if self.type == operand.type:
5966 return operand.result()
5968 return self.type.cast_code(operand.result())
5969 return "%s(%s, %s)" % (
5971 typecast(self.operand1),
5972 typecast(self.operand2))
5975 # Note: This class is temporarily "shut down" into an ineffective temp
5978 # More sophisticated temp reuse was going on before, one could have a
5979 # look at adding this again after /all/ classes are converted to the
5980 # new temp scheme. (The temp juggling cannot work otherwise).
5981 class BoolBinopNode(ExprNode):
5982 # Short-circuiting boolean operation.
5988 subexprs = ['operand1', 'operand2']
5990 def infer_type(self, env):
5991 type1 = self.operand1.infer_type(env)
5992 type2 = self.operand2.infer_type(env)
5993 return PyrexTypes.independent_spanning_type(type1, type2)
5995 def may_be_none(self):
5996 if self.operator == 'or':
5997 return self.operand2.may_be_none()
5999 return self.operand1.may_be_none() or self.operand2.may_be_none()
6001 def calculate_constant_result(self):
6002 if self.operator == 'and':
6003 self.constant_result = \
6004 self.operand1.constant_result and \
6005 self.operand2.constant_result
6007 self.constant_result = \
6008 self.operand1.constant_result or \
6009 self.operand2.constant_result
6011 def compile_time_value(self, denv):
6012 if self.operator == 'and':
6013 return self.operand1.compile_time_value(denv) \
6014 and self.operand2.compile_time_value(denv)
6016 return self.operand1.compile_time_value(denv) \
6017 or self.operand2.compile_time_value(denv)
6019 def coerce_to_boolean(self, env):
6020 return BoolBinopNode(
6022 operator = self.operator,
6023 operand1 = self.operand1.coerce_to_boolean(env),
6024 operand2 = self.operand2.coerce_to_boolean(env),
6025 type = PyrexTypes.c_bint_type,
6026 is_temp = self.is_temp)
6028 def analyse_types(self, env):
6029 self.operand1.analyse_types(env)
6030 self.operand2.analyse_types(env)
6031 self.type = PyrexTypes.independent_spanning_type(self.operand1.type, self.operand2.type)
6032 self.operand1 = self.operand1.coerce_to(self.type, env)
6033 self.operand2 = self.operand2.coerce_to(self.type, env)
6035 # For what we're about to do, it's vital that
6036 # both operands be temp nodes.
6037 self.operand1 = self.operand1.coerce_to_simple(env)
6038 self.operand2 = self.operand2.coerce_to_simple(env)
6041 gil_message = "Truth-testing Python object"
6043 def check_const(self):
6044 return self.operand1.check_const() and self.operand2.check_const()
6046 def generate_evaluation_code(self, code):
6047 code.mark_pos(self.pos)
6048 self.operand1.generate_evaluation_code(code)
6049 test_result, uses_temp = self.generate_operand1_test(code)
6050 if self.operator == 'and':
6059 code.funcstate.release_temp(test_result)
6060 self.operand1.generate_disposal_code(code)
6061 self.operand2.generate_evaluation_code(code)
6062 self.allocate_temp_result(code)
6063 self.operand2.make_owned_reference(code)
6064 code.putln("%s = %s;" % (self.result(), self.operand2.result()))
6065 self.operand2.generate_post_assignment_code(code)
6066 self.operand2.free_temps(code)
6067 code.putln("} else {")
6068 self.operand1.make_owned_reference(code)
6069 code.putln("%s = %s;" % (self.result(), self.operand1.result()))
6070 self.operand1.generate_post_assignment_code(code)
6071 self.operand1.free_temps(code)
6074 def generate_operand1_test(self, code):
6075 # Generate code to test the truth of the first operand.
6076 if self.type.is_pyobject:
6077 test_result = code.funcstate.allocate_temp(PyrexTypes.c_bint_type,
6080 "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
6082 self.operand1.py_result(),
6083 code.error_goto_if_neg(test_result, self.pos)))
6085 test_result = self.operand1.result()
6086 return (test_result, self.type.is_pyobject)
6089 class CondExprNode(ExprNode):
6090 # Short-circuiting conditional expression.
6094 # false_val ExprNode
6099 subexprs = ['test', 'true_val', 'false_val']
6101 def type_dependencies(self, env):
6102 return self.true_val.type_dependencies(env) + self.false_val.type_dependencies(env)
6104 def infer_type(self, env):
6105 return PyrexTypes.independent_spanning_type(self.true_val.infer_type(env),
6106 self.false_val.infer_type(env))
6108 def calculate_constant_result(self):
6109 if self.test.constant_result:
6110 self.constant_result = self.true_val.constant_result
6112 self.constant_result = self.false_val.constant_result
6114 def analyse_types(self, env):
6115 self.test.analyse_types(env)
6116 self.test = self.test.coerce_to_boolean(env)
6117 self.true_val.analyse_types(env)
6118 self.false_val.analyse_types(env)
6119 self.type = PyrexTypes.independent_spanning_type(self.true_val.type, self.false_val.type)
6120 if self.true_val.type.is_pyobject or self.false_val.type.is_pyobject:
6121 self.true_val = self.true_val.coerce_to(self.type, env)
6122 self.false_val = self.false_val.coerce_to(self.type, env)
6124 if self.type == PyrexTypes.error_type:
6127 def type_error(self):
6128 if not (self.true_val.type.is_error or self.false_val.type.is_error):
6129 error(self.pos, "Incompatable types in conditional expression (%s; %s)" %
6130 (self.true_val.type, self.false_val.type))
6131 self.type = PyrexTypes.error_type
6133 def check_const(self):
6134 return (self.test.check_const()
6135 and self.true_val.check_const()
6136 and self.false_val.check_const())
6138 def generate_evaluation_code(self, code):
6139 # Because subexprs may not be evaluated we can use a more optimal
6140 # subexpr allocation strategy than the default, so override evaluation_code.
6142 code.mark_pos(self.pos)
6143 self.allocate_temp_result(code)
6144 self.test.generate_evaluation_code(code)
6145 code.putln("if (%s) {" % self.test.result() )
6146 self.eval_and_get(code, self.true_val)
6147 code.putln("} else {")
6148 self.eval_and_get(code, self.false_val)
6150 self.test.generate_disposal_code(code)
6151 self.test.free_temps(code)
6153 def eval_and_get(self, code, expr):
6154 expr.generate_evaluation_code(code)
6155 expr.make_owned_reference(code)
6156 code.putln("%s = %s;" % (self.result(), expr.result()))
6157 expr.generate_post_assignment_code(code)
6158 expr.free_temps(code)
6160 richcmp_constants = {
6170 class CmpNode(object):
6171 # Mixin class containing code common to PrimaryCmpNodes
6172 # and CascadedCmpNodes.
6174 special_bool_cmp_function = None
6176 def infer_type(self, env):
6177 # TODO: Actually implement this (after merging with -unstable).
6178 return py_object_type
6180 def calculate_cascaded_constant_result(self, operand1_result):
6181 func = compile_time_binary_operators[self.operator]
6182 operand2_result = self.operand2.constant_result
6183 result = func(operand1_result, operand2_result)
6185 self.cascade.calculate_cascaded_constant_result(operand2_result)
6186 if self.cascade.constant_result:
6187 self.constant_result = result and self.cascade.constant_result
6189 self.constant_result = result
6191 def cascaded_compile_time_value(self, operand1, denv):
6192 func = get_compile_time_binop(self)
6193 operand2 = self.operand2.compile_time_value(denv)
6195 result = func(operand1, operand2)
6196 except Exception, e:
6197 self.compile_time_value_error(e)
6200 cascade = self.cascade
6202 # FIXME: I bet this must call cascaded_compile_time_value()
6203 result = result and cascade.cascaded_compile_time_value(operand2, denv)
6206 def is_cpp_comparison(self):
6207 return self.operand1.type.is_cpp_class or self.operand2.type.is_cpp_class
6209 def find_common_int_type(self, env, op, operand1, operand2):
6210 # type1 != type2 and at least one of the types is not a C int
6211 type1 = operand1.type
6212 type2 = operand2.type
6213 type1_can_be_int = False
6214 type2_can_be_int = False
6216 if isinstance(operand1, (StringNode, BytesNode, UnicodeNode)) \
6217 and operand1.can_coerce_to_char_literal():
6218 type1_can_be_int = True
6219 if isinstance(operand2, (StringNode, BytesNode, UnicodeNode)) \
6220 and operand2.can_coerce_to_char_literal():
6221 type2_can_be_int = True
6224 if type2_can_be_int:
6227 if type1_can_be_int:
6229 elif type1_can_be_int:
6230 if type2_can_be_int:
6231 return PyrexTypes.c_uchar_type
6235 def find_common_type(self, env, op, operand1, common_type=None):
6236 operand2 = self.operand2
6237 type1 = operand1.type
6238 type2 = operand2.type
6240 new_common_type = None
6242 # catch general errors
6243 if type1 == str_type and (type2.is_string or type2 in (bytes_type, unicode_type)) or \
6244 type2 == str_type and (type1.is_string or type1 in (bytes_type, unicode_type)):
6245 error(self.pos, "Comparisons between bytes/unicode and str are not portable to Python 3")
6246 new_common_type = error_type
6248 # try to use numeric comparisons where possible
6249 elif type1.is_complex or type2.is_complex:
6250 if op not in ('==', '!='):
6251 error(self.pos, "complex types are unordered")
6252 new_common_type = error_type
6253 if type1.is_pyobject:
6254 new_common_type = type1
6255 elif type2.is_pyobject:
6256 new_common_type = type2
6258 new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
6259 elif type1.is_numeric and type2.is_numeric:
6260 new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
6261 elif common_type is None or not common_type.is_pyobject:
6262 new_common_type = self.find_common_int_type(env, op, operand1, operand2)
6264 if new_common_type is None:
6265 # fall back to generic type compatibility tests
6267 new_common_type = type1
6268 elif type1.is_pyobject or type2.is_pyobject:
6269 if type2.is_numeric or type2.is_string:
6270 if operand2.check_for_coercion_error(type1):
6271 new_common_type = error_type
6273 new_common_type = py_object_type
6274 elif type1.is_numeric or type1.is_string:
6275 if operand1.check_for_coercion_error(type2):
6276 new_common_type = error_type
6278 new_common_type = py_object_type
6279 elif py_object_type.assignable_from(type1) and py_object_type.assignable_from(type2):
6280 new_common_type = py_object_type
6282 # one Python type and one non-Python type, not assignable
6283 self.invalid_types_error(operand1, op, operand2)
6284 new_common_type = error_type
6285 elif type1.assignable_from(type2):
6286 new_common_type = type1
6287 elif type2.assignable_from(type1):
6288 new_common_type = type2
6290 # C types that we couldn't handle up to here are an error
6291 self.invalid_types_error(operand1, op, operand2)
6292 new_common_type = error_type
6294 if new_common_type.is_string and (isinstance(operand1, BytesNode) or
6295 isinstance(operand2, BytesNode)):
6296 # special case when comparing char* to bytes literal: must
6297 # compare string values!
6298 new_common_type = bytes_type
6300 # recursively merge types
6301 if common_type is None or new_common_type.is_error:
6302 common_type = new_common_type
6304 # we could do a lot better by splitting the comparison
6305 # into a non-Python part and a Python part, but this is
6307 common_type = PyrexTypes.spanning_type(common_type, new_common_type)
6310 common_type = self.cascade.find_common_type(env, self.operator, operand2, common_type)
6314 def invalid_types_error(self, operand1, op, operand2):
6315 error(self.pos, "Invalid types for '%s' (%s, %s)" %
6316 (op, operand1.type, operand2.type))
6318 def is_python_comparison(self):
6319 return (not self.is_ptr_contains()
6320 and not self.is_c_string_contains()
6321 and (self.has_python_operands()
6322 or (self.cascade and self.cascade.is_python_comparison())
6323 or self.operator in ('in', 'not_in')))
6325 def coerce_operands_to(self, dst_type, env):
6326 operand2 = self.operand2
6327 if operand2.type != dst_type:
6328 self.operand2 = operand2.coerce_to(dst_type, env)
6330 self.cascade.coerce_operands_to(dst_type, env)
6332 def is_python_result(self):
6333 return ((self.has_python_operands() and
6334 self.special_bool_cmp_function is None and
6335 self.operator not in ('is', 'is_not', 'in', 'not_in') and
6336 not self.is_c_string_contains() and
6337 not self.is_ptr_contains())
6338 or (self.cascade and self.cascade.is_python_result()))
6340 def is_c_string_contains(self):
6341 return self.operator in ('in', 'not_in') and \
6342 ((self.operand1.type.is_int
6343 and (self.operand2.type.is_string or self.operand2.type is bytes_type)) or
6344 (self.operand1.type is PyrexTypes.c_py_unicode_type
6345 and self.operand2.type is unicode_type))
6347 def is_ptr_contains(self):
6348 if self.operator in ('in', 'not_in'):
6349 container_type = self.operand2.type
6350 return (container_type.is_ptr or container_type.is_array) \
6351 and not container_type.is_string
6353 def find_special_bool_compare_function(self, env):
6354 if self.operator in ('==', '!='):
6355 type1, type2 = self.operand1.type, self.operand2.type
6356 if type1.is_pyobject and type2.is_pyobject:
6357 if type1 is Builtin.unicode_type or type2 is Builtin.unicode_type:
6358 env.use_utility_code(pyunicode_equals_utility_code)
6359 self.special_bool_cmp_function = "__Pyx_PyUnicode_Equals"
6363 def generate_operation_code(self, code, result_code,
6364 operand1, op , operand2):
6365 if self.type.is_pyobject:
6366 coerce_result = "__Pyx_PyBool_FromLong"
6373 if self.special_bool_cmp_function:
6374 if operand1.type.is_pyobject:
6375 result1 = operand1.py_result()
6377 result1 = operand1.result()
6378 if operand2.type.is_pyobject:
6379 result2 = operand2.py_result()
6381 result2 = operand2.result()
6382 code.putln("%s = %s(%s, %s, %s); %s" % (
6384 self.special_bool_cmp_function,
6387 richcmp_constants[op],
6388 code.error_goto_if_neg(result_code, self.pos)))
6389 elif op == 'in' or op == 'not_in':
6390 code.globalstate.use_utility_code(contains_utility_code)
6391 if self.type.is_pyobject:
6392 coerce_result = "__Pyx_PyBoolOrNull_FromLong"
6394 negation = "__Pyx_NegateNonNeg"
6395 if operand2.type is dict_type:
6396 method = "PyDict_Contains"
6398 method = "PySequence_Contains"
6399 if self.type.is_pyobject:
6400 error_clause = code.error_goto_if_null
6401 got_ref = "__Pyx_XGOTREF(%s); " % result_code
6403 error_clause = code.error_goto_if_neg
6406 "%s = %s(%s(%s(%s, %s))); %s%s" % (
6411 operand2.py_result(),
6412 operand1.py_result(),
6414 error_clause(result_code, self.pos)))
6415 elif (operand1.type.is_pyobject
6416 and op not in ('is', 'is_not')):
6417 code.putln("%s = PyObject_RichCompare(%s, %s, %s); %s" % (
6419 operand1.py_result(),
6420 operand2.py_result(),
6421 richcmp_constants[op],
6422 code.error_goto_if_null(result_code, self.pos)))
6423 code.put_gotref(result_code)
6424 elif operand1.type.is_complex:
6429 code.putln("%s = %s(%s%s(%s, %s));" % (
6433 operand1.type.unary_op('eq'),
6437 type1 = operand1.type
6438 type2 = operand2.type
6439 if (type1.is_extension_type or type2.is_extension_type) \
6440 and not type1.same_as(type2):
6441 common_type = py_object_type
6442 elif type1.is_numeric:
6443 common_type = PyrexTypes.widest_numeric_type(type1, type2)
6446 code1 = operand1.result_as(common_type)
6447 code2 = operand2.result_as(common_type)
6448 code.putln("%s = %s(%s %s %s);" % (
6452 self.c_operator(op),
6455 def c_operator(self, op):
6458 elif op == 'is_not':
6463 contains_utility_code = UtilityCode(
6465 static CYTHON_INLINE long __Pyx_NegateNonNeg(long b) { return unlikely(b < 0) ? b : !b; }
6466 static CYTHON_INLINE PyObject* __Pyx_PyBoolOrNull_FromLong(long b) {
6467 return unlikely(b < 0) ? NULL : __Pyx_PyBool_FromLong(b);
6471 char_in_bytes_utility_code = UtilityCode(
6473 static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); /*proto*/
6476 static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) {
6477 const Py_ssize_t length = PyBytes_GET_SIZE(bytes);
6478 char* char_start = PyBytes_AS_STRING(bytes);
6480 for (pos=char_start; pos < char_start+length; pos++) {
6481 if (character == pos[0]) return 1;
6487 pyunicode_in_unicode_utility_code = UtilityCode(
6489 static CYTHON_INLINE int __Pyx_UnicodeContains(PyObject* unicode, Py_UNICODE character); /*proto*/
6492 static CYTHON_INLINE int __Pyx_UnicodeContains(PyObject* unicode, Py_UNICODE character) {
6493 const Py_ssize_t length = PyUnicode_GET_SIZE(unicode);
6494 Py_UNICODE* char_start = PyUnicode_AS_UNICODE(unicode);
6496 for (pos=char_start; pos < char_start+length; pos++) {
6497 if (character == pos[0]) return 1;
6503 pyunicode_equals_utility_code = UtilityCode(
6505 static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/
6508 static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) {
6509 if (s1 == s2) { /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */
6510 return (equals == Py_EQ);
6511 } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) {
6512 if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) {
6513 return (equals == Py_NE);
6514 } else if (PyUnicode_GET_SIZE(s1) == 1) {
6515 if (equals == Py_EQ)
6516 return (PyUnicode_AS_UNICODE(s1)[0] == PyUnicode_AS_UNICODE(s2)[0]);
6518 return (PyUnicode_AS_UNICODE(s1)[0] != PyUnicode_AS_UNICODE(s2)[0]);
6520 int result = PyUnicode_Compare(s1, s2);
6521 if ((result == -1) && unlikely(PyErr_Occurred()))
6523 return (equals == Py_EQ) ? (result == 0) : (result != 0);
6525 } else if ((s1 == Py_None) & (s2 == Py_None)) {
6526 return (equals == Py_EQ);
6527 } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) {
6528 return (equals == Py_NE);
6529 } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) {
6530 return (equals == Py_NE);
6533 PyObject* py_result = PyObject_RichCompare(s1, s2, equals);
6536 result = __Pyx_PyObject_IsTrue(py_result);
6537 Py_DECREF(py_result);
6544 class PrimaryCmpNode(ExprNode, CmpNode):
6545 # Non-cascaded comparison or first comparison of
6546 # a cascaded sequence.
6551 # cascade CascadedCmpNode
6553 # We don't use the subexprs mechanism, because
6554 # things here are too complicated for it to handle.
6555 # Instead, we override all the framework methods
6558 child_attrs = ['operand1', 'operand2', 'cascade']
6562 def infer_type(self, env):
6563 # TODO: Actually implement this (after merging with -unstable).
6564 return py_object_type
6566 def type_dependencies(self, env):
6569 def calculate_constant_result(self):
6570 self.calculate_cascaded_constant_result(self.operand1.constant_result)
6572 def compile_time_value(self, denv):
6573 operand1 = self.operand1.compile_time_value(denv)
6574 return self.cascaded_compile_time_value(operand1, denv)
6576 def analyse_types(self, env):
6577 self.operand1.analyse_types(env)
6578 self.operand2.analyse_types(env)
6579 if self.is_cpp_comparison():
6580 self.analyse_cpp_comparison(env)
6582 error(self.pos, "Cascading comparison not yet supported for cpp types.")
6585 self.cascade.analyse_types(env)
6587 if self.operator in ('in', 'not_in'):
6588 if self.is_c_string_contains():
6589 self.is_pycmp = False
6592 error(self.pos, "Cascading comparison not yet supported for 'int_val in string'.")
6594 if self.operand2.type is unicode_type:
6595 env.use_utility_code(pyunicode_in_unicode_utility_code)
6597 if self.operand1.type is PyrexTypes.c_uchar_type:
6598 self.operand1 = self.operand1.coerce_to(PyrexTypes.c_char_type, env)
6599 if self.operand2.type is not bytes_type:
6600 self.operand2 = self.operand2.coerce_to(bytes_type, env)
6601 env.use_utility_code(char_in_bytes_utility_code)
6602 self.operand2 = self.operand2.as_none_safe_node(
6603 "argument of type 'NoneType' is not iterable")
6604 elif self.is_ptr_contains():
6606 error(self.pos, "Cascading comparison not yet supported for 'val in sliced pointer'.")
6607 self.type = PyrexTypes.c_bint_type
6608 # Will be transformed by IterationTransform
6611 if self.operand2.type is dict_type:
6612 self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
6613 common_type = py_object_type
6614 self.is_pycmp = True
6615 elif self.find_special_bool_compare_function(env):
6616 common_type = None # if coercion needed, the method call above has already done it
6617 self.is_pycmp = False # result is bint
6618 self.is_temp = True # must check for error return
6620 common_type = self.find_common_type(env, self.operator, self.operand1)
6621 self.is_pycmp = common_type.is_pyobject
6623 if common_type is not None and not common_type.is_error:
6624 if self.operand1.type != common_type:
6625 self.operand1 = self.operand1.coerce_to(common_type, env)
6626 self.coerce_operands_to(common_type, env)
6629 self.operand2 = self.operand2.coerce_to_simple(env)
6630 self.cascade.coerce_cascaded_operands_to_temp(env)
6631 if self.is_python_result():
6632 self.type = PyrexTypes.py_object_type
6634 self.type = PyrexTypes.c_bint_type
6637 cdr.type = self.type
6639 if self.is_pycmp or self.cascade:
6642 def analyse_cpp_comparison(self, env):
6643 type1 = self.operand1.type
6644 type2 = self.operand2.type
6645 entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
6647 error(self.pos, "Invalid types for '%s' (%s, %s)" %
6648 (self.operator, type1, type2))
6649 self.type = PyrexTypes.error_type
6650 self.result_code = "<error>"
6652 func_type = entry.type
6653 if func_type.is_ptr:
6654 func_type = func_type.base_type
6655 if len(func_type.args) == 1:
6656 self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
6658 self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
6659 self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
6660 self.type = func_type.return_type
6662 def has_python_operands(self):
6663 return (self.operand1.type.is_pyobject
6664 or self.operand2.type.is_pyobject)
6666 def check_const(self):
6671 return self.operand1.check_const() and self.operand2.check_const()
6673 def calculate_result_code(self):
6674 if self.operand1.type.is_complex:
6675 if self.operator == "!=":
6679 return "(%s%s(%s, %s))" % (
6681 self.operand1.type.binary_op('=='),
6682 self.operand1.result(),
6683 self.operand2.result())
6684 elif self.is_c_string_contains():
6685 if self.operand2.type is bytes_type:
6686 method = "__Pyx_BytesContains"
6688 method = "__Pyx_UnicodeContains"
6689 if self.operator == "not_in":
6693 return "(%s%s(%s, %s))" % (
6696 self.operand2.result(),
6697 self.operand1.result())
6699 return "(%s %s %s)" % (
6700 self.operand1.result(),
6701 self.c_operator(self.operator),
6702 self.operand2.result())
6704 def generate_evaluation_code(self, code):
6705 self.operand1.generate_evaluation_code(code)
6706 self.operand2.generate_evaluation_code(code)
6708 self.allocate_temp_result(code)
6709 self.generate_operation_code(code, self.result(),
6710 self.operand1, self.operator, self.operand2)
6712 self.cascade.generate_evaluation_code(code,
6713 self.result(), self.operand2)
6714 self.operand1.generate_disposal_code(code)
6715 self.operand1.free_temps(code)
6716 self.operand2.generate_disposal_code(code)
6717 self.operand2.free_temps(code)
6719 def generate_subexpr_disposal_code(self, code):
6720 # If this is called, it is a non-cascaded cmp,
6721 # so only need to dispose of the two main operands.
6722 self.operand1.generate_disposal_code(code)
6723 self.operand2.generate_disposal_code(code)
6725 def free_subexpr_temps(self, code):
6726 # If this is called, it is a non-cascaded cmp,
6727 # so only need to dispose of the two main operands.
6728 self.operand1.free_temps(code)
6729 self.operand2.free_temps(code)
6731 def annotate(self, code):
6732 self.operand1.annotate(code)
6733 self.operand2.annotate(code)
6735 self.cascade.annotate(code)
6738 class CascadedCmpNode(Node, CmpNode):
6739 # A CascadedCmpNode is not a complete expression node. It
6740 # hangs off the side of another comparison node, shares
6741 # its left operand with that node, and shares its result
6742 # with the PrimaryCmpNode at the head of the chain.
6746 # cascade CascadedCmpNode
6748 child_attrs = ['operand2', 'cascade']
6751 constant_result = constant_value_not_set # FIXME: where to calculate this?
6753 def infer_type(self, env):
6754 # TODO: Actually implement this (after merging with -unstable).
6755 return py_object_type
6757 def type_dependencies(self, env):
6760 def has_constant_result(self):
6761 return self.constant_result is not constant_value_not_set and \
6762 self.constant_result is not not_a_constant
6764 def analyse_types(self, env):
6765 self.operand2.analyse_types(env)
6767 self.cascade.analyse_types(env)
6769 def has_python_operands(self):
6770 return self.operand2.type.is_pyobject
6772 def coerce_operands_to_pyobjects(self, env):
6773 self.operand2 = self.operand2.coerce_to_pyobject(env)
6774 if self.operand2.type is dict_type and self.operator in ('in', 'not_in'):
6775 self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
6777 self.cascade.coerce_operands_to_pyobjects(env)
6779 def coerce_cascaded_operands_to_temp(self, env):
6781 #self.operand2 = self.operand2.coerce_to_temp(env) #CTT
6782 self.operand2 = self.operand2.coerce_to_simple(env)
6783 self.cascade.coerce_cascaded_operands_to_temp(env)
6785 def generate_evaluation_code(self, code, result, operand1):
6786 if self.type.is_pyobject:
6787 code.putln("if (__Pyx_PyObject_IsTrue(%s)) {" % result)
6788 code.put_decref(result, self.type)
6790 code.putln("if (%s) {" % result)
6791 self.operand2.generate_evaluation_code(code)
6792 self.generate_operation_code(code, result,
6793 operand1, self.operator, self.operand2)
6795 self.cascade.generate_evaluation_code(
6796 code, result, self.operand2)
6797 # Cascaded cmp result is always temp
6798 self.operand2.generate_disposal_code(code)
6799 self.operand2.free_temps(code)
6802 def annotate(self, code):
6803 self.operand2.annotate(code)
6805 self.cascade.annotate(code)
6808 binop_node_classes = {
6809 "or": BoolBinopNode,
6810 "and": BoolBinopNode,
6825 def binop_node(pos, operator, operand1, operand2, inplace=False):
6826 # Construct binop node of appropriate class for
6828 return binop_node_classes[operator](pos,
6829 operator = operator,
6830 operand1 = operand1,
6831 operand2 = operand2,
6834 #-------------------------------------------------------------------
6838 # Coercion nodes are special in that they are created during
6839 # the analyse_types phase of parse tree processing.
6840 # Their __init__ methods consequently incorporate some aspects
6843 #-------------------------------------------------------------------
6845 class CoercionNode(ExprNode):
6846 # Abstract base class for coercion nodes.
6848 # arg ExprNode node being coerced
6851 constant_result = not_a_constant
6853 def __init__(self, arg):
6857 print("%s Coercing %s" % (self, self.arg))
6859 def calculate_constant_result(self):
6860 # constant folding can break type coercion, so this is disabled
6863 def annotate(self, code):
6864 self.arg.annotate(code)
6865 if self.arg.type != self.type:
6866 file, line, col = self.pos
6867 code.annotate((file, line, col-1), AnnotationItem(style='coerce', tag='coerce', text='[%s] to [%s]' % (self.arg.type, self.type)))
6870 class CastNode(CoercionNode):
6871 # Wrap a node in a C type cast.
6873 def __init__(self, arg, new_type):
6874 CoercionNode.__init__(self, arg)
6875 self.type = new_type
6877 def may_be_none(self):
6878 return self.arg.may_be_none()
6880 def calculate_result_code(self):
6881 return self.arg.result_as(self.type)
6883 def generate_result_code(self, code):
6884 self.arg.generate_result_code(code)
6887 class PyTypeTestNode(CoercionNode):
6888 # This node is used to check that a generic Python
6889 # object is an instance of a particular extension type.
6890 # This node borrows the result of its argument node.
6892 def __init__(self, arg, dst_type, env, notnone=False):
6893 # The arg is know to be a Python object, and
6894 # the dst_type is known to be an extension type.
6895 assert dst_type.is_extension_type or dst_type.is_builtin_type, "PyTypeTest on non extension type"
6896 CoercionNode.__init__(self, arg)
6897 self.type = dst_type
6898 self.result_ctype = arg.ctype()
6899 self.notnone = notnone
6901 nogil_check = Node.gil_error
6902 gil_message = "Python type test"
6904 def analyse_types(self, env):
6907 def may_be_none(self):
6910 return self.arg.may_be_none()
6912 def result_in_temp(self):
6913 return self.arg.result_in_temp()
6915 def is_ephemeral(self):
6916 return self.arg.is_ephemeral()
6918 def calculate_constant_result(self):
6922 def calculate_result_code(self):
6923 return self.arg.result()
6925 def generate_result_code(self, code):
6926 if self.type.typeobj_is_available():
6927 if not self.type.is_builtin_type:
6928 code.globalstate.use_utility_code(type_test_utility_code)
6931 self.type.type_test_code(self.arg.py_result(), self.notnone),
6932 code.error_goto(self.pos)))
6934 error(self.pos, "Cannot test type of extern C class "
6935 "without type object name specification")
6937 def generate_post_assignment_code(self, code):
6938 self.arg.generate_post_assignment_code(code)
6940 def free_temps(self, code):
6941 self.arg.free_temps(code)
6944 class NoneCheckNode(CoercionNode):
6945 # This node is used to check that a Python object is not None and
6946 # raises an appropriate exception (as specified by the creating
6949 def __init__(self, arg, exception_type_cname, exception_message):
6950 CoercionNode.__init__(self, arg)
6951 self.type = arg.type
6952 self.result_ctype = arg.ctype()
6953 self.exception_type_cname = exception_type_cname
6954 self.exception_message = exception_message
6956 def analyse_types(self, env):
6959 def may_be_none(self):
6962 def result_in_temp(self):
6963 return self.arg.result_in_temp()
6965 def calculate_result_code(self):
6966 return self.arg.result()
6968 def generate_result_code(self, code):
6970 "if (unlikely(%s == Py_None)) {" % self.arg.result())
6971 code.putln('PyErr_SetString(%s, "%s"); %s ' % (
6972 self.exception_type_cname,
6973 StringEncoding.escape_byte_string(
6974 self.exception_message.encode('UTF-8')),
6975 code.error_goto(self.pos)))
6978 def generate_post_assignment_code(self, code):
6979 self.arg.generate_post_assignment_code(code)
6981 def free_temps(self, code):
6982 self.arg.free_temps(code)
6985 class CoerceToPyTypeNode(CoercionNode):
6986 # This node is used to convert a C data type
6987 # to a Python object.
6989 type = py_object_type
6992 def __init__(self, arg, env, type=py_object_type):
6993 CoercionNode.__init__(self, arg)
6994 if not arg.type.create_to_py_utility_code(env):
6996 "Cannot convert '%s' to Python object" % arg.type)
6997 if type is not py_object_type:
6998 self.type = py_object_type
6999 elif arg.type.is_string:
7000 self.type = bytes_type
7001 elif arg.type is PyrexTypes.c_py_unicode_type:
7002 self.type = unicode_type
7004 gil_message = "Converting to Python object"
7006 def may_be_none(self):
7007 # FIXME: is this always safe?
7010 def coerce_to_boolean(self, env):
7011 arg_type = self.arg.type
7012 if (arg_type == PyrexTypes.c_bint_type or
7013 (arg_type.is_pyobject and arg_type.name == 'bool')):
7014 return self.arg.coerce_to_temp(env)
7016 return CoerceToBooleanNode(self, env)
7018 def coerce_to_integer(self, env):
7019 # If not already some C integer type, coerce to longint.
7020 if self.arg.type.is_int:
7023 return self.arg.coerce_to(PyrexTypes.c_long_type, env)
7025 def analyse_types(self, env):
7026 # The arg is always already analysed
7029 def generate_result_code(self, code):
7030 function = self.arg.type.to_py_function
7031 code.putln('%s = %s(%s); %s' % (
7035 code.error_goto_if_null(self.result(), self.pos)))
7036 code.put_gotref(self.py_result())
7039 class CoerceIntToBytesNode(CoerceToPyTypeNode):
7040 # This node is used to convert a C int type to a Python bytes
7045 def __init__(self, arg, env):
7046 arg = arg.coerce_to_simple(env)
7047 CoercionNode.__init__(self, arg)
7048 self.type = Builtin.bytes_type
7050 def generate_result_code(self, code):
7052 arg_result = arg.result()
7053 if arg.type not in (PyrexTypes.c_char_type,
7054 PyrexTypes.c_uchar_type,
7055 PyrexTypes.c_schar_type):
7057 code.putln("if ((%s < 0) || (%s > 255)) {" % (
7058 arg_result, arg_result))
7060 code.putln("if (%s > 255) {" % arg_result)
7061 code.putln('PyErr_Format(PyExc_OverflowError, '
7062 '"value too large to pack into a byte"); %s' % (
7063 code.error_goto(self.pos)))
7066 if arg.type is not PyrexTypes.c_char_type:
7067 temp = code.funcstate.allocate_temp(PyrexTypes.c_char_type, manage_ref=False)
7068 code.putln("%s = (char)%s;" % (temp, arg_result))
7070 code.putln('%s = PyBytes_FromStringAndSize(&%s, 1); %s' % (
7073 code.error_goto_if_null(self.result(), self.pos)))
7074 if temp is not None:
7075 code.funcstate.release_temp(temp)
7076 code.put_gotref(self.py_result())
7079 class CoerceFromPyTypeNode(CoercionNode):
7080 # This node is used to convert a Python object
7083 def __init__(self, result_type, arg, env):
7084 CoercionNode.__init__(self, arg)
7085 self.type = result_type
7087 if not result_type.create_from_py_utility_code(env):
7089 "Cannot convert Python object to '%s'" % result_type)
7090 if self.type.is_string and self.arg.is_ephemeral():
7092 "Obtaining char * from temporary Python value")
7094 def analyse_types(self, env):
7095 # The arg is always already analysed
7098 def generate_result_code(self, code):
7099 function = self.type.from_py_function
7100 operand = self.arg.py_result()
7101 rhs = "%s(%s)" % (function, operand)
7102 if self.type.is_enum:
7103 rhs = typecast(self.type, c_long_type, rhs)
7104 code.putln('%s = %s; %s' % (
7107 code.error_goto_if(self.type.error_condition(self.result()), self.pos)))
7108 if self.type.is_pyobject:
7109 code.put_gotref(self.py_result())
7112 class CoerceToBooleanNode(CoercionNode):
7113 # This node is used when a result needs to be used
7114 # in a boolean context.
7116 type = PyrexTypes.c_bint_type
7118 _special_builtins = {
7119 Builtin.list_type : 'PyList_GET_SIZE',
7120 Builtin.tuple_type : 'PyTuple_GET_SIZE',
7121 Builtin.bytes_type : 'PyBytes_GET_SIZE',
7122 Builtin.unicode_type : 'PyUnicode_GET_SIZE',
7125 def __init__(self, arg, env):
7126 CoercionNode.__init__(self, arg)
7127 if arg.type.is_pyobject:
7130 def nogil_check(self, env):
7131 if self.arg.type.is_pyobject and self._special_builtins.get(self.arg.type) is None:
7134 gil_message = "Truth-testing Python object"
7136 def check_const(self):
7140 return self.arg.check_const()
7142 def calculate_result_code(self):
7143 return "(%s != 0)" % self.arg.result()
7145 def generate_result_code(self, code):
7146 if not self.is_temp:
7148 test_func = self._special_builtins.get(self.arg.type)
7149 if test_func is not None:
7150 code.putln("%s = (%s != Py_None) && (%s(%s) != 0);" % (
7152 self.arg.py_result(),
7154 self.arg.py_result()))
7157 "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
7159 self.arg.py_result(),
7160 code.error_goto_if_neg(self.result(), self.pos)))
7162 class CoerceToComplexNode(CoercionNode):
7164 def __init__(self, arg, dst_type, env):
7165 if arg.type.is_complex:
7166 arg = arg.coerce_to_simple(env)
7167 self.type = dst_type
7168 CoercionNode.__init__(self, arg)
7169 dst_type.create_declaration_utility_code(env)
7171 def calculate_result_code(self):
7172 if self.arg.type.is_complex:
7173 real_part = "__Pyx_CREAL(%s)" % self.arg.result()
7174 imag_part = "__Pyx_CIMAG(%s)" % self.arg.result()
7176 real_part = self.arg.result()
7178 return "%s(%s, %s)" % (
7179 self.type.from_parts,
7183 def generate_result_code(self, code):
7186 class CoerceToTempNode(CoercionNode):
7187 # This node is used to force the result of another node
7188 # to be stored in a temporary. It is only used if the
7189 # argument node's result is not already in a temporary.
7191 def __init__(self, arg, env):
7192 CoercionNode.__init__(self, arg)
7193 self.type = self.arg.type
7194 self.constant_result = self.arg.constant_result
7196 if self.type.is_pyobject:
7197 self.result_ctype = py_object_type
7199 gil_message = "Creating temporary Python reference"
7201 def analyse_types(self, env):
7202 # The arg is always already analysed
7205 def coerce_to_boolean(self, env):
7206 self.arg = self.arg.coerce_to_boolean(env)
7207 if self.arg.is_simple():
7209 self.type = self.arg.type
7210 self.result_ctype = self.type
7213 def generate_result_code(self, code):
7214 #self.arg.generate_evaluation_code(code) # Already done
7215 # by generic generate_subexpr_evaluation_code!
7216 code.putln("%s = %s;" % (
7217 self.result(), self.arg.result_as(self.ctype())))
7218 if self.type.is_pyobject and self.use_managed_ref:
7219 code.put_incref(self.result(), self.ctype())
7222 class CloneNode(CoercionNode):
7223 # This node is employed when the result of another node needs
7224 # to be used multiple times. The argument node's result must
7225 # be in a temporary. This node "borrows" the result from the
7226 # argument node, and does not generate any evaluation or
7227 # disposal code for it. The original owner of the argument
7228 # node is responsible for doing those things.
7230 subexprs = [] # Arg is not considered a subexpr
7233 def __init__(self, arg):
7234 CoercionNode.__init__(self, arg)
7235 if hasattr(arg, 'type'):
7236 self.type = arg.type
7237 self.result_ctype = arg.result_ctype
7238 if hasattr(arg, 'entry'):
7239 self.entry = arg.entry
7242 return self.arg.result()
7244 def type_dependencies(self, env):
7245 return self.arg.type_dependencies(env)
7247 def infer_type(self, env):
7248 return self.arg.infer_type(env)
7250 def analyse_types(self, env):
7251 self.type = self.arg.type
7252 self.result_ctype = self.arg.result_ctype
7254 if hasattr(self.arg, 'entry'):
7255 self.entry = self.arg.entry
7257 def generate_evaluation_code(self, code):
7260 def generate_result_code(self, code):
7263 def generate_disposal_code(self, code):
7266 def free_temps(self, code):
7270 class ModuleRefNode(ExprNode):
7271 # Simple returns the module object
7273 type = py_object_type
7277 def analyse_types(self, env):
7280 def may_be_none(self):
7283 def calculate_result_code(self):
7284 return Naming.module_cname
7286 def generate_result_code(self, code):
7289 class DocstringRefNode(ExprNode):
7290 # Extracts the docstring of the body element
7293 type = py_object_type
7296 def __init__(self, pos, body):
7297 ExprNode.__init__(self, pos)
7298 assert body.type.is_pyobject
7301 def analyse_types(self, env):
7304 def generate_result_code(self, code):
7305 code.putln('%s = __Pyx_GetAttrString(%s, "__doc__"); %s' % (
7306 self.result(), self.body.result(),
7307 code.error_goto_if_null(self.result(), self.pos)))
7308 code.put_gotref(self.result())
7312 #------------------------------------------------------------------------------------
7314 # Runtime support code
7316 #------------------------------------------------------------------------------------
7318 get_name_interned_utility_code = UtilityCode(
7320 static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
7323 static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
7325 result = PyObject_GetAttr(dict, name);
7327 PyErr_SetObject(PyExc_NameError, name);
7332 #------------------------------------------------------------------------------------
7334 import_utility_code = UtilityCode(
7336 static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/
7339 static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) {
7340 PyObject *py_import = 0;
7341 PyObject *empty_list = 0;
7342 PyObject *module = 0;
7343 PyObject *global_dict = 0;
7344 PyObject *empty_dict = 0;
7346 py_import = __Pyx_GetAttrString(%(BUILTINS)s, "__import__");
7352 empty_list = PyList_New(0);
7357 global_dict = PyModule_GetDict(%(GLOBALS)s);
7360 empty_dict = PyDict_New();
7363 module = PyObject_CallFunctionObjArgs(py_import,
7364 name, global_dict, empty_dict, list, NULL);
7366 Py_XDECREF(empty_list);
7367 Py_XDECREF(py_import);
7368 Py_XDECREF(empty_dict);
7372 "BUILTINS": Naming.builtins_cname,
7373 "GLOBALS": Naming.module_cname,
7376 #------------------------------------------------------------------------------------
7378 get_exception_utility_code = UtilityCode(
7380 static PyObject *__Pyx_GetExcValue(void); /*proto*/
7383 static PyObject *__Pyx_GetExcValue(void) {
7384 PyObject *type = 0, *value = 0, *tb = 0;
7385 PyObject *tmp_type, *tmp_value, *tmp_tb;
7386 PyObject *result = 0;
7387 PyThreadState *tstate = PyThreadState_Get();
7388 PyErr_Fetch(&type, &value, &tb);
7389 PyErr_NormalizeException(&type, &value, &tb);
7390 if (PyErr_Occurred())
7396 tmp_type = tstate->exc_type;
7397 tmp_value = tstate->exc_value;
7398 tmp_tb = tstate->exc_traceback;
7399 tstate->exc_type = type;
7400 tstate->exc_value = value;
7401 tstate->exc_traceback = tb;
7402 /* Make sure tstate is in a consistent state when we XDECREF
7403 these objects (XDECREF may run arbitrary code). */
7404 Py_XDECREF(tmp_type);
7405 Py_XDECREF(tmp_value);
7420 #------------------------------------------------------------------------------------
7422 type_test_utility_code = UtilityCode(
7424 static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/
7427 static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) {
7428 if (unlikely(!type)) {
7429 PyErr_Format(PyExc_SystemError, "Missing type object");
7432 if (likely(PyObject_TypeCheck(obj, type)))
7434 PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s",
7435 Py_TYPE(obj)->tp_name, type->tp_name);
7440 #------------------------------------------------------------------------------------
7442 create_class_utility_code = UtilityCode(
7444 static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name,
7445 PyObject *modname); /*proto*/
7448 static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name,
7449 PyObject *modname) {
7450 PyObject *result = NULL;
7451 PyObject *metaclass = NULL;
7453 if (PyDict_SetItemString(dict, "__module__", modname) < 0)
7456 /* Python2 __metaclass__ */
7457 metaclass = PyDict_GetItemString(dict, "__metaclass__");
7460 /* Default metaclass */
7461 #if PY_MAJOR_VERSION < 3
7462 if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7463 PyObject *base = PyTuple_GET_ITEM(bases, 0);
7464 metaclass = PyObject_GetAttrString(base, "__class__");
7467 metaclass = (PyObject *)base->ob_type;
7470 metaclass = (PyObject *) &PyClass_Type;
7472 if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7473 PyObject *base = PyTuple_GET_ITEM(bases, 0);
7474 metaclass = (PyObject *)base->ob_type;
7476 metaclass = (PyObject *) &PyType_Type;
7479 Py_INCREF(metaclass);
7481 result = PyObject_CallFunctionObjArgs(metaclass, name, bases, dict, NULL);
7482 Py_DECREF(metaclass);
7487 #------------------------------------------------------------------------------------
7489 create_py3class_utility_code = UtilityCode(
7491 static PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw);
7492 static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *mkw, PyObject *modname, PyObject *doc);
7493 static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, PyObject *mkw);
7496 PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw)
7498 PyObject *metaclass = NULL;
7500 metaclass = PyDict_GetItemString(mkw, "metaclass");
7502 Py_INCREF(metaclass);
7503 if (PyDict_DelItemString(mkw, "metaclass") < 0) {
7504 Py_DECREF(metaclass);
7509 /* Default metaclass */
7510 #if PY_MAJOR_VERSION < 3
7511 if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7512 PyObject *base = PyTuple_GET_ITEM(bases, 0);
7513 metaclass = PyObject_GetAttrString(base, "__class__");
7514 if (metaclass == NULL) {
7516 metaclass = (PyObject *)base->ob_type;
7519 metaclass = (PyObject *) &PyClass_Type;
7522 if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7523 PyObject *base = PyTuple_GET_ITEM(bases, 0);
7524 metaclass = (PyObject *)base->ob_type;
7526 metaclass = (PyObject *) &PyType_Type;
7529 Py_INCREF(metaclass);
7533 PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *mkw, PyObject *modname, PyObject *doc)
7540 prep = PyObject_GetAttrString(metaclass, "__prepare__");
7542 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
7545 return PyDict_New();
7547 pargs = PyTuple_New(2);
7555 PyTuple_SET_ITEM(pargs, 0, name);
7556 PyTuple_SET_ITEM(pargs, 1, bases);
7558 ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
7566 /* Required here to emulate assignment order */
7567 /* XXX: use consts here */
7568 #if PY_MAJOR_VERSION >= 3
7569 str = PyUnicode_FromString("__module__");
7571 str = PyString_FromString("__module__");
7578 if (PyObject_SetItem(ns, str, modname) < 0) {
7585 #if PY_MAJOR_VERSION >= 3
7586 str = PyUnicode_FromString("__doc__");
7588 str = PyString_FromString("__doc__");
7594 if (PyObject_SetItem(ns, str, doc) < 0) {
7604 PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, PyObject *mkw)
7609 margs = PyTuple_Pack(3, name, bases, dict, NULL);
7612 result = PyEval_CallObjectWithKeywords(metaclass, margs, mkw);
7618 #------------------------------------------------------------------------------------
7620 cpp_exception_utility_code = UtilityCode(
7622 #ifndef __Pyx_CppExn2PyErr
7623 static void __Pyx_CppExn2PyErr() {
7625 if (PyErr_Occurred())
7626 ; // let the latest Python exn pass through and ignore the current one
7629 } catch (const std::invalid_argument& exn) {
7630 // Catch a handful of different errors here and turn them into the
7631 // equivalent Python errors.
7632 // Change invalid_argument to ValueError
7633 PyErr_SetString(PyExc_ValueError, exn.what());
7634 } catch (const std::out_of_range& exn) {
7635 // Change out_of_range to IndexError
7636 PyErr_SetString(PyExc_IndexError, exn.what());
7637 } catch (const std::exception& exn) {
7638 PyErr_SetString(PyExc_RuntimeError, exn.what());
7642 PyErr_SetString(PyExc_RuntimeError, "Unknown exception");
7650 pyerr_occurred_withgil_utility_code= UtilityCode(
7652 static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void); /* proto */
7655 static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void) {
7658 PyGILState_STATE _save = PyGILState_Ensure();
7660 err = !!PyErr_Occurred();
7662 PyGILState_Release(_save);
7669 #------------------------------------------------------------------------------------
7671 raise_noneattr_error_utility_code = UtilityCode(
7673 static CYTHON_INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname);
7676 static CYTHON_INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname) {
7677 PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", attrname);
7681 raise_noneindex_error_utility_code = UtilityCode(
7683 static CYTHON_INLINE void __Pyx_RaiseNoneIndexingError(void);
7686 static CYTHON_INLINE void __Pyx_RaiseNoneIndexingError(void) {
7687 PyErr_SetString(PyExc_TypeError, "'NoneType' object is unsubscriptable");
7691 raise_none_iter_error_utility_code = UtilityCode(
7693 static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void);
7696 static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) {
7697 PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
7701 #------------------------------------------------------------------------------------
7703 getitem_dict_utility_code = UtilityCode(
7705 #if PY_MAJOR_VERSION >= 3
7706 static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) {
7708 if (unlikely(d == Py_None)) {
7709 __Pyx_RaiseNoneIndexingError();
7712 value = PyDict_GetItemWithError(d, key);
7713 if (unlikely(!value)) {
7714 if (!PyErr_Occurred())
7715 PyErr_SetObject(PyExc_KeyError, key);
7722 #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key)
7725 requires = [raise_noneindex_error_utility_code])
7727 #------------------------------------------------------------------------------------
7729 getitem_int_pyunicode_utility_code = UtilityCode(
7731 #define __Pyx_GetItemInt_Unicode(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7732 __Pyx_GetItemInt_Unicode_Fast(o, i) : \\
7733 __Pyx_GetItemInt_Unicode_Generic(o, to_py_func(i)))
7735 static CYTHON_INLINE Py_UNICODE __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i) {
7736 if (likely((0 <= i) & (i < PyUnicode_GET_SIZE(ustring)))) {
7737 return PyUnicode_AS_UNICODE(ustring)[i];
7738 } else if ((-PyUnicode_GET_SIZE(ustring) <= i) & (i < 0)) {
7739 i += PyUnicode_GET_SIZE(ustring);
7740 return PyUnicode_AS_UNICODE(ustring)[i];
7742 PyErr_SetString(PyExc_IndexError, "string index out of range");
7743 return (Py_UNICODE)-1;
7747 static CYTHON_INLINE Py_UNICODE __Pyx_GetItemInt_Unicode_Generic(PyObject* ustring, PyObject* j) {
7749 PyObject *uchar_string;
7750 if (!j) return (Py_UNICODE)-1;
7751 uchar_string = PyObject_GetItem(ustring, j);
7753 if (!uchar_string) return (Py_UNICODE)-1;
7754 uchar = PyUnicode_AS_UNICODE(uchar_string)[0];
7755 Py_DECREF(uchar_string);
7760 getitem_int_utility_code = UtilityCode(
7763 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) {
7765 if (!j) return NULL;
7766 r = PyObject_GetItem(o, j);
7773 #define __Pyx_GetItemInt_%(type)s(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7774 __Pyx_GetItemInt_%(type)s_Fast(o, i) : \\
7775 __Pyx_GetItemInt_Generic(o, to_py_func(i)))
7777 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_%(type)s_Fast(PyObject *o, Py_ssize_t i) {
7778 if (likely(o != Py_None)) {
7779 if (likely((0 <= i) & (i < Py%(type)s_GET_SIZE(o)))) {
7780 PyObject *r = Py%(type)s_GET_ITEM(o, i);
7784 else if ((-Py%(type)s_GET_SIZE(o) <= i) & (i < 0)) {
7785 PyObject *r = Py%(type)s_GET_ITEM(o, Py%(type)s_GET_SIZE(o) + i);
7790 return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
7792 """ % {'type' : type_name} for type_name in ('List', 'Tuple')
7795 #define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7796 __Pyx_GetItemInt_Fast(o, i) : \\
7797 __Pyx_GetItemInt_Generic(o, to_py_func(i)))
7799 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) {
7801 if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
7802 r = PyList_GET_ITEM(o, i);
7805 else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) {
7806 r = PyTuple_GET_ITEM(o, i);
7809 else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) {
7810 r = PySequence_GetItem(o, i);
7813 r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
7823 #------------------------------------------------------------------------------------
7825 setitem_int_utility_code = UtilityCode(
7827 #define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7828 __Pyx_SetItemInt_Fast(o, i, v) : \\
7829 __Pyx_SetItemInt_Generic(o, to_py_func(i), v))
7831 static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) {
7834 r = PyObject_SetItem(o, j, v);
7839 static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) {
7840 if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
7842 Py_DECREF(PyList_GET_ITEM(o, i));
7843 PyList_SET_ITEM(o, i, v);
7846 else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0)))
7847 return PySequence_SetItem(o, i, v);
7849 PyObject *j = PyInt_FromSsize_t(i);
7850 return __Pyx_SetItemInt_Generic(o, j, v);
7857 #------------------------------------------------------------------------------------
7859 delitem_int_utility_code = UtilityCode(
7861 #define __Pyx_DelItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7862 __Pyx_DelItemInt_Fast(o, i) : \\
7863 __Pyx_DelItem_Generic(o, to_py_func(i)))
7865 static CYTHON_INLINE int __Pyx_DelItem_Generic(PyObject *o, PyObject *j) {
7868 r = PyObject_DelItem(o, j);
7873 static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i) {
7874 if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && likely(i >= 0))
7875 return PySequence_DelItem(o, i);
7877 PyObject *j = PyInt_FromSsize_t(i);
7878 return __Pyx_DelItem_Generic(o, j);
7885 #------------------------------------------------------------------------------------
7887 raise_too_many_values_to_unpack = UtilityCode(
7889 static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected);
7892 static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) {
7893 PyErr_Format(PyExc_ValueError,
7894 #if PY_VERSION_HEX < 0x02050000
7895 "too many values to unpack (expected %d)", (int)expected);
7897 "too many values to unpack (expected %zd)", expected);
7902 raise_need_more_values_to_unpack = UtilityCode(
7904 static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index);
7907 static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) {
7908 PyErr_Format(PyExc_ValueError,
7909 #if PY_VERSION_HEX < 0x02050000
7910 "need more than %d value%s to unpack", (int)index,
7912 "need more than %zd value%s to unpack", index,
7914 (index == 1) ? "" : "s");
7918 #------------------------------------------------------------------------------------
7920 tuple_unpacking_error_code = UtilityCode(
7922 static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/
7925 static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) {
7927 __Pyx_RaiseNoneNotIterableError();
7928 } else if (PyTuple_GET_SIZE(t) < index) {
7929 __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t));
7931 __Pyx_RaiseTooManyValuesError(index);
7935 requires = [raise_none_iter_error_utility_code,
7936 raise_need_more_values_to_unpack,
7937 raise_too_many_values_to_unpack]
7940 unpacking_utility_code = UtilityCode(
7942 static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/
7943 static int __Pyx_EndUnpack(PyObject *, Py_ssize_t expected); /*proto*/
7946 static PyObject *__Pyx_UnpackItem(PyObject *iter, Py_ssize_t index) {
7948 if (!(item = PyIter_Next(iter))) {
7949 if (!PyErr_Occurred()) {
7950 __Pyx_RaiseNeedMoreValuesError(index);
7956 static int __Pyx_EndUnpack(PyObject *iter, Py_ssize_t expected) {
7958 if ((item = PyIter_Next(iter))) {
7960 __Pyx_RaiseTooManyValuesError(expected);
7963 else if (!PyErr_Occurred())
7969 requires = [raise_need_more_values_to_unpack,
7970 raise_too_many_values_to_unpack]
7973 #------------------------------------------------------------------------------------
7975 # CPython supports calling functions with non-dict kwargs by
7976 # converting them to a dict first
7978 kwargs_call_utility_code = UtilityCode(
7980 static PyObject* __Pyx_PyEval_CallObjectWithKeywords(PyObject*, PyObject*, PyObject*); /*proto*/
7983 static PyObject* __Pyx_PyEval_CallObjectWithKeywords(PyObject *callable, PyObject *args, PyObject *kwargs) {
7985 if (likely(PyDict_Check(kwargs))) {
7986 return PyEval_CallObjectWithKeywords(callable, args, kwargs);
7988 PyObject* real_dict;
7989 real_dict = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, kwargs, NULL);
7990 if (unlikely(!real_dict))
7992 result = PyEval_CallObjectWithKeywords(callable, args, real_dict);
7993 Py_DECREF(real_dict);
7994 return result; /* may be NULL */
8001 #------------------------------------------------------------------------------------
8003 int_pow_utility_code = UtilityCode(
8005 static CYTHON_INLINE %(type)s %(func_name)s(%(type)s, %(type)s); /* proto */
8008 static CYTHON_INLINE %(type)s %(func_name)s(%(type)s b, %(type)s e) {
8020 if (unlikely(e<0)) return 0;
8023 t *= (b * (e&1)) | ((~e)&1); /* 1 or b */
8031 # ------------------------------ Division ------------------------------------
8033 div_int_utility_code = UtilityCode(
8035 static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s, %(type)s); /* proto */
8038 static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s a, %(type)s b) {
8040 %(type)s r = a - q*b;
8041 q -= ((r != 0) & ((r ^ b) < 0));
8046 mod_int_utility_code = UtilityCode(
8048 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
8051 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
8052 %(type)s r = a %% b;
8053 r += ((r != 0) & ((r ^ b) < 0)) * b;
8058 mod_float_utility_code = UtilityCode(
8060 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
8063 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
8064 %(type)s r = fmod%(math_h_modifier)s(a, b);
8065 r += ((r != 0) & ((r < 0) ^ (b < 0))) * b;
8070 cdivision_warning_utility_code = UtilityCode(
8072 static int __Pyx_cdivision_warning(void); /* proto */
8075 static int __Pyx_cdivision_warning(void) {
8076 return PyErr_WarnExplicit(PyExc_RuntimeWarning,
8077 "division with oppositely signed operands, C and Python semantics differ",
8084 'FILENAME': Naming.filename_cname,
8085 'LINENO': Naming.lineno_cname,
8089 division_overflow_test_code = UtilityCode(
8091 #define UNARY_NEG_WOULD_OVERFLOW(x) \
8092 (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x)))
8096 binding_cfunc_utility_code = UtilityCode(
8098 #define %(binding_cfunc)s_USED 1
8101 PyCFunctionObject func;
8102 } %(binding_cfunc)s_object;
8104 PyTypeObject %(binding_cfunc)s_type;
8105 PyTypeObject *%(binding_cfunc)s = NULL;
8107 PyObject *%(binding_cfunc)s_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module); /* proto */
8108 #define %(binding_cfunc)s_New(ml, self) %(binding_cfunc)s_NewEx(ml, self, NULL)
8110 int %(binding_cfunc)s_init(void); /* proto */
8111 """ % Naming.__dict__,
8114 PyObject *%(binding_cfunc)s_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) {
8115 %(binding_cfunc)s_object *op = PyObject_GC_New(%(binding_cfunc)s_object, %(binding_cfunc)s);
8120 op->func.m_self = self;
8122 op->func.m_module = module;
8123 PyObject_GC_Track(op);
8124 return (PyObject *)op;
8127 static void %(binding_cfunc)s_dealloc(%(binding_cfunc)s_object *m) {
8128 PyObject_GC_UnTrack(m);
8129 Py_XDECREF(m->func.m_self);
8130 Py_XDECREF(m->func.m_module);
8134 static PyObject *%(binding_cfunc)s_descr_get(PyObject *func, PyObject *obj, PyObject *type) {
8137 return PyMethod_New(func, obj, type);
8140 int %(binding_cfunc)s_init(void) {
8141 %(binding_cfunc)s_type = PyCFunction_Type;
8142 %(binding_cfunc)s_type.tp_name = __Pyx_NAMESTR("cython_binding_builtin_function_or_method");
8143 %(binding_cfunc)s_type.tp_dealloc = (destructor)%(binding_cfunc)s_dealloc;
8144 %(binding_cfunc)s_type.tp_descr_get = %(binding_cfunc)s_descr_get;
8145 if (PyType_Ready(&%(binding_cfunc)s_type) < 0) {
8148 %(binding_cfunc)s = &%(binding_cfunc)s_type;
8152 """ % Naming.__dict__)