varargs tempification needs to be done for all varargs, not only Python objects
[cython.git] / Cython / Compiler / ExprNodes.py
1 #
2 #   Pyrex - Parse tree nodes for expressions
3 #
4
5 import cython
6 from cython import set
7 cython.declare(error=object, warning=object, warn_once=object, InternalError=object,
8                CompileError=object, UtilityCode=object, StringEncoding=object, operator=object,
9                Naming=object, Nodes=object, PyrexTypes=object, py_object_type=object,
10                list_type=object, tuple_type=object, set_type=object, dict_type=object, \
11                unicode_type=object, str_type=object, bytes_type=object, type_type=object,
12                Builtin=object, Symtab=object, Utils=object, find_coercion_error=object,
13                debug_disposal_code=object, debug_temp_alloc=object, debug_coercion=object)
14
15 import operator
16
17 from Errors import error, warning, warn_once, InternalError, CompileError
18 from Errors import hold_errors, release_errors, held_errors, report_error
19 from Code import UtilityCode
20 import StringEncoding
21 import Naming
22 import Nodes
23 from Nodes import Node
24 import PyrexTypes
25 from PyrexTypes import py_object_type, c_long_type, typecast, error_type, \
26      unspecified_type
27 from Builtin import list_type, tuple_type, set_type, dict_type, \
28      unicode_type, str_type, bytes_type, type_type
29 import Builtin
30 import Symtab
31 import Options
32 from Cython import Utils
33 from Annotate import AnnotationItem
34
35 from Cython.Debugging import print_call_chain
36 from DebugFlags import debug_disposal_code, debug_temp_alloc, \
37     debug_coercion
38
39 try:
40     from __builtin__ import basestring
41 except ImportError:
42     basestring = str # Python 3
43
44 class NotConstant(object):
45     def __repr__(self):
46         return "<NOT CONSTANT>"
47
48 not_a_constant = NotConstant()
49 constant_value_not_set = object()
50
51 # error messages when coercing from key[0] to key[1]
52 find_coercion_error = {
53     # string related errors
54     (Builtin.unicode_type, Builtin.bytes_type) : "Cannot convert Unicode string to 'bytes' implicitly, encoding required.",
55     (Builtin.unicode_type, Builtin.str_type)   : "Cannot convert Unicode string to 'str' implicitly. This is not portable and requires explicit encoding.",
56     (Builtin.unicode_type, PyrexTypes.c_char_ptr_type) : "Unicode objects do not support coercion to C types.",
57     (Builtin.bytes_type, Builtin.unicode_type) : "Cannot convert 'bytes' object to unicode implicitly, decoding required",
58     (Builtin.bytes_type, Builtin.str_type) : "Cannot convert 'bytes' object to str implicitly. This is not portable to Py3.",
59     (Builtin.str_type, Builtin.unicode_type) : "str objects do not support coercion to unicode, use a unicode string literal instead (u'')",
60     (Builtin.str_type, Builtin.bytes_type) : "Cannot convert 'str' to 'bytes' implicitly. This is not portable.",
61     (Builtin.str_type, PyrexTypes.c_char_ptr_type) : "'str' objects do not support coercion to C types (use 'bytes'?).",
62     (PyrexTypes.c_char_ptr_type, Builtin.unicode_type) : "Cannot convert 'char*' to unicode implicitly, decoding required",
63     (PyrexTypes.c_uchar_ptr_type, Builtin.unicode_type) : "Cannot convert 'char*' to unicode implicitly, decoding required",
64     }.get
65
66
67 class ExprNode(Node):
68     #  subexprs     [string]     Class var holding names of subexpr node attrs
69     #  type         PyrexType    Type of the result
70     #  result_code  string       Code fragment
71     #  result_ctype string       C type of result_code if different from type
72     #  is_temp      boolean      Result is in a temporary variable
73     #  is_sequence_constructor
74     #               boolean      Is a list or tuple constructor expression
75     #  is_starred   boolean      Is a starred expression (e.g. '*a')
76     #  saved_subexpr_nodes
77     #               [ExprNode or [ExprNode or None] or None]
78     #                            Cached result of subexpr_nodes()
79     #  use_managed_ref boolean   use ref-counted temps/assignments/etc.
80
81     result_ctype = None
82     type = None
83     temp_code = None
84     old_temp = None # error checker for multiple frees etc.
85     use_managed_ref = True # can be set by optimisation transforms
86
87     #  The Analyse Expressions phase for expressions is split
88     #  into two sub-phases:
89     #
90     #    Analyse Types
91     #      Determines the result type of the expression based
92     #      on the types of its sub-expressions, and inserts
93     #      coercion nodes into the expression tree where needed.
94     #      Marks nodes which will need to have temporary variables
95     #      allocated.
96     #
97     #    Allocate Temps
98     #      Allocates temporary variables where needed, and fills
99     #      in the result_code field of each node.
100     #
101     #  ExprNode provides some convenience routines which
102     #  perform both of the above phases. These should only
103     #  be called from statement nodes, and only when no
104     #  coercion nodes need to be added around the expression
105     #  being analysed. In that case, the above two phases
106     #  should be invoked separately.
107     #
108     #  Framework code in ExprNode provides much of the common
109     #  processing for the various phases. It makes use of the
110     #  'subexprs' class attribute of ExprNodes, which should
111     #  contain a list of the names of attributes which can
112     #  hold sub-nodes or sequences of sub-nodes.
113     #
114     #  The framework makes use of a number of abstract methods.
115     #  Their responsibilities are as follows.
116     #
117     #    Declaration Analysis phase
118     #
119     #      analyse_target_declaration
120     #        Called during the Analyse Declarations phase to analyse
121     #        the LHS of an assignment or argument of a del statement.
122     #        Nodes which cannot be the LHS of an assignment need not
123     #        implement it.
124     #
125     #    Expression Analysis phase
126     #
127     #      analyse_types
128     #        - Call analyse_types on all sub-expressions.
129     #        - Check operand types, and wrap coercion nodes around
130     #          sub-expressions where needed.
131     #        - Set the type of this node.
132     #        - If a temporary variable will be required for the
133     #          result, set the is_temp flag of this node.
134     #
135     #      analyse_target_types
136     #        Called during the Analyse Types phase to analyse
137     #        the LHS of an assignment or argument of a del
138     #        statement. Similar responsibilities to analyse_types.
139     #
140     #      target_code
141     #        Called by the default implementation of allocate_target_temps.
142     #        Should return a C lvalue for assigning to the node. The default
143     #        implementation calls calculate_result_code.
144     #
145     #      check_const
146     #        - Check that this node and its subnodes form a
147     #          legal constant expression. If so, do nothing,
148     #          otherwise call not_const.
149     #
150     #        The default implementation of check_const
151     #        assumes that the expression is not constant.
152     #
153     #      check_const_addr
154     #        - Same as check_const, except check that the
155     #          expression is a C lvalue whose address is
156     #          constant. Otherwise, call addr_not_const.
157     #
158     #        The default implementation of calc_const_addr
159     #        assumes that the expression is not a constant
160     #        lvalue.
161     #
162     #   Code Generation phase
163     #
164     #      generate_evaluation_code
165     #        - Call generate_evaluation_code for sub-expressions.
166     #        - Perform the functions of generate_result_code
167     #          (see below).
168     #        - If result is temporary, call generate_disposal_code
169     #          on all sub-expressions.
170     #
171     #        A default implementation of generate_evaluation_code
172     #        is provided which uses the following abstract methods:
173     #
174     #          generate_result_code
175     #            - Generate any C statements necessary to calculate
176     #              the result of this node from the results of its
177     #              sub-expressions.
178     #
179     #          calculate_result_code
180     #            - Should return a C code fragment evaluating to the
181     #              result. This is only called when the result is not
182     #              a temporary.
183     #
184     #      generate_assignment_code
185     #        Called on the LHS of an assignment.
186     #        - Call generate_evaluation_code for sub-expressions.
187     #        - Generate code to perform the assignment.
188     #        - If the assignment absorbed a reference, call
189     #          generate_post_assignment_code on the RHS,
190     #          otherwise call generate_disposal_code on it.
191     #
192     #      generate_deletion_code
193     #        Called on an argument of a del statement.
194     #        - Call generate_evaluation_code for sub-expressions.
195     #        - Generate code to perform the deletion.
196     #        - Call generate_disposal_code on all sub-expressions.
197     #
198     #
199
200     is_sequence_constructor = 0
201     is_attribute = 0
202
203     saved_subexpr_nodes = None
204     is_temp = 0
205     is_target = 0
206     is_starred = 0
207
208     constant_result = constant_value_not_set
209
210     try:
211         _get_child_attrs = operator.attrgetter('subexprs')
212     except AttributeError:
213         # Python 2.3
214         def __get_child_attrs(self):
215             return self.subexprs
216         _get_child_attrs = __get_child_attrs
217     child_attrs = property(fget=_get_child_attrs)
218
219     def not_implemented(self, method_name):
220         print_call_chain(method_name, "not implemented") ###
221         raise InternalError(
222             "%s.%s not implemented" %
223                 (self.__class__.__name__, method_name))
224
225     def is_lvalue(self):
226         return 0
227
228     def is_ephemeral(self):
229         #  An ephemeral node is one whose result is in
230         #  a Python temporary and we suspect there are no
231         #  other references to it. Certain operations are
232         #  disallowed on such values, since they are
233         #  likely to result in a dangling pointer.
234         return self.type.is_pyobject and self.is_temp
235
236     def subexpr_nodes(self):
237         #  Extract a list of subexpression nodes based
238         #  on the contents of the subexprs class attribute.
239         nodes = []
240         for name in self.subexprs:
241             item = getattr(self, name)
242             if item is not None:
243                 if type(item) is list:
244                     nodes.extend(item)
245                 else:
246                     nodes.append(item)
247         return nodes
248
249     def result(self):
250         if self.is_temp:
251             return self.temp_code
252         else:
253             return self.calculate_result_code()
254
255     def result_as(self, type = None):
256         #  Return the result code cast to the specified C type.
257         return typecast(type, self.ctype(), self.result())
258
259     def py_result(self):
260         #  Return the result code cast to PyObject *.
261         return self.result_as(py_object_type)
262
263     def ctype(self):
264         #  Return the native C type of the result (i.e. the
265         #  C type of the result_code expression).
266         return self.result_ctype or self.type
267
268     def get_constant_c_result_code(self):
269         # Return the constant value of this node as a result code
270         # string, or None if the node is not constant.  This method
271         # can be called when the constant result code is required
272         # before the code generation phase.
273         #
274         # The return value is a string that can represent a simple C
275         # value, a constant C name or a constant C expression.  If the
276         # node type depends on Python code, this must return None.
277         return None
278
279     def calculate_constant_result(self):
280         # Calculate the constant compile time result value of this
281         # expression and store it in ``self.constant_result``.  Does
282         # nothing by default, thus leaving ``self.constant_result``
283         # unknown.  If valid, the result can be an arbitrary Python
284         # value.
285         #
286         # This must only be called when it is assured that all
287         # sub-expressions have a valid constant_result value.  The
288         # ConstantFolding transform will do this.
289         pass
290
291     def has_constant_result(self):
292         return self.constant_result is not constant_value_not_set and \
293                self.constant_result is not not_a_constant
294
295     def compile_time_value(self, denv):
296         #  Return value of compile-time expression, or report error.
297         error(self.pos, "Invalid compile-time expression")
298
299     def compile_time_value_error(self, e):
300         error(self.pos, "Error in compile-time expression: %s: %s" % (
301             e.__class__.__name__, e))
302
303     # ------------- Declaration Analysis ----------------
304
305     def analyse_target_declaration(self, env):
306         error(self.pos, "Cannot assign to or delete this")
307
308     # ------------- Expression Analysis ----------------
309
310     def analyse_const_expression(self, env):
311         #  Called during the analyse_declarations phase of a
312         #  constant expression. Analyses the expression's type,
313         #  checks whether it is a legal const expression,
314         #  and determines its value.
315         self.analyse_types(env)
316         return self.check_const()
317
318     def analyse_expressions(self, env):
319         #  Convenience routine performing both the Type
320         #  Analysis and Temp Allocation phases for a whole
321         #  expression.
322         self.analyse_types(env)
323
324     def analyse_target_expression(self, env, rhs):
325         #  Convenience routine performing both the Type
326         #  Analysis and Temp Allocation phases for the LHS of
327         #  an assignment.
328         self.analyse_target_types(env)
329
330     def analyse_boolean_expression(self, env):
331         #  Analyse expression and coerce to a boolean.
332         self.analyse_types(env)
333         bool = self.coerce_to_boolean(env)
334         return bool
335
336     def analyse_temp_boolean_expression(self, env):
337         #  Analyse boolean expression and coerce result into
338         #  a temporary. This is used when a branch is to be
339         #  performed on the result and we won't have an
340         #  opportunity to ensure disposal code is executed
341         #  afterwards. By forcing the result into a temporary,
342         #  we ensure that all disposal has been done by the
343         #  time we get the result.
344         self.analyse_types(env)
345         return self.coerce_to_boolean(env).coerce_to_simple(env)
346
347     # --------------- Type Inference -----------------
348
349     def type_dependencies(self, env):
350         # Returns the list of entries whose types must be determined
351         # before the type of self can be infered.
352         if hasattr(self, 'type') and self.type is not None:
353             return ()
354         return sum([node.type_dependencies(env) for node in self.subexpr_nodes()], ())
355
356     def infer_type(self, env):
357         # Attempt to deduce the type of self.
358         # Differs from analyse_types as it avoids unnecessary
359         # analysis of subexpressions, but can assume everything
360         # in self.type_dependencies() has been resolved.
361         if hasattr(self, 'type') and self.type is not None:
362             return self.type
363         elif hasattr(self, 'entry') and self.entry is not None:
364             return self.entry.type
365         else:
366             self.not_implemented("infer_type")
367
368     # --------------- Type Analysis ------------------
369
370     def analyse_as_module(self, env):
371         # If this node can be interpreted as a reference to a
372         # cimported module, return its scope, else None.
373         return None
374
375     def analyse_as_type(self, env):
376         # If this node can be interpreted as a reference to a
377         # type, return that type, else None.
378         return None
379
380     def analyse_as_extension_type(self, env):
381         # If this node can be interpreted as a reference to an
382         # extension type, return its type, else None.
383         return None
384
385     def analyse_types(self, env):
386         self.not_implemented("analyse_types")
387
388     def analyse_target_types(self, env):
389         self.analyse_types(env)
390
391     def nogil_check(self, env):
392         # By default, any expression based on Python objects is
393         # prevented in nogil environments.  Subtypes must override
394         # this if they can work without the GIL.
395         if self.type.is_pyobject:
396             self.gil_error()
397
398     def gil_assignment_check(self, env):
399         if env.nogil and self.type.is_pyobject:
400             error(self.pos, "Assignment of Python object not allowed without gil")
401
402     def check_const(self):
403         self.not_const()
404         return False
405
406     def not_const(self):
407         error(self.pos, "Not allowed in a constant expression")
408
409     def check_const_addr(self):
410         self.addr_not_const()
411         return False
412
413     def addr_not_const(self):
414         error(self.pos, "Address is not constant")
415
416     # ----------------- Result Allocation -----------------
417
418     def result_in_temp(self):
419         #  Return true if result is in a temporary owned by
420         #  this node or one of its subexpressions. Overridden
421         #  by certain nodes which can share the result of
422         #  a subnode.
423         return self.is_temp
424
425     def target_code(self):
426         #  Return code fragment for use as LHS of a C assignment.
427         return self.calculate_result_code()
428
429     def calculate_result_code(self):
430         self.not_implemented("calculate_result_code")
431
432 #    def release_target_temp(self, env):
433 #        #  Release temporaries used by LHS of an assignment.
434 #        self.release_subexpr_temps(env)
435
436     def allocate_temp_result(self, code):
437         if self.temp_code:
438             raise RuntimeError("Temp allocated multiple times in %r: %r" % (self.__class__.__name__, self.pos))
439         type = self.type
440         if not type.is_void:
441             if type.is_pyobject:
442                 type = PyrexTypes.py_object_type
443             self.temp_code = code.funcstate.allocate_temp(
444                 type, manage_ref=self.use_managed_ref)
445         else:
446             self.temp_code = None
447
448     def release_temp_result(self, code):
449         if not self.temp_code:
450             if self.old_temp:
451                 raise RuntimeError("temp %s released multiple times in %s" % (
452                         self.old_temp, self.__class__.__name__))
453             else:
454                 raise RuntimeError("no temp, but release requested in %s" % (
455                         self.__class__.__name__))
456         code.funcstate.release_temp(self.temp_code)
457         self.old_temp = self.temp_code
458         self.temp_code = None
459
460     # ---------------- Code Generation -----------------
461
462     def make_owned_reference(self, code):
463         #  If result is a pyobject, make sure we own
464         #  a reference to it.
465         if self.type.is_pyobject and not self.result_in_temp():
466             code.put_incref(self.result(), self.ctype())
467
468     def generate_evaluation_code(self, code):
469         code.mark_pos(self.pos)
470
471         #  Generate code to evaluate this node and
472         #  its sub-expressions, and dispose of any
473         #  temporary results of its sub-expressions.
474         self.generate_subexpr_evaluation_code(code)
475
476         if self.is_temp:
477             self.allocate_temp_result(code)
478
479         self.generate_result_code(code)
480         if self.is_temp:
481             # If we are temp we do not need to wait until this node is disposed
482             # before disposing children.
483             self.generate_subexpr_disposal_code(code)
484             self.free_subexpr_temps(code)
485
486     def generate_subexpr_evaluation_code(self, code):
487         for node in self.subexpr_nodes():
488             node.generate_evaluation_code(code)
489
490     def generate_result_code(self, code):
491         self.not_implemented("generate_result_code")
492
493     def generate_disposal_code(self, code):
494         if self.is_temp:
495             if self.type.is_pyobject:
496                 code.put_decref_clear(self.result(), self.ctype())
497         else:
498             # Already done if self.is_temp
499             self.generate_subexpr_disposal_code(code)
500
501     def generate_subexpr_disposal_code(self, code):
502         #  Generate code to dispose of temporary results
503         #  of all sub-expressions.
504         for node in self.subexpr_nodes():
505             node.generate_disposal_code(code)
506
507     def generate_post_assignment_code(self, code):
508         if self.is_temp:
509             if self.type.is_pyobject:
510                 code.putln("%s = 0;" % self.result())
511         else:
512             self.generate_subexpr_disposal_code(code)
513
514     def generate_assignment_code(self, rhs, code):
515         #  Stub method for nodes which are not legal as
516         #  the LHS of an assignment. An error will have
517         #  been reported earlier.
518         pass
519
520     def generate_deletion_code(self, code):
521         #  Stub method for nodes that are not legal as
522         #  the argument of a del statement. An error
523         #  will have been reported earlier.
524         pass
525
526     def free_temps(self, code):
527         if self.is_temp:
528             if not self.type.is_void:
529                 self.release_temp_result(code)
530         else:
531             self.free_subexpr_temps(code)
532
533     def free_subexpr_temps(self, code):
534         for sub in self.subexpr_nodes():
535             sub.free_temps(code)
536
537     def generate_function_definitions(self, env, code):
538         pass
539
540     # ---------------- Annotation ---------------------
541
542     def annotate(self, code):
543         for node in self.subexpr_nodes():
544             node.annotate(code)
545
546     # ----------------- Coercion ----------------------
547
548     def coerce_to(self, dst_type, env):
549         #   Coerce the result so that it can be assigned to
550         #   something of type dst_type. If processing is necessary,
551         #   wraps this node in a coercion node and returns that.
552         #   Otherwise, returns this node unchanged.
553         #
554         #   This method is called during the analyse_expressions
555         #   phase of the src_node's processing.
556         #
557         #   Note that subclasses that override this (especially
558         #   ConstNodes) must not (re-)set their own .type attribute
559         #   here.  Since expression nodes may turn up in different
560         #   places in the tree (e.g. inside of CloneNodes in cascaded
561         #   assignments), this method must return a new node instance
562         #   if it changes the type.
563         #
564         src = self
565         src_type = self.type
566         src_is_py_type = src_type.is_pyobject
567         dst_is_py_type = dst_type.is_pyobject
568
569         if self.check_for_coercion_error(dst_type):
570             return self
571
572         if dst_type.is_reference:
573             dst_type = dst_type.ref_base_type
574
575         if dst_type.is_pyobject:
576             if not src.type.is_pyobject:
577                 if dst_type is bytes_type and src.type.is_int:
578                     src = CoerceIntToBytesNode(src, env)
579                 else:
580                     src = CoerceToPyTypeNode(src, env)
581             if not src.type.subtype_of(dst_type):
582                 if not isinstance(src, NoneNode):
583                     src = PyTypeTestNode(src, dst_type, env)
584         elif src.type.is_pyobject:
585             src = CoerceFromPyTypeNode(dst_type, src, env)
586         elif (dst_type.is_complex
587               and src_type != dst_type
588               and dst_type.assignable_from(src_type)):
589             src = CoerceToComplexNode(src, dst_type, env)
590         else: # neither src nor dst are py types
591             # Added the string comparison, since for c types that
592             # is enough, but Cython gets confused when the types are
593             # in different pxi files.
594             if not (str(src.type) == str(dst_type) or dst_type.assignable_from(src_type)):
595                 self.fail_assignment(dst_type)
596         return src
597
598     def fail_assignment(self, dst_type):
599         error(self.pos, "Cannot assign type '%s' to '%s'" % (self.type, dst_type))
600
601     def check_for_coercion_error(self, dst_type, fail=False, default=None):
602         if fail and not default:
603             default = "Cannot assign type '%(FROM)s' to '%(TO)s'"
604         message = find_coercion_error((self.type, dst_type), default)
605         if message is not None:
606             error(self.pos, message % {'FROM': self.type, 'TO': dst_type})
607             return True
608         if fail:
609             self.fail_assignment(dst_type)
610             return True
611         return False
612
613     def coerce_to_pyobject(self, env):
614         return self.coerce_to(PyrexTypes.py_object_type, env)
615
616     def coerce_to_boolean(self, env):
617         #  Coerce result to something acceptable as
618         #  a boolean value.
619
620         # if it's constant, calculate the result now
621         if self.has_constant_result():
622             bool_value = bool(self.constant_result)
623             return BoolNode(self.pos, value=bool_value,
624                             constant_result=bool_value)
625
626         type = self.type
627         if type.is_pyobject or type.is_ptr or type.is_float:
628             return CoerceToBooleanNode(self, env)
629         else:
630             if not (type.is_int or type.is_enum or type.is_error):
631                 error(self.pos,
632                     "Type '%s' not acceptable as a boolean" % type)
633             return self
634
635     def coerce_to_integer(self, env):
636         # If not already some C integer type, coerce to longint.
637         if self.type.is_int:
638             return self
639         else:
640             return self.coerce_to(PyrexTypes.c_long_type, env)
641
642     def coerce_to_temp(self, env):
643         #  Ensure that the result is in a temporary.
644         if self.result_in_temp():
645             return self
646         else:
647             return CoerceToTempNode(self, env)
648
649     def coerce_to_simple(self, env):
650         #  Ensure that the result is simple (see is_simple).
651         if self.is_simple():
652             return self
653         else:
654             return self.coerce_to_temp(env)
655
656     def is_simple(self):
657         #  A node is simple if its result is something that can
658         #  be referred to without performing any operations, e.g.
659         #  a constant, local var, C global var, struct member
660         #  reference, or temporary.
661         return self.result_in_temp()
662
663     def may_be_none(self):
664         if not self.type.is_pyobject:
665             return False
666         if self.constant_result not in (not_a_constant, constant_value_not_set):
667             return self.constant_result is not None
668         return True
669
670     def as_cython_attribute(self):
671         return None
672
673     def as_none_safe_node(self, message, error="PyExc_TypeError"):
674         # Wraps the node in a NoneCheckNode if it is not known to be
675         # not-None (e.g. because it is a Python literal).
676         if self.may_be_none():
677             return NoneCheckNode(self, error, message)
678         else:
679             return self
680
681
682 class AtomicExprNode(ExprNode):
683     #  Abstract base class for expression nodes which have
684     #  no sub-expressions.
685
686     subexprs = []
687
688     # Override to optimize -- we know we have no children
689     def generate_subexpr_evaluation_code(self, code):
690         pass
691     def generate_subexpr_disposal_code(self, code):
692         pass
693
694 class PyConstNode(AtomicExprNode):
695     #  Abstract base class for constant Python values.
696
697     is_literal = 1
698     type = py_object_type
699
700     def is_simple(self):
701         return 1
702
703     def may_be_none(self):
704         return False
705
706     def analyse_types(self, env):
707         pass
708
709     def calculate_result_code(self):
710         return self.value
711
712     def generate_result_code(self, code):
713         pass
714
715
716 class NoneNode(PyConstNode):
717     #  The constant value None
718
719     value = "Py_None"
720
721     constant_result = None
722
723     nogil_check = None
724
725     def compile_time_value(self, denv):
726         return None
727
728     def may_be_none(self):
729         return True
730
731
732 class EllipsisNode(PyConstNode):
733     #  '...' in a subscript list.
734
735     value = "Py_Ellipsis"
736
737     constant_result = Ellipsis
738
739     def compile_time_value(self, denv):
740         return Ellipsis
741
742
743 class ConstNode(AtomicExprNode):
744     # Abstract base type for literal constant nodes.
745     #
746     # value     string      C code fragment
747
748     is_literal = 1
749     nogil_check = None
750
751     def is_simple(self):
752         return 1
753
754     def may_be_none(self):
755         return False
756
757     def analyse_types(self, env):
758         pass # Types are held in class variables
759
760     def check_const(self):
761         return True
762
763     def get_constant_c_result_code(self):
764         return self.calculate_result_code()
765
766     def calculate_result_code(self):
767         return str(self.value)
768
769     def generate_result_code(self, code):
770         pass
771
772
773 class BoolNode(ConstNode):
774     type = PyrexTypes.c_bint_type
775     #  The constant value True or False
776
777     def calculate_constant_result(self):
778         self.constant_result = self.value
779
780     def compile_time_value(self, denv):
781         return self.value
782
783     def calculate_result_code(self):
784         return str(int(self.value))
785
786
787 class NullNode(ConstNode):
788     type = PyrexTypes.c_null_ptr_type
789     value = "NULL"
790     constant_result = 0
791
792     def get_constant_c_result_code(self):
793         return self.value
794
795
796 class CharNode(ConstNode):
797     type = PyrexTypes.c_char_type
798
799     def calculate_constant_result(self):
800         self.constant_result = ord(self.value)
801
802     def compile_time_value(self, denv):
803         return ord(self.value)
804
805     def calculate_result_code(self):
806         return "'%s'" % StringEncoding.escape_char(self.value)
807
808
809 class IntNode(ConstNode):
810
811     # unsigned     "" or "U"
812     # longness     "" or "L" or "LL"
813     # is_c_literal   True/False/None   creator considers this a C integer literal
814
815     unsigned = ""
816     longness = ""
817     is_c_literal = None # unknown
818
819     def __init__(self, pos, **kwds):
820         ExprNode.__init__(self, pos, **kwds)
821         if 'type' not in kwds:
822             self.type = self.find_suitable_type_for_value()
823
824     def find_suitable_type_for_value(self):
825         if self.constant_result is constant_value_not_set:
826             try:
827                 self.calculate_constant_result()
828             except ValueError:
829                 pass
830         # we ignore 'is_c_literal = True' and instead map signed 32bit
831         # integers as C long values
832         if self.is_c_literal or \
833                self.constant_result in (constant_value_not_set, not_a_constant) or \
834                self.unsigned or self.longness == 'LL':
835             # clearly a C literal
836             rank = (self.longness == 'LL') and 2 or 1
837             suitable_type = PyrexTypes.modifiers_and_name_to_type[not self.unsigned, rank, "int"]
838             if self.type:
839                 suitable_type = PyrexTypes.widest_numeric_type(suitable_type, self.type)
840         else:
841             # C literal or Python literal - split at 32bit boundary
842             if self.constant_result >= -2**31 and self.constant_result < 2**31:
843                 if self.type and self.type.is_int:
844                     suitable_type = self.type
845                 else:
846                     suitable_type = PyrexTypes.c_long_type
847             else:
848                 suitable_type = PyrexTypes.py_object_type
849         return suitable_type
850
851     def coerce_to(self, dst_type, env):
852         if self.type is dst_type:
853             return self
854         elif dst_type.is_float:
855             if self.constant_result is not not_a_constant:
856                 float_value = float(self.constant_result)
857                 return FloatNode(self.pos, value=repr(float_value), type=dst_type,
858                                  constant_result=float_value)
859             else:
860                 return FloatNode(self.pos, value=self.value, type=dst_type,
861                                  constant_result=not_a_constant)
862         if dst_type.is_numeric and not dst_type.is_complex:
863             node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
864                            type = dst_type, is_c_literal = True,
865                            unsigned=self.unsigned, longness=self.longness)
866             return node
867         elif dst_type.is_pyobject:
868             node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
869                            type = PyrexTypes.py_object_type, is_c_literal = False,
870                            unsigned=self.unsigned, longness=self.longness)
871         else:
872             # FIXME: not setting the type here to keep it working with
873             # complex numbers. Should they be special cased?
874             node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
875                            unsigned=self.unsigned, longness=self.longness)
876         # We still need to perform normal coerce_to processing on the
877         # result, because we might be coercing to an extension type,
878         # in which case a type test node will be needed.
879         return ConstNode.coerce_to(node, dst_type, env)
880
881     def coerce_to_boolean(self, env):
882         return IntNode(
883             self.pos, value=self.value,
884             type = PyrexTypes.c_bint_type,
885             unsigned=self.unsigned, longness=self.longness)
886
887     def generate_evaluation_code(self, code):
888         if self.type.is_pyobject:
889             # pre-allocate a Python version of the number
890             plain_integer_string = self.value_as_c_integer_string(plain_digits=True)
891             self.result_code = code.get_py_num(plain_integer_string, self.longness)
892         else:
893             self.result_code = self.get_constant_c_result_code()
894
895     def get_constant_c_result_code(self):
896         return self.value_as_c_integer_string() + self.unsigned + self.longness
897
898     def value_as_c_integer_string(self, plain_digits=False):
899         value = self.value
900         if isinstance(value, basestring) and len(value) > 2:
901             # must convert C-incompatible Py3 oct/bin notations
902             if value[1] in 'oO':
903                 if plain_digits:
904                     value = int(value[2:], 8)
905                 else:
906                     value = value[0] + value[2:] # '0o123' => '0123'
907             elif value[1] in 'bB':
908                 value = int(value[2:], 2)
909             elif plain_digits and value[1] in 'xX':
910                 value = int(value[2:], 16)
911         return str(value)
912
913     def calculate_result_code(self):
914         return self.result_code
915
916     def calculate_constant_result(self):
917         self.constant_result = Utils.str_to_number(self.value)
918
919     def compile_time_value(self, denv):
920         return Utils.str_to_number(self.value)
921
922
923 class FloatNode(ConstNode):
924     type = PyrexTypes.c_double_type
925
926     def calculate_constant_result(self):
927         self.constant_result = float(self.value)
928
929     def compile_time_value(self, denv):
930         return float(self.value)
931
932     def calculate_result_code(self):
933         strval = self.value
934         assert isinstance(strval, (str, unicode))
935         cmpval = repr(float(strval))
936         if cmpval == 'nan':
937             return "(Py_HUGE_VAL * 0)"
938         elif cmpval == 'inf':
939             return "Py_HUGE_VAL"
940         elif cmpval == '-inf':
941             return "(-Py_HUGE_VAL)"
942         else:
943             return strval
944
945
946 class BytesNode(ConstNode):
947     # A char* or bytes literal
948     #
949     # value      BytesLiteral
950
951     # start off as Python 'bytes' to support len() in O(1)
952     type = bytes_type
953
954     def compile_time_value(self, denv):
955         return self.value
956
957     def analyse_as_type(self, env):
958         type = PyrexTypes.parse_basic_type(self.value)
959         if type is not None:
960             return type
961         from TreeFragment import TreeFragment
962         pos = (self.pos[0], self.pos[1], self.pos[2]-7)
963         declaration = TreeFragment(u"sizeof(%s)" % self.value, name=pos[0].filename, initial_pos=pos)
964         sizeof_node = declaration.root.stats[0].expr
965         sizeof_node.analyse_types(env)
966         if isinstance(sizeof_node, SizeofTypeNode):
967             return sizeof_node.arg_type
968
969     def can_coerce_to_char_literal(self):
970         return len(self.value) == 1
971
972     def coerce_to_boolean(self, env):
973         # This is special because testing a C char* for truth directly
974         # would yield the wrong result.
975         return BoolNode(self.pos, value=bool(self.value))
976
977     def coerce_to(self, dst_type, env):
978         if self.type == dst_type:
979             return self
980         if dst_type.is_int:
981             if not self.can_coerce_to_char_literal():
982                 error(self.pos, "Only single-character string literals can be coerced into ints.")
983                 return self
984             if dst_type is PyrexTypes.c_py_unicode_type:
985                 error(self.pos, "Bytes literals cannot coerce to Py_UNICODE, use a unicode literal instead.")
986                 return self
987             return CharNode(self.pos, value=self.value)
988
989         node = BytesNode(self.pos, value=self.value)
990         if dst_type.is_pyobject:
991             if dst_type in (py_object_type, Builtin.bytes_type):
992                 node.type = Builtin.bytes_type
993             else:
994                 self.check_for_coercion_error(dst_type, fail=True)
995                 return node
996         elif dst_type == PyrexTypes.c_char_ptr_type:
997             node.type = dst_type
998             return node
999         elif dst_type == PyrexTypes.c_uchar_ptr_type:
1000             node.type = PyrexTypes.c_char_ptr_type
1001             return CastNode(node, PyrexTypes.c_uchar_ptr_type)
1002         elif dst_type.assignable_from(PyrexTypes.c_char_ptr_type):
1003             node.type = dst_type
1004             return node
1005
1006         # We still need to perform normal coerce_to processing on the
1007         # result, because we might be coercing to an extension type,
1008         # in which case a type test node will be needed.
1009         return ConstNode.coerce_to(node, dst_type, env)
1010
1011     def generate_evaluation_code(self, code):
1012         if self.type.is_pyobject:
1013             self.result_code = code.get_py_string_const(self.value)
1014         else:
1015             self.result_code = code.get_string_const(self.value)
1016
1017     def get_constant_c_result_code(self):
1018         return None # FIXME
1019
1020     def calculate_result_code(self):
1021         return self.result_code
1022
1023
1024 class UnicodeNode(PyConstNode):
1025     # A Python unicode object
1026     #
1027     # value        EncodedString
1028     # bytes_value  BytesLiteral    the literal parsed as bytes string ('-3' unicode literals only)
1029
1030     bytes_value = None
1031     type = unicode_type
1032
1033     def coerce_to(self, dst_type, env):
1034         if dst_type is self.type:
1035             pass
1036         elif dst_type is PyrexTypes.c_py_unicode_type:
1037             if not self.can_coerce_to_char_literal():
1038                 error(self.pos, "Only single-character Unicode string literals can be coerced into Py_UNICODE.")
1039                 return self
1040             int_value = ord(self.value)
1041             return IntNode(self.pos, value=int_value, constant_result=int_value)
1042         elif not dst_type.is_pyobject:
1043             if dst_type.is_string and self.bytes_value is not None:
1044                 # special case: '-3' enforced unicode literal used in a C char* context
1045                 return BytesNode(self.pos, value=self.bytes_value).coerce_to(dst_type, env)
1046             error(self.pos, "Unicode literals do not support coercion to C types other than Py_UNICODE.")
1047         elif dst_type is not py_object_type:
1048             if not self.check_for_coercion_error(dst_type):
1049                 self.fail_assignment(dst_type)
1050         return self
1051
1052     def can_coerce_to_char_literal(self):
1053         return len(self.value) == 1
1054
1055     def contains_surrogates(self):
1056         # Check if the unicode string contains surrogate code points
1057         # on a CPython platform with wide (UCS-4) or narrow (UTF-16)
1058         # Unicode, i.e. characters that would be spelled as two
1059         # separate code units on a narrow platform.
1060         for c in map(ord, self.value):
1061             if c > 65535: # can only happen on wide platforms
1062                 return True
1063             # We only look for the first code unit (D800-DBFF) of a
1064             # surrogate pair - if we find one, the other one
1065             # (DC00-DFFF) is likely there, too.  If we don't find it,
1066             # any second code unit cannot make for a surrogate pair by
1067             # itself.
1068             if c >= 0xD800 and c <= 0xDBFF:
1069                 return True
1070         return False
1071
1072     def generate_evaluation_code(self, code):
1073         self.result_code = code.get_py_string_const(self.value)
1074
1075     def calculate_result_code(self):
1076         return self.result_code
1077
1078     def compile_time_value(self, env):
1079         return self.value
1080
1081
1082 class StringNode(PyConstNode):
1083     # A Python str object, i.e. a byte string in Python 2.x and a
1084     # unicode string in Python 3.x
1085     #
1086     # value          BytesLiteral (or EncodedString with ASCII content)
1087     # unicode_value  EncodedString or None
1088     # is_identifier  boolean
1089
1090     type = str_type
1091     is_identifier = None
1092     unicode_value = None
1093
1094     def coerce_to(self, dst_type, env):
1095         if dst_type is not py_object_type and not str_type.subtype_of(dst_type):
1096 #            if dst_type is Builtin.bytes_type:
1097 #                # special case: bytes = 'str literal'
1098 #                return BytesNode(self.pos, value=self.value)
1099             if not dst_type.is_pyobject:
1100                 return BytesNode(self.pos, value=self.value).coerce_to(dst_type, env)
1101             self.check_for_coercion_error(dst_type, fail=True)
1102
1103         # this will be a unicode string in Py3, so make sure we can decode it
1104         if self.value.encoding and isinstance(self.value, StringEncoding.BytesLiteral):
1105             try:
1106                 self.value.decode(self.value.encoding)
1107             except UnicodeDecodeError:
1108                 error(self.pos, ("Decoding unprefixed string literal from '%s' failed. Consider using"
1109                                  "a byte string or unicode string explicitly, "
1110                                  "or adjust the source code encoding.") % self.value.encoding)
1111
1112         return self
1113
1114     def can_coerce_to_char_literal(self):
1115         return not self.is_identifier and len(self.value) == 1
1116
1117     def generate_evaluation_code(self, code):
1118         self.result_code = code.get_py_string_const(
1119             self.value, identifier=self.is_identifier, is_str=True)
1120
1121     def get_constant_c_result_code(self):
1122         return None
1123
1124     def calculate_result_code(self):
1125         return self.result_code
1126
1127     def compile_time_value(self, env):
1128         return self.value
1129
1130
1131 class IdentifierStringNode(StringNode):
1132     # A special str value that represents an identifier (bytes in Py2,
1133     # unicode in Py3).
1134     is_identifier = True
1135
1136
1137 class LongNode(AtomicExprNode):
1138     #  Python long integer literal
1139     #
1140     #  value   string
1141
1142     type = py_object_type
1143
1144     def calculate_constant_result(self):
1145         self.constant_result = Utils.str_to_number(self.value)
1146
1147     def compile_time_value(self, denv):
1148         return Utils.str_to_number(self.value)
1149
1150     def analyse_types(self, env):
1151         self.is_temp = 1
1152
1153     def may_be_none(self):
1154         return False
1155
1156     gil_message = "Constructing Python long int"
1157
1158     def generate_result_code(self, code):
1159         code.putln(
1160             '%s = PyLong_FromString((char *)"%s", 0, 0); %s' % (
1161                 self.result(),
1162                 self.value,
1163                 code.error_goto_if_null(self.result(), self.pos)))
1164         code.put_gotref(self.py_result())
1165
1166
1167 class ImagNode(AtomicExprNode):
1168     #  Imaginary number literal
1169     #
1170     #  value   float    imaginary part
1171
1172     type = PyrexTypes.c_double_complex_type
1173
1174     def calculate_constant_result(self):
1175         self.constant_result = complex(0.0, self.value)
1176
1177     def compile_time_value(self, denv):
1178         return complex(0.0, self.value)
1179
1180     def analyse_types(self, env):
1181         self.type.create_declaration_utility_code(env)
1182
1183     def may_be_none(self):
1184         return False
1185
1186     def coerce_to(self, dst_type, env):
1187         if self.type is dst_type:
1188             return self
1189         node = ImagNode(self.pos, value=self.value)
1190         if dst_type.is_pyobject:
1191             node.is_temp = 1
1192             node.type = PyrexTypes.py_object_type
1193         # We still need to perform normal coerce_to processing on the
1194         # result, because we might be coercing to an extension type,
1195         # in which case a type test node will be needed.
1196         return AtomicExprNode.coerce_to(node, dst_type, env)
1197
1198     gil_message = "Constructing complex number"
1199
1200     def calculate_result_code(self):
1201         if self.type.is_pyobject:
1202             return self.result()
1203         else:
1204             return "%s(0, %r)" % (self.type.from_parts, float(self.value))
1205
1206     def generate_result_code(self, code):
1207         if self.type.is_pyobject:
1208             code.putln(
1209                 "%s = PyComplex_FromDoubles(0.0, %r); %s" % (
1210                     self.result(),
1211                     float(self.value),
1212                     code.error_goto_if_null(self.result(), self.pos)))
1213             code.put_gotref(self.py_result())
1214
1215
1216 class NewExprNode(AtomicExprNode):
1217
1218     # C++ new statement
1219     #
1220     # cppclass              node                 c++ class to create
1221
1222     type = None
1223
1224     def infer_type(self, env):
1225         type = self.cppclass.analyse_as_type(env)
1226         if type is None or not type.is_cpp_class:
1227             error(self.pos, "new operator can only be applied to a C++ class")
1228             self.type = error_type
1229             return
1230         self.cpp_check(env)
1231         constructor = type.scope.lookup(u'<init>')
1232         if constructor is None:
1233             return_type = PyrexTypes.CFuncType(type, [])
1234             return_type = PyrexTypes.CPtrType(return_type)
1235             type.scope.declare_cfunction(u'<init>', return_type, self.pos)
1236             constructor = type.scope.lookup(u'<init>')
1237         self.class_type = type
1238         self.entry = constructor
1239         self.type = constructor.type
1240         return self.type
1241
1242     def analyse_types(self, env):
1243         if self.type is None:
1244             self.infer_type(env)
1245
1246     def may_be_none(self):
1247         return False
1248
1249     def generate_result_code(self, code):
1250         pass
1251
1252     def calculate_result_code(self):
1253         return "new " + self.class_type.declaration_code("")
1254
1255
1256 class NameNode(AtomicExprNode):
1257     #  Reference to a local or global variable name.
1258     #
1259     #  name            string    Python name of the variable
1260     #  entry           Entry     Symbol table entry
1261     #  type_entry      Entry     For extension type names, the original type entry
1262
1263     is_name = True
1264     is_cython_module = False
1265     cython_attribute = None
1266     lhs_of_first_assignment = False
1267     is_used_as_rvalue = 0
1268     entry = None
1269     type_entry = None
1270
1271     def create_analysed_rvalue(pos, env, entry):
1272         node = NameNode(pos)
1273         node.analyse_types(env, entry=entry)
1274         return node
1275
1276     def as_cython_attribute(self):
1277         return self.cython_attribute
1278
1279     create_analysed_rvalue = staticmethod(create_analysed_rvalue)
1280
1281     def type_dependencies(self, env):
1282         if self.entry is None:
1283             self.entry = env.lookup(self.name)
1284         if self.entry is not None and self.entry.type.is_unspecified:
1285             return (self.entry,)
1286         else:
1287             return ()
1288
1289     def infer_type(self, env):
1290         if self.entry is None:
1291             self.entry = env.lookup(self.name)
1292         if self.entry is None:
1293             return py_object_type
1294         elif (self.entry.type.is_extension_type or self.entry.type.is_builtin_type) and \
1295                 self.name == self.entry.type.name:
1296             # Unfortunately the type attribute of type objects
1297             # is used for the pointer to the type they represent.
1298             return type_type
1299         elif self.entry.type.is_cfunction:
1300             # special case: referring to a C function must return its pointer
1301             return PyrexTypes.CPtrType(self.entry.type)
1302         else:
1303             return self.entry.type
1304
1305     def compile_time_value(self, denv):
1306         try:
1307             return denv.lookup(self.name)
1308         except KeyError:
1309             error(self.pos, "Compile-time name '%s' not defined" % self.name)
1310
1311     def get_constant_c_result_code(self):
1312         if not self.entry or self.entry.type.is_pyobject:
1313             return None
1314         return self.entry.cname
1315
1316     def coerce_to(self, dst_type, env):
1317         #  If coercing to a generic pyobject and this is a builtin
1318         #  C function with a Python equivalent, manufacture a NameNode
1319         #  referring to the Python builtin.
1320         #print "NameNode.coerce_to:", self.name, dst_type ###
1321         if dst_type is py_object_type:
1322             entry = self.entry
1323             if entry and entry.is_cfunction:
1324                 var_entry = entry.as_variable
1325                 if var_entry:
1326                     if var_entry.is_builtin and Options.cache_builtins:
1327                         var_entry = env.declare_builtin(var_entry.name, self.pos)
1328                     node = NameNode(self.pos, name = self.name)
1329                     node.entry = var_entry
1330                     node.analyse_rvalue_entry(env)
1331                     return node
1332         return super(NameNode, self).coerce_to(dst_type, env)
1333
1334     def analyse_as_module(self, env):
1335         # Try to interpret this as a reference to a cimported module.
1336         # Returns the module scope, or None.
1337         entry = self.entry
1338         if not entry:
1339             entry = env.lookup(self.name)
1340         if entry and entry.as_module:
1341             return entry.as_module
1342         return None
1343
1344     def analyse_as_type(self, env):
1345         if self.cython_attribute:
1346             type = PyrexTypes.parse_basic_type(self.cython_attribute)
1347         else:
1348             type = PyrexTypes.parse_basic_type(self.name)
1349         if type:
1350             return type
1351         entry = self.entry
1352         if not entry:
1353             entry = env.lookup(self.name)
1354         if entry and entry.is_type:
1355             return entry.type
1356         else:
1357             return None
1358
1359     def analyse_as_extension_type(self, env):
1360         # Try to interpret this as a reference to an extension type.
1361         # Returns the extension type, or None.
1362         entry = self.entry
1363         if not entry:
1364             entry = env.lookup(self.name)
1365         if entry and entry.is_type and entry.type.is_extension_type:
1366             return entry.type
1367         else:
1368             return None
1369
1370     def analyse_target_declaration(self, env):
1371         if not self.entry:
1372             self.entry = env.lookup_here(self.name)
1373         if not self.entry:
1374             if env.directives['warn.undeclared']:
1375                 warning(self.pos, "implicit declaration of '%s'" % self.name, 1)
1376             if env.directives['infer_types'] != False:
1377                 type = unspecified_type
1378             else:
1379                 type = py_object_type
1380             self.entry = env.declare_var(self.name, type, self.pos)
1381         env.control_flow.set_state(self.pos, (self.name, 'initialized'), True)
1382         env.control_flow.set_state(self.pos, (self.name, 'source'), 'assignment')
1383         if self.entry.is_declared_generic:
1384             self.result_ctype = py_object_type
1385
1386     def analyse_types(self, env):
1387         if self.entry is None:
1388             self.entry = env.lookup(self.name)
1389         if not self.entry:
1390             self.entry = env.declare_builtin(self.name, self.pos)
1391         if not self.entry:
1392             self.type = PyrexTypes.error_type
1393             return
1394         entry = self.entry
1395         if entry:
1396             entry.used = 1
1397             if entry.type.is_buffer:
1398                 import Buffer
1399                 Buffer.used_buffer_aux_vars(entry)
1400             if entry.utility_code:
1401                 env.use_utility_code(entry.utility_code)
1402         self.analyse_rvalue_entry(env)
1403
1404     def analyse_target_types(self, env):
1405         self.analyse_entry(env)
1406         if not self.is_lvalue():
1407             error(self.pos, "Assignment to non-lvalue '%s'"
1408                 % self.name)
1409             self.type = PyrexTypes.error_type
1410         self.entry.used = 1
1411         if self.entry.type.is_buffer:
1412             import Buffer
1413             Buffer.used_buffer_aux_vars(self.entry)
1414
1415     def analyse_rvalue_entry(self, env):
1416         #print "NameNode.analyse_rvalue_entry:", self.name ###
1417         #print "Entry:", self.entry.__dict__ ###
1418         self.analyse_entry(env)
1419         entry = self.entry
1420         if entry.is_declared_generic:
1421             self.result_ctype = py_object_type
1422         if entry.is_pyglobal or entry.is_builtin:
1423             if Options.cache_builtins and entry.is_builtin:
1424                 self.is_temp = 0
1425             else:
1426                 self.is_temp = 1
1427                 env.use_utility_code(get_name_interned_utility_code)
1428             self.is_used_as_rvalue = 1
1429
1430     def nogil_check(self, env):
1431         if self.is_used_as_rvalue:
1432             entry = self.entry
1433             if entry.is_builtin:
1434                 if not Options.cache_builtins: # cached builtins are ok
1435                     self.gil_error()
1436             elif entry.is_pyglobal:
1437                 self.gil_error()
1438
1439     gil_message = "Accessing Python global or builtin"
1440
1441     def analyse_entry(self, env):
1442         #print "NameNode.analyse_entry:", self.name ###
1443         self.check_identifier_kind()
1444         entry = self.entry
1445         type = entry.type
1446         self.type = type
1447
1448     def check_identifier_kind(self):
1449         # Check that this is an appropriate kind of name for use in an
1450         # expression.  Also finds the variable entry associated with
1451         # an extension type.
1452         entry = self.entry
1453         if entry.is_type and entry.type.is_extension_type:
1454             self.type_entry = entry
1455         if not (entry.is_const or entry.is_variable
1456             or entry.is_builtin or entry.is_cfunction
1457             or entry.is_cpp_class):
1458                 if self.entry.as_variable:
1459                     self.entry = self.entry.as_variable
1460                 else:
1461                     error(self.pos,
1462                           "'%s' is not a constant, variable or function identifier" % self.name)
1463
1464     def is_simple(self):
1465         #  If it's not a C variable, it'll be in a temp.
1466         return 1
1467
1468     def calculate_target_results(self, env):
1469         pass
1470
1471     def check_const(self):
1472         entry = self.entry
1473         if entry is not None and not (entry.is_const or entry.is_cfunction or entry.is_builtin):
1474             self.not_const()
1475             return False
1476         return True
1477
1478     def check_const_addr(self):
1479         entry = self.entry
1480         if not (entry.is_cglobal or entry.is_cfunction or entry.is_builtin):
1481             self.addr_not_const()
1482             return False
1483         return True
1484
1485     def is_lvalue(self):
1486         return self.entry.is_variable and \
1487             not self.entry.type.is_array and \
1488             not self.entry.is_readonly
1489
1490     def is_ephemeral(self):
1491         #  Name nodes are never ephemeral, even if the
1492         #  result is in a temporary.
1493         return 0
1494
1495     def calculate_result_code(self):
1496         entry = self.entry
1497         if not entry:
1498             return "<error>" # There was an error earlier
1499         return entry.cname
1500
1501     def generate_result_code(self, code):
1502         assert hasattr(self, 'entry')
1503         entry = self.entry
1504         if entry is None:
1505             return # There was an error earlier
1506         if entry.is_builtin and Options.cache_builtins:
1507             return # Lookup already cached
1508         elif entry.is_pyclass_attr:
1509             assert entry.type.is_pyobject, "Python global or builtin not a Python object"
1510             interned_cname = code.intern_identifier(self.entry.name)
1511             if entry.is_builtin:
1512                 namespace = Naming.builtins_cname
1513             else: # entry.is_pyglobal
1514                 namespace = entry.scope.namespace_cname
1515             code.putln(
1516                 '%s = PyObject_GetItem(%s, %s); %s' % (
1517                 self.result(),
1518                 namespace,
1519                 interned_cname,
1520                 code.error_goto_if_null(self.result(), self.pos)))
1521             code.put_gotref(self.py_result())
1522
1523         elif entry.is_pyglobal or entry.is_builtin:
1524             assert entry.type.is_pyobject, "Python global or builtin not a Python object"
1525             interned_cname = code.intern_identifier(self.entry.name)
1526             if entry.is_builtin:
1527                 namespace = Naming.builtins_cname
1528             else: # entry.is_pyglobal
1529                 namespace = entry.scope.namespace_cname
1530             code.globalstate.use_utility_code(get_name_interned_utility_code)
1531             code.putln(
1532                 '%s = __Pyx_GetName(%s, %s); %s' % (
1533                 self.result(),
1534                 namespace,
1535                 interned_cname,
1536                 code.error_goto_if_null(self.result(), self.pos)))
1537             code.put_gotref(self.py_result())
1538
1539         elif entry.is_local and False:
1540             # control flow not good enough yet
1541             assigned = entry.scope.control_flow.get_state((entry.name, 'initialized'), self.pos)
1542             if assigned is False:
1543                 error(self.pos, "local variable '%s' referenced before assignment" % entry.name)
1544             elif not Options.init_local_none and assigned is None:
1545                 code.putln('if (%s == 0) { PyErr_SetString(PyExc_UnboundLocalError, "%s"); %s }' %
1546                            (entry.cname, entry.name, code.error_goto(self.pos)))
1547                 entry.scope.control_flow.set_state(self.pos, (entry.name, 'initialized'), True)
1548
1549     def generate_assignment_code(self, rhs, code):
1550         #print "NameNode.generate_assignment_code:", self.name ###
1551         entry = self.entry
1552         if entry is None:
1553             return # There was an error earlier
1554
1555         if (self.entry.type.is_ptr and isinstance(rhs, ListNode)
1556             and not self.lhs_of_first_assignment):
1557             error(self.pos, "Literal list must be assigned to pointer at time of declaration")
1558
1559         # is_pyglobal seems to be True for module level-globals only.
1560         # We use this to access class->tp_dict if necessary.
1561         if entry.is_pyglobal:
1562             assert entry.type.is_pyobject, "Python global or builtin not a Python object"
1563             interned_cname = code.intern_identifier(self.entry.name)
1564             namespace = self.entry.scope.namespace_cname
1565             if entry.is_member:
1566                 # if the entry is a member we have to cheat: SetAttr does not work
1567                 # on types, so we create a descriptor which is then added to tp_dict
1568                 code.put_error_if_neg(self.pos,
1569                     'PyDict_SetItem(%s->tp_dict, %s, %s)' % (
1570                         namespace,
1571                         interned_cname,
1572                         rhs.py_result()))
1573                 rhs.generate_disposal_code(code)
1574                 rhs.free_temps(code)
1575                 # in Py2.6+, we need to invalidate the method cache
1576                 code.putln("PyType_Modified(%s);" %
1577                             entry.scope.parent_type.typeptr_cname)
1578             elif entry.is_pyclass_attr:
1579                 code.put_error_if_neg(self.pos,
1580                     'PyObject_SetItem(%s, %s, %s)' % (
1581                         namespace,
1582                         interned_cname,
1583                         rhs.py_result()))
1584                 rhs.generate_disposal_code(code)
1585                 rhs.free_temps(code)
1586             else:
1587                 code.put_error_if_neg(self.pos,
1588                     'PyObject_SetAttr(%s, %s, %s)' % (
1589                         namespace,
1590                         interned_cname,
1591                         rhs.py_result()))
1592                 if debug_disposal_code:
1593                     print("NameNode.generate_assignment_code:")
1594                     print("...generating disposal code for %s" % rhs)
1595                 rhs.generate_disposal_code(code)
1596                 rhs.free_temps(code)
1597         else:
1598             if self.type.is_buffer:
1599                 # Generate code for doing the buffer release/acquisition.
1600                 # This might raise an exception in which case the assignment (done
1601                 # below) will not happen.
1602                 #
1603                 # The reason this is not in a typetest-like node is because the
1604                 # variables that the acquired buffer info is stored to is allocated
1605                 # per entry and coupled with it.
1606                 self.generate_acquire_buffer(rhs, code)
1607
1608             if self.type.is_pyobject:
1609                 #print "NameNode.generate_assignment_code: to", self.name ###
1610                 #print "...from", rhs ###
1611                 #print "...LHS type", self.type, "ctype", self.ctype() ###
1612                 #print "...RHS type", rhs.type, "ctype", rhs.ctype() ###
1613                 if self.use_managed_ref:
1614                     rhs.make_owned_reference(code)
1615                     if entry.is_cglobal:
1616                         code.put_gotref(self.py_result())
1617                     if not self.lhs_of_first_assignment:
1618                         if entry.is_local and not Options.init_local_none:
1619                             initialized = entry.scope.control_flow.get_state((entry.name, 'initialized'), self.pos)
1620                             if initialized is True:
1621                                 code.put_decref(self.result(), self.ctype())
1622                             elif initialized is None:
1623                                 code.put_xdecref(self.result(), self.ctype())
1624                         else:
1625                             code.put_decref(self.result(), self.ctype())
1626                     if entry.is_cglobal:
1627                         code.put_giveref(rhs.py_result())
1628
1629             code.putln('%s = %s;' % (self.result(),
1630                                      rhs.result_as(self.ctype())))
1631             if debug_disposal_code:
1632                 print("NameNode.generate_assignment_code:")
1633                 print("...generating post-assignment code for %s" % rhs)
1634             rhs.generate_post_assignment_code(code)
1635             rhs.free_temps(code)
1636
1637     def generate_acquire_buffer(self, rhs, code):
1638         # rhstmp is only used in case the rhs is a complicated expression leading to
1639         # the object, to avoid repeating the same C expression for every reference
1640         # to the rhs. It does NOT hold a reference.
1641         pretty_rhs = isinstance(rhs, NameNode) or rhs.is_temp
1642         if pretty_rhs:
1643             rhstmp = rhs.result_as(self.ctype())
1644         else:
1645             rhstmp = code.funcstate.allocate_temp(self.entry.type, manage_ref=False)
1646             code.putln('%s = %s;' % (rhstmp, rhs.result_as(self.ctype())))
1647
1648         buffer_aux = self.entry.buffer_aux
1649         bufstruct = buffer_aux.buffer_info_var.cname
1650         import Buffer
1651         Buffer.put_assign_to_buffer(self.result(), rhstmp, buffer_aux, self.entry.type,
1652                                     is_initialized=not self.lhs_of_first_assignment,
1653                                     pos=self.pos, code=code)
1654
1655         if not pretty_rhs:
1656             code.putln("%s = 0;" % rhstmp)
1657             code.funcstate.release_temp(rhstmp)
1658
1659     def generate_deletion_code(self, code):
1660         if self.entry is None:
1661             return # There was an error earlier
1662         if not self.entry.is_pyglobal:
1663             error(self.pos, "Deletion of local or C global name not supported")
1664             return
1665         if self.entry.is_pyclass_attr:
1666             namespace = self.entry.scope.namespace_cname
1667             code.put_error_if_neg(self.pos,
1668                 'PyMapping_DelItemString(%s, "%s")' % (
1669                     namespace,
1670                     self.entry.name))
1671         else:
1672             code.put_error_if_neg(self.pos,
1673                 '__Pyx_DelAttrString(%s, "%s")' % (
1674                     Naming.module_cname,
1675                     self.entry.name))
1676
1677     def annotate(self, code):
1678         if hasattr(self, 'is_called') and self.is_called:
1679             pos = (self.pos[0], self.pos[1], self.pos[2] - len(self.name) - 1)
1680             if self.type.is_pyobject:
1681                 code.annotate(pos, AnnotationItem('py_call', 'python function', size=len(self.name)))
1682             else:
1683                 code.annotate(pos, AnnotationItem('c_call', 'c function', size=len(self.name)))
1684
1685 class BackquoteNode(ExprNode):
1686     #  `expr`
1687     #
1688     #  arg    ExprNode
1689
1690     type = py_object_type
1691
1692     subexprs = ['arg']
1693
1694     def analyse_types(self, env):
1695         self.arg.analyse_types(env)
1696         self.arg = self.arg.coerce_to_pyobject(env)
1697         self.is_temp = 1
1698
1699     gil_message = "Backquote expression"
1700
1701     def calculate_constant_result(self):
1702         self.constant_result = repr(self.arg.constant_result)
1703
1704     def generate_result_code(self, code):
1705         code.putln(
1706             "%s = PyObject_Repr(%s); %s" % (
1707                 self.result(),
1708                 self.arg.py_result(),
1709                 code.error_goto_if_null(self.result(), self.pos)))
1710         code.put_gotref(self.py_result())
1711
1712
1713
1714 class ImportNode(ExprNode):
1715     #  Used as part of import statement implementation.
1716     #  Implements result =
1717     #    __import__(module_name, globals(), None, name_list)
1718     #
1719     #  module_name   StringNode            dotted name of module
1720     #  name_list     ListNode or None      list of names to be imported
1721
1722     type = py_object_type
1723
1724     subexprs = ['module_name', 'name_list']
1725
1726     def analyse_types(self, env):
1727         self.module_name.analyse_types(env)
1728         self.module_name = self.module_name.coerce_to_pyobject(env)
1729         if self.name_list:
1730             self.name_list.analyse_types(env)
1731             self.name_list.coerce_to_pyobject(env)
1732         self.is_temp = 1
1733         env.use_utility_code(import_utility_code)
1734
1735     gil_message = "Python import"
1736
1737     def generate_result_code(self, code):
1738         if self.name_list:
1739             name_list_code = self.name_list.py_result()
1740         else:
1741             name_list_code = "0"
1742         code.putln(
1743             "%s = __Pyx_Import(%s, %s); %s" % (
1744                 self.result(),
1745                 self.module_name.py_result(),
1746                 name_list_code,
1747                 code.error_goto_if_null(self.result(), self.pos)))
1748         code.put_gotref(self.py_result())
1749
1750
1751 class IteratorNode(ExprNode):
1752     #  Used as part of for statement implementation.
1753     #
1754     #  allocate_counter_temp/release_counter_temp needs to be called
1755     #  by parent (ForInStatNode)
1756     #
1757     #  Implements result = iter(sequence)
1758     #
1759     #  sequence   ExprNode
1760
1761     type = py_object_type
1762
1763     subexprs = ['sequence']
1764
1765     def analyse_types(self, env):
1766         self.sequence.analyse_types(env)
1767         if (self.sequence.type.is_array or self.sequence.type.is_ptr) and \
1768                 not self.sequence.type.is_string:
1769             # C array iteration will be transformed later on
1770             self.type = self.sequence.type
1771         else:
1772             self.sequence = self.sequence.coerce_to_pyobject(env)
1773             if self.sequence.type is list_type or \
1774                    self.sequence.type is tuple_type:
1775                 self.sequence = self.sequence.as_none_safe_node("'NoneType' object is not iterable")
1776         self.is_temp = 1
1777
1778     gil_message = "Iterating over Python object"
1779
1780     def allocate_counter_temp(self, code):
1781         self.counter_cname = code.funcstate.allocate_temp(
1782             PyrexTypes.c_py_ssize_t_type, manage_ref=False)
1783
1784     def release_counter_temp(self, code):
1785         code.funcstate.release_temp(self.counter_cname)
1786
1787     def generate_result_code(self, code):
1788         if self.sequence.type.is_array or self.sequence.type.is_ptr:
1789             raise InternalError("for in carray slice not transformed")
1790         is_builtin_sequence = self.sequence.type is list_type or \
1791                               self.sequence.type is tuple_type
1792         may_be_a_sequence = not self.sequence.type.is_builtin_type
1793         if may_be_a_sequence:
1794             code.putln(
1795                 "if (PyList_CheckExact(%s) || PyTuple_CheckExact(%s)) {" % (
1796                     self.sequence.py_result(),
1797                     self.sequence.py_result()))
1798         if is_builtin_sequence or may_be_a_sequence:
1799             code.putln(
1800                 "%s = 0; %s = %s; __Pyx_INCREF(%s);" % (
1801                     self.counter_cname,
1802                     self.result(),
1803                     self.sequence.py_result(),
1804                     self.result()))
1805         if not is_builtin_sequence:
1806             if may_be_a_sequence:
1807                 code.putln("} else {")
1808             code.putln("%s = -1; %s = PyObject_GetIter(%s); %s" % (
1809                     self.counter_cname,
1810                     self.result(),
1811                     self.sequence.py_result(),
1812                     code.error_goto_if_null(self.result(), self.pos)))
1813             code.put_gotref(self.py_result())
1814             if may_be_a_sequence:
1815                 code.putln("}")
1816
1817
1818 class NextNode(AtomicExprNode):
1819     #  Used as part of for statement implementation.
1820     #  Implements result = iterator.next()
1821     #  Created during analyse_types phase.
1822     #  The iterator is not owned by this node.
1823     #
1824     #  iterator   ExprNode
1825
1826     type = py_object_type
1827
1828     def __init__(self, iterator, env):
1829         self.pos = iterator.pos
1830         self.iterator = iterator
1831         if iterator.type.is_ptr or iterator.type.is_array:
1832             self.type = iterator.type.base_type
1833         self.is_temp = 1
1834
1835     def generate_result_code(self, code):
1836         sequence_type = self.iterator.sequence.type
1837         if sequence_type is list_type:
1838             type_checks = [(list_type, "List")]
1839         elif sequence_type is tuple_type:
1840             type_checks = [(tuple_type, "Tuple")]
1841         elif not sequence_type.is_builtin_type:
1842             type_checks = [(list_type, "List"), (tuple_type, "Tuple")]
1843         else:
1844             type_checks = []
1845
1846         for py_type, prefix in type_checks:
1847             if len(type_checks) > 1:
1848                 code.putln(
1849                     "if (likely(Py%s_CheckExact(%s))) {" % (
1850                         prefix, self.iterator.py_result()))
1851             code.putln(
1852                 "if (%s >= Py%s_GET_SIZE(%s)) break;" % (
1853                     self.iterator.counter_cname,
1854                     prefix,
1855                     self.iterator.py_result()))
1856             code.putln(
1857                 "%s = Py%s_GET_ITEM(%s, %s); __Pyx_INCREF(%s); %s++;" % (
1858                     self.result(),
1859                     prefix,
1860                     self.iterator.py_result(),
1861                     self.iterator.counter_cname,
1862                     self.result(),
1863                     self.iterator.counter_cname))
1864             if len(type_checks) > 1:
1865                 code.put("} else ")
1866         if len(type_checks) == 1:
1867             return
1868         code.putln("{")
1869         code.putln(
1870             "%s = PyIter_Next(%s);" % (
1871                 self.result(),
1872                 self.iterator.py_result()))
1873         code.putln(
1874             "if (!%s) {" %
1875                 self.result())
1876         code.putln(code.error_goto_if_PyErr(self.pos))
1877         code.putln("break;")
1878         code.putln("}")
1879         code.put_gotref(self.py_result())
1880         code.putln("}")
1881
1882
1883 class ExcValueNode(AtomicExprNode):
1884     #  Node created during analyse_types phase
1885     #  of an ExceptClauseNode to fetch the current
1886     #  exception value.
1887
1888     type = py_object_type
1889
1890     def __init__(self, pos, env):
1891         ExprNode.__init__(self, pos)
1892
1893     def set_var(self, var):
1894         self.var = var
1895
1896     def calculate_result_code(self):
1897         return self.var
1898
1899     def generate_result_code(self, code):
1900         pass
1901
1902     def analyse_types(self, env):
1903         pass
1904
1905
1906 class TempNode(ExprNode):
1907     # Node created during analyse_types phase
1908     # of some nodes to hold a temporary value.
1909     #
1910     # Note: One must call "allocate" and "release" on
1911     # the node during code generation to get/release the temp.
1912     # This is because the temp result is often used outside of
1913     # the regular cycle.
1914
1915     subexprs = []
1916
1917     def __init__(self, pos, type, env):
1918         ExprNode.__init__(self, pos)
1919         self.type = type
1920         if type.is_pyobject:
1921             self.result_ctype = py_object_type
1922         self.is_temp = 1
1923
1924     def analyse_types(self, env):
1925         return self.type
1926
1927     def generate_result_code(self, code):
1928         pass
1929
1930     def allocate(self, code):
1931         self.temp_cname = code.funcstate.allocate_temp(self.type, manage_ref=True)
1932
1933     def release(self, code):
1934         code.funcstate.release_temp(self.temp_cname)
1935         self.temp_cname = None
1936
1937     def result(self):
1938         try:
1939             return self.temp_cname
1940         except:
1941             assert False, "Remember to call allocate/release on TempNode"
1942             raise
1943
1944     # Do not participate in normal temp alloc/dealloc:
1945     def allocate_temp_result(self, code):
1946         pass
1947
1948     def release_temp_result(self, code):
1949         pass
1950
1951 class PyTempNode(TempNode):
1952     #  TempNode holding a Python value.
1953
1954     def __init__(self, pos, env):
1955         TempNode.__init__(self, pos, PyrexTypes.py_object_type, env)
1956
1957 class RawCNameExprNode(ExprNode):
1958     subexprs = []
1959
1960     def __init__(self, pos, type=None):
1961         self.pos = pos
1962         self.type = type
1963
1964     def analyse_types(self, env):
1965         return self.type
1966
1967     def set_cname(self, cname):
1968         self.cname = cname
1969
1970     def result(self):
1971         return self.cname
1972
1973     def generate_result_code(self, code):
1974         pass
1975
1976
1977 #-------------------------------------------------------------------
1978 #
1979 #  Trailer nodes
1980 #
1981 #-------------------------------------------------------------------
1982
1983 class IndexNode(ExprNode):
1984     #  Sequence indexing.
1985     #
1986     #  base     ExprNode
1987     #  index    ExprNode
1988     #  indices  [ExprNode]
1989     #  is_buffer_access boolean Whether this is a buffer access.
1990     #
1991     #  indices is used on buffer access, index on non-buffer access.
1992     #  The former contains a clean list of index parameters, the
1993     #  latter whatever Python object is needed for index access.
1994
1995     subexprs = ['base', 'index', 'indices']
1996     indices = None
1997
1998     def __init__(self, pos, index, *args, **kw):
1999         ExprNode.__init__(self, pos, index=index, *args, **kw)
2000         self._index = index
2001
2002     def calculate_constant_result(self):
2003         self.constant_result = \
2004             self.base.constant_result[self.index.constant_result]
2005
2006     def compile_time_value(self, denv):
2007         base = self.base.compile_time_value(denv)
2008         index = self.index.compile_time_value(denv)
2009         try:
2010             return base[index]
2011         except Exception, e:
2012             self.compile_time_value_error(e)
2013
2014     def is_ephemeral(self):
2015         return self.base.is_ephemeral()
2016
2017     def is_simple(self):
2018         if self.is_buffer_access:
2019             return False
2020         base = self.base
2021         return (base.is_simple() and self.index.is_simple()
2022                 and base.type and (base.type.is_ptr or base.type.is_array))
2023
2024     def analyse_target_declaration(self, env):
2025         pass
2026
2027     def analyse_as_type(self, env):
2028         base_type = self.base.analyse_as_type(env)
2029         if base_type and not base_type.is_pyobject:
2030             if base_type.is_cpp_class:
2031                 if isinstance(self.index, TupleNode):
2032                     template_values = self.index.args
2033                 else:
2034                     template_values = [self.index]
2035                 import Nodes
2036                 type_node = Nodes.TemplatedTypeNode(
2037                     pos = self.pos,
2038                     positional_args = template_values,
2039                     keyword_args = None)
2040                 return type_node.analyse(env, base_type = base_type)
2041             else:
2042                 return PyrexTypes.CArrayType(base_type, int(self.index.compile_time_value(env)))
2043         return None
2044
2045     def type_dependencies(self, env):
2046         return self.base.type_dependencies(env) + self.index.type_dependencies(env)
2047
2048     def infer_type(self, env):
2049         base_type = self.base.infer_type(env)
2050         if isinstance(self.index, SliceNode):
2051             # slicing!
2052             if base_type.is_string:
2053                 # sliced C strings must coerce to Python
2054                 return bytes_type
2055             elif base_type in (unicode_type, bytes_type, str_type, list_type, tuple_type):
2056                 # slicing these returns the same type
2057                 return base_type
2058             else:
2059                 # TODO: Handle buffers (hopefully without too much redundancy).
2060                 return py_object_type
2061
2062         index_type = self.index.infer_type(env)
2063         if index_type and index_type.is_int or isinstance(self.index, (IntNode, LongNode)):
2064             # indexing!
2065             if base_type is unicode_type:
2066                 # Py_UNICODE will automatically coerce to a unicode string
2067                 # if required, so this is safe. We only infer Py_UNICODE
2068                 # when the index is a C integer type. Otherwise, we may
2069                 # need to use normal Python item access, in which case
2070                 # it's faster to return the one-char unicode string than
2071                 # to receive it, throw it away, and potentially rebuild it
2072                 # on a subsequent PyObject coercion.
2073                 return PyrexTypes.c_py_unicode_type
2074             elif isinstance(self.base, BytesNode):
2075                 #if env.global_scope().context.language_level >= 3:
2076                 #    # infering 'char' can be made to work in Python 3 mode
2077                 #    return PyrexTypes.c_char_type
2078                 # Py2/3 return different types on indexing bytes objects
2079                 return py_object_type
2080             elif base_type.is_ptr or base_type.is_array:
2081                 return base_type.base_type
2082
2083         # may be slicing or indexing, we don't know
2084         if base_type is unicode_type:
2085             # this type always returns its own type on Python indexing/slicing
2086             return base_type
2087         else:
2088             # TODO: Handle buffers (hopefully without too much redundancy).
2089             return py_object_type
2090
2091     def analyse_types(self, env):
2092         self.analyse_base_and_index_types(env, getting = 1)
2093
2094     def analyse_target_types(self, env):
2095         self.analyse_base_and_index_types(env, setting = 1)
2096
2097     def analyse_base_and_index_types(self, env, getting = 0, setting = 0):
2098         # Note: This might be cleaned up by having IndexNode
2099         # parsed in a saner way and only construct the tuple if
2100         # needed.
2101
2102         # Note that this function must leave IndexNode in a cloneable state.
2103         # For buffers, self.index is packed out on the initial analysis, and
2104         # when cloning self.indices is copied.
2105         self.is_buffer_access = False
2106
2107         self.base.analyse_types(env)
2108         if self.base.type.is_error:
2109             # Do not visit child tree if base is undeclared to avoid confusing
2110             # error messages
2111             self.type = PyrexTypes.error_type
2112             return
2113
2114         is_slice = isinstance(self.index, SliceNode)
2115         # Potentially overflowing index value.
2116         if not is_slice and isinstance(self.index, IntNode) and Utils.long_literal(self.index.value):
2117             self.index = self.index.coerce_to_pyobject(env)
2118
2119         # Handle the case where base is a literal char* (and we expect a string, not an int)
2120         if isinstance(self.base, BytesNode) or is_slice:
2121             if self.base.type.is_string or not (self.base.type.is_ptr or self.base.type.is_array):
2122                 self.base = self.base.coerce_to_pyobject(env)
2123
2124         skip_child_analysis = False
2125         buffer_access = False
2126         if self.base.type.is_buffer:
2127             if self.indices:
2128                 indices = self.indices
2129             else:
2130                 if isinstance(self.index, TupleNode):
2131                     indices = self.index.args
2132                 else:
2133                     indices = [self.index]
2134             if len(indices) == self.base.type.ndim:
2135                 buffer_access = True
2136                 skip_child_analysis = True
2137                 for x in indices:
2138                     x.analyse_types(env)
2139                     if not x.type.is_int:
2140                         buffer_access = False
2141             if buffer_access:
2142                 assert hasattr(self.base, "entry") # Must be a NameNode-like node
2143
2144         # On cloning, indices is cloned. Otherwise, unpack index into indices
2145         assert not (buffer_access and isinstance(self.index, CloneNode))
2146
2147         if buffer_access:
2148             self.indices = indices
2149             self.index = None
2150             self.type = self.base.type.dtype
2151             self.is_buffer_access = True
2152             self.buffer_type = self.base.entry.type
2153
2154             if getting and self.type.is_pyobject:
2155                 self.is_temp = True
2156             if setting:
2157                 if not self.base.entry.type.writable:
2158                     error(self.pos, "Writing to readonly buffer")
2159                 else:
2160                     self.base.entry.buffer_aux.writable_needed = True
2161         else:
2162             base_type = self.base.type
2163             if isinstance(self.index, TupleNode):
2164                 self.index.analyse_types(env, skip_children=skip_child_analysis)
2165             elif not skip_child_analysis:
2166                 self.index.analyse_types(env)
2167             self.original_index_type = self.index.type
2168             if base_type is PyrexTypes.c_py_unicode_type:
2169                 # we infer Py_UNICODE for unicode strings in some
2170                 # cases, but indexing must still work for them
2171                 if self.index.constant_result in (0, -1):
2172                     # FIXME: we know that this node is redundant -
2173                     # currently, this needs to get handled in Optimize.py
2174                     pass
2175                 self.base = self.base.coerce_to_pyobject(env)
2176                 base_type = self.base.type
2177             if base_type.is_pyobject:
2178                 if self.index.type.is_int:
2179                     if (not setting
2180                         and (base_type in (list_type, tuple_type, unicode_type))
2181                         and (not self.index.type.signed or isinstance(self.index, IntNode) and int(self.index.value) >= 0)
2182                         and not env.directives['boundscheck']):
2183                         self.is_temp = 0
2184                     else:
2185                         self.is_temp = 1
2186                     self.index = self.index.coerce_to(PyrexTypes.c_py_ssize_t_type, env).coerce_to_simple(env)
2187                 else:
2188                     self.index = self.index.coerce_to_pyobject(env)
2189                     self.is_temp = 1
2190                 if self.index.type.is_int and base_type is unicode_type:
2191                     # Py_UNICODE will automatically coerce to a unicode string
2192                     # if required, so this is fast and safe
2193                     self.type = PyrexTypes.c_py_unicode_type
2194                 elif is_slice and base_type in (bytes_type, str_type, unicode_type, list_type, tuple_type):
2195                     self.type = base_type
2196                 else:
2197                     self.type = py_object_type
2198             else:
2199                 if base_type.is_ptr or base_type.is_array:
2200                     self.type = base_type.base_type
2201                     if is_slice:
2202                         self.type = base_type
2203                     elif self.index.type.is_pyobject:
2204                         self.index = self.index.coerce_to(
2205                             PyrexTypes.c_py_ssize_t_type, env)
2206                     elif not self.index.type.is_int:
2207                         error(self.pos,
2208                             "Invalid index type '%s'" %
2209                                 self.index.type)
2210                 elif base_type.is_cpp_class:
2211                     function = env.lookup_operator("[]", [self.base, self.index])
2212                     if function is None:
2213                         error(self.pos, "Indexing '%s' not supported for index type '%s'" % (base_type, self.index.type))
2214                         self.type = PyrexTypes.error_type
2215                         self.result_code = "<error>"
2216                         return
2217                     func_type = function.type
2218                     if func_type.is_ptr:
2219                         func_type = func_type.base_type
2220                     self.index = self.index.coerce_to(func_type.args[0].type, env)
2221                     self.type = func_type.return_type
2222                     if setting and not func_type.return_type.is_reference:
2223                         error(self.pos, "Can't set non-reference result '%s'" % self.type)
2224                 else:
2225                     error(self.pos,
2226                         "Attempting to index non-array type '%s'" %
2227                             base_type)
2228                     self.type = PyrexTypes.error_type
2229
2230     gil_message = "Indexing Python object"
2231
2232     def nogil_check(self, env):
2233         if self.is_buffer_access:
2234             if env.directives['boundscheck']:
2235                 error(self.pos, "Cannot check buffer index bounds without gil; use boundscheck(False) directive")
2236                 return
2237             elif self.type.is_pyobject:
2238                 error(self.pos, "Cannot access buffer with object dtype without gil")
2239                 return
2240         super(IndexNode, self).nogil_check(env)
2241
2242
2243     def check_const_addr(self):
2244         return self.base.check_const_addr() and self.index.check_const()
2245
2246     def is_lvalue(self):
2247         return 1
2248
2249     def calculate_result_code(self):
2250         if self.is_buffer_access:
2251             return "(*%s)" % self.buffer_ptr_code
2252         elif self.base.type is list_type:
2253             return "PyList_GET_ITEM(%s, %s)" % (self.base.result(), self.index.result())
2254         elif self.base.type is tuple_type:
2255             return "PyTuple_GET_ITEM(%s, %s)" % (self.base.result(), self.index.result())
2256         elif self.base.type is unicode_type and self.type is PyrexTypes.c_py_unicode_type:
2257             return "PyUnicode_AS_UNICODE(%s)[%s]" % (self.base.result(), self.index.result())
2258         elif (self.type.is_ptr or self.type.is_array) and self.type == self.base.type:
2259             error(self.pos, "Invalid use of pointer slice")
2260         else:
2261             return "(%s[%s])" % (
2262                 self.base.result(), self.index.result())
2263
2264     def extra_index_params(self):
2265         if self.index.type.is_int:
2266             if self.original_index_type.signed:
2267                 size_adjustment = ""
2268             else:
2269                 size_adjustment = "+1"
2270             return ", sizeof(%s)%s, %s" % (self.original_index_type.declaration_code(""), size_adjustment, self.original_index_type.to_py_function)
2271         else:
2272             return ""
2273
2274     def generate_subexpr_evaluation_code(self, code):
2275         self.base.generate_evaluation_code(code)
2276         if not self.indices:
2277             self.index.generate_evaluation_code(code)
2278         else:
2279             for i in self.indices:
2280                 i.generate_evaluation_code(code)
2281
2282     def generate_subexpr_disposal_code(self, code):
2283         self.base.generate_disposal_code(code)
2284         if not self.indices:
2285             self.index.generate_disposal_code(code)
2286         else:
2287             for i in self.indices:
2288                 i.generate_disposal_code(code)
2289
2290     def free_subexpr_temps(self, code):
2291         self.base.free_temps(code)
2292         if not self.indices:
2293             self.index.free_temps(code)
2294         else:
2295             for i in self.indices:
2296                 i.free_temps(code)
2297
2298     def generate_result_code(self, code):
2299         if self.is_buffer_access:
2300             if code.globalstate.directives['nonecheck']:
2301                 self.put_nonecheck(code)
2302             self.buffer_ptr_code = self.buffer_lookup_code(code)
2303             if self.type.is_pyobject:
2304                 # is_temp is True, so must pull out value and incref it.
2305                 code.putln("%s = *%s;" % (self.result(), self.buffer_ptr_code))
2306                 code.putln("__Pyx_INCREF((PyObject*)%s);" % self.result())
2307         elif self.is_temp:
2308             if self.type.is_pyobject:
2309                 if self.index.type.is_int:
2310                     index_code = self.index.result()
2311                     if self.base.type is list_type:
2312                         function = "__Pyx_GetItemInt_List"
2313                     elif self.base.type is tuple_type:
2314                         function = "__Pyx_GetItemInt_Tuple"
2315                     else:
2316                         function = "__Pyx_GetItemInt"
2317                     code.globalstate.use_utility_code(getitem_int_utility_code)
2318                 else:
2319                     index_code = self.index.py_result()
2320                     if self.base.type is dict_type:
2321                         function = "__Pyx_PyDict_GetItem"
2322                         code.globalstate.use_utility_code(getitem_dict_utility_code)
2323                     else:
2324                         function = "PyObject_GetItem"
2325                 code.putln(
2326                     "%s = %s(%s, %s%s); if (!%s) %s" % (
2327                         self.result(),
2328                         function,
2329                         self.base.py_result(),
2330                         index_code,
2331                         self.extra_index_params(),
2332                         self.result(),
2333                         code.error_goto(self.pos)))
2334                 code.put_gotref(self.py_result())
2335             elif self.type is PyrexTypes.c_py_unicode_type and self.base.type is unicode_type:
2336                 assert self.index.type.is_int
2337                 index_code = self.index.result()
2338                 function = "__Pyx_GetItemInt_Unicode"
2339                 code.globalstate.use_utility_code(getitem_int_pyunicode_utility_code)
2340                 code.putln(
2341                     "%s = %s(%s, %s%s); if (unlikely(%s == (Py_UNICODE)-1)) %s;" % (
2342                         self.result(),
2343                         function,
2344                         self.base.py_result(),
2345                         index_code,
2346                         self.extra_index_params(),
2347                         self.result(),
2348                         code.error_goto(self.pos)))
2349
2350     def generate_setitem_code(self, value_code, code):
2351         if self.index.type.is_int:
2352             function = "__Pyx_SetItemInt"
2353             index_code = self.index.result()
2354             code.globalstate.use_utility_code(setitem_int_utility_code)
2355         else:
2356             index_code = self.index.py_result()
2357             if self.base.type is dict_type:
2358                 function = "PyDict_SetItem"
2359             # It would seem that we could specialized lists/tuples, but that
2360             # shouldn't happen here.
2361             # Both PyList_SetItem PyTuple_SetItem and a Py_ssize_t as input,
2362             # not a PyObject*, and bad conversion here would give the wrong
2363             # exception. Also, tuples are supposed to be immutable, and raise
2364             # TypeErrors when trying to set their entries (PyTuple_SetItem
2365             # is for creating new tuples from).
2366             else:
2367                 function = "PyObject_SetItem"
2368         code.putln(
2369             "if (%s(%s, %s, %s%s) < 0) %s" % (
2370                 function,
2371                 self.base.py_result(),
2372                 index_code,
2373                 value_code,
2374                 self.extra_index_params(),
2375                 code.error_goto(self.pos)))
2376
2377     def generate_buffer_setitem_code(self, rhs, code, op=""):
2378         # Used from generate_assignment_code and InPlaceAssignmentNode
2379         if code.globalstate.directives['nonecheck']:
2380             self.put_nonecheck(code)
2381         ptrexpr = self.buffer_lookup_code(code)
2382         if self.buffer_type.dtype.is_pyobject:
2383             # Must manage refcounts. Decref what is already there
2384             # and incref what we put in.
2385             ptr = code.funcstate.allocate_temp(self.buffer_type.buffer_ptr_type, manage_ref=False)
2386             rhs_code = rhs.result()
2387             code.putln("%s = %s;" % (ptr, ptrexpr))
2388             code.put_gotref("*%s" % ptr)
2389             code.putln("__Pyx_DECREF(*%s); __Pyx_INCREF(%s);" % (
2390                 ptr, rhs_code
2391                 ))
2392             code.putln("*%s %s= %s;" % (ptr, op, rhs_code))
2393             code.put_giveref("*%s" % ptr)
2394             code.funcstate.release_temp(ptr)
2395         else:
2396             # Simple case
2397             code.putln("*%s %s= %s;" % (ptrexpr, op, rhs.result()))
2398
2399     def generate_assignment_code(self, rhs, code):
2400         self.generate_subexpr_evaluation_code(code)
2401         if self.is_buffer_access:
2402             self.generate_buffer_setitem_code(rhs, code)
2403         elif self.type.is_pyobject:
2404             self.generate_setitem_code(rhs.py_result(), code)
2405         else:
2406             code.putln(
2407                 "%s = %s;" % (
2408                     self.result(), rhs.result()))
2409         self.generate_subexpr_disposal_code(code)
2410         self.free_subexpr_temps(code)
2411         rhs.generate_disposal_code(code)
2412         rhs.free_temps(code)
2413
2414     def generate_deletion_code(self, code):
2415         self.generate_subexpr_evaluation_code(code)
2416         #if self.type.is_pyobject:
2417         if self.index.type.is_int:
2418             function = "__Pyx_DelItemInt"
2419             index_code = self.index.result()
2420             code.globalstate.use_utility_code(delitem_int_utility_code)
2421         else:
2422             index_code = self.index.py_result()
2423             if self.base.type is dict_type:
2424                 function = "PyDict_DelItem"
2425             else:
2426                 function = "PyObject_DelItem"
2427         code.putln(
2428             "if (%s(%s, %s%s) < 0) %s" % (
2429                 function,
2430                 self.base.py_result(),
2431                 index_code,
2432                 self.extra_index_params(),
2433                 code.error_goto(self.pos)))
2434         self.generate_subexpr_disposal_code(code)
2435         self.free_subexpr_temps(code)
2436
2437     def buffer_lookup_code(self, code):
2438         # Assign indices to temps
2439         index_temps = [code.funcstate.allocate_temp(i.type, manage_ref=False) for i in self.indices]
2440         for temp, index in zip(index_temps, self.indices):
2441             code.putln("%s = %s;" % (temp, index.result()))
2442         # Generate buffer access code using these temps
2443         import Buffer
2444         # The above could happen because child_attrs is wrong somewhere so that
2445         # options are not propagated.
2446         return Buffer.put_buffer_lookup_code(entry=self.base.entry,
2447                                              index_signeds=[i.type.signed for i in self.indices],
2448                                              index_cnames=index_temps,
2449                                              directives=code.globalstate.directives,
2450                                              pos=self.pos, code=code)
2451
2452     def put_nonecheck(self, code):
2453         code.globalstate.use_utility_code(raise_noneindex_error_utility_code)
2454         code.putln("if (%s) {" % code.unlikely("%s == Py_None") % self.base.result_as(PyrexTypes.py_object_type))
2455         code.putln("__Pyx_RaiseNoneIndexingError();")
2456         code.putln(code.error_goto(self.pos))
2457         code.putln("}")
2458
2459 class SliceIndexNode(ExprNode):
2460     #  2-element slice indexing
2461     #
2462     #  base      ExprNode
2463     #  start     ExprNode or None
2464     #  stop      ExprNode or None
2465
2466     subexprs = ['base', 'start', 'stop']
2467
2468     def infer_type(self, env):
2469         base_type = self.base.infer_type(env)
2470         if base_type.is_string:
2471             return bytes_type
2472         elif base_type in (bytes_type, str_type, unicode_type,
2473                            list_type, tuple_type):
2474             return base_type
2475         return py_object_type
2476
2477     def calculate_constant_result(self):
2478         self.constant_result = self.base.constant_result[
2479             self.start.constant_result : self.stop.constant_result]
2480
2481     def compile_time_value(self, denv):
2482         base = self.base.compile_time_value(denv)
2483         if self.start is None:
2484             start = 0
2485         else:
2486             start = self.start.compile_time_value(denv)
2487         if self.stop is None:
2488             stop = None
2489         else:
2490             stop = self.stop.compile_time_value(denv)
2491         try:
2492             return base[start:stop]
2493         except Exception, e:
2494             self.compile_time_value_error(e)
2495
2496     def analyse_target_declaration(self, env):
2497         pass
2498
2499     def analyse_target_types(self, env):
2500         self.analyse_types(env)
2501         # when assigning, we must accept any Python type
2502         if self.type.is_pyobject:
2503             self.type = py_object_type
2504
2505     def analyse_types(self, env):
2506         self.base.analyse_types(env)
2507         if self.start:
2508             self.start.analyse_types(env)
2509         if self.stop:
2510             self.stop.analyse_types(env)
2511         base_type = self.base.type
2512         if base_type.is_string:
2513             self.type = bytes_type
2514         elif base_type.is_ptr:
2515             self.type = base_type
2516         elif base_type.is_array:
2517             # we need a ptr type here instead of an array type, as
2518             # array types can result in invalid type casts in the C
2519             # code
2520             self.type = PyrexTypes.CPtrType(base_type.base_type)
2521         else:
2522             self.base = self.base.coerce_to_pyobject(env)
2523             self.type = py_object_type
2524         if base_type.is_builtin_type:
2525             # slicing builtin types returns something of the same type
2526             self.type = base_type
2527         c_int = PyrexTypes.c_py_ssize_t_type
2528         if self.start:
2529             self.start = self.start.coerce_to(c_int, env)
2530         if self.stop:
2531             self.stop = self.stop.coerce_to(c_int, env)
2532         self.is_temp = 1
2533
2534     nogil_check = Node.gil_error
2535     gil_message = "Slicing Python object"
2536
2537     def generate_result_code(self, code):
2538         if not self.type.is_pyobject:
2539             error(self.pos,
2540                   "Slicing is not currently supported for '%s'." % self.type)
2541             return
2542         if self.base.type.is_string:
2543             if self.stop is None:
2544                 code.putln(
2545                     "%s = PyBytes_FromString(%s + %s); %s" % (
2546                         self.result(),
2547                         self.base.result(),
2548                         self.start_code(),
2549                         code.error_goto_if_null(self.result(), self.pos)))
2550             else:
2551                 code.putln(
2552                     "%s = PyBytes_FromStringAndSize(%s + %s, %s - %s); %s" % (
2553                         self.result(),
2554                         self.base.result(),
2555                         self.start_code(),
2556                         self.stop_code(),
2557                         self.start_code(),
2558                         code.error_goto_if_null(self.result(), self.pos)))
2559         else:
2560             code.putln(
2561                 "%s = __Pyx_PySequence_GetSlice(%s, %s, %s); %s" % (
2562                     self.result(),
2563                     self.base.py_result(),
2564                     self.start_code(),
2565                     self.stop_code(),
2566                     code.error_goto_if_null(self.result(), self.pos)))
2567         code.put_gotref(self.py_result())
2568
2569     def generate_assignment_code(self, rhs, code):
2570         self.generate_subexpr_evaluation_code(code)
2571         if self.type.is_pyobject:
2572             code.put_error_if_neg(self.pos,
2573                 "__Pyx_PySequence_SetSlice(%s, %s, %s, %s)" % (
2574                     self.base.py_result(),
2575                     self.start_code(),
2576                     self.stop_code(),
2577                     rhs.py_result()))
2578         else:
2579             start_offset = ''
2580             if self.start:
2581                 start_offset = self.start_code()
2582                 if start_offset == '0':
2583                     start_offset = ''
2584                 else:
2585                     start_offset += '+'
2586             if rhs.type.is_array:
2587                 array_length = rhs.type.size
2588                 self.generate_slice_guard_code(code, array_length)
2589             else:
2590                 error(self.pos,
2591                       "Slice assignments from pointers are not yet supported.")
2592                 # FIXME: fix the array size according to start/stop
2593                 array_length = self.base.type.size
2594             for i in range(array_length):
2595                 code.putln("%s[%s%s] = %s[%d];" % (
2596                         self.base.result(), start_offset, i,
2597                         rhs.result(), i))
2598         self.generate_subexpr_disposal_code(code)
2599         self.free_subexpr_temps(code)
2600         rhs.generate_disposal_code(code)
2601         rhs.free_temps(code)
2602
2603     def generate_deletion_code(self, code):
2604         if not self.base.type.is_pyobject:
2605             error(self.pos,
2606                   "Deleting slices is only supported for Python types, not '%s'." % self.type)
2607             return
2608         self.generate_subexpr_evaluation_code(code)
2609         code.put_error_if_neg(self.pos,
2610             "__Pyx_PySequence_DelSlice(%s, %s, %s)" % (
2611                 self.base.py_result(),
2612                 self.start_code(),
2613                 self.stop_code()))
2614         self.generate_subexpr_disposal_code(code)
2615         self.free_subexpr_temps(code)
2616
2617     def generate_slice_guard_code(self, code, target_size):
2618         if not self.base.type.is_array:
2619             return
2620         slice_size = self.base.type.size
2621         start = stop = None
2622         if self.stop:
2623             stop = self.stop.result()
2624             try:
2625                 stop = int(stop)
2626                 if stop < 0:
2627                     slice_size = self.base.type.size + stop
2628                 else:
2629                     slice_size = stop
2630                 stop = None
2631             except ValueError:
2632                 pass
2633         if self.start:
2634             start = self.start.result()
2635             try:
2636                 start = int(start)
2637                 if start < 0:
2638                     start = self.base.type.size + start
2639                 slice_size -= start
2640                 start = None
2641             except ValueError:
2642                 pass
2643         check = None
2644         if slice_size < 0:
2645             if target_size > 0:
2646                 error(self.pos, "Assignment to empty slice.")
2647         elif start is None and stop is None:
2648             # we know the exact slice length
2649             if target_size != slice_size:
2650                 error(self.pos, "Assignment to slice of wrong length, expected %d, got %d" % (
2651                         slice_size, target_size))
2652         elif start is not None:
2653             if stop is None:
2654                 stop = slice_size
2655             check = "(%s)-(%s)" % (stop, start)
2656         else: # stop is not None:
2657             check = stop
2658         if check:
2659             code.putln("if (unlikely((%s) != %d)) {" % (check, target_size))
2660             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));' % (
2661                         target_size, check))
2662             code.putln(code.error_goto(self.pos))
2663             code.putln("}")
2664
2665     def start_code(self):
2666         if self.start:
2667             return self.start.result()
2668         else:
2669             return "0"
2670
2671     def stop_code(self):
2672         if self.stop:
2673             return self.stop.result()
2674         elif self.base.type.is_array:
2675             return self.base.type.size
2676         else:
2677             return "PY_SSIZE_T_MAX"
2678
2679     def calculate_result_code(self):
2680         # self.result() is not used, but this method must exist
2681         return "<unused>"
2682
2683
2684 class SliceNode(ExprNode):
2685     #  start:stop:step in subscript list
2686     #
2687     #  start     ExprNode
2688     #  stop      ExprNode
2689     #  step      ExprNode
2690
2691     type = py_object_type
2692     is_temp = 1
2693
2694     def calculate_constant_result(self):
2695         self.constant_result = self.base.constant_result[
2696             self.start.constant_result : \
2697                 self.stop.constant_result : \
2698                 self.step.constant_result]
2699
2700     def compile_time_value(self, denv):
2701         start = self.start.compile_time_value(denv)
2702         if self.stop is None:
2703             stop = None
2704         else:
2705             stop = self.stop.compile_time_value(denv)
2706         if self.step is None:
2707             step = None
2708         else:
2709             step = self.step.compile_time_value(denv)
2710         try:
2711             return slice(start, stop, step)
2712         except Exception, e:
2713             self.compile_time_value_error(e)
2714
2715     subexprs = ['start', 'stop', 'step']
2716
2717     def analyse_types(self, env):
2718         self.start.analyse_types(env)
2719         self.stop.analyse_types(env)
2720         self.step.analyse_types(env)
2721         self.start = self.start.coerce_to_pyobject(env)
2722         self.stop = self.stop.coerce_to_pyobject(env)
2723         self.step = self.step.coerce_to_pyobject(env)
2724
2725     gil_message = "Constructing Python slice object"
2726
2727     def generate_result_code(self, code):
2728         code.putln(
2729             "%s = PySlice_New(%s, %s, %s); %s" % (
2730                 self.result(),
2731                 self.start.py_result(),
2732                 self.stop.py_result(),
2733                 self.step.py_result(),
2734                 code.error_goto_if_null(self.result(), self.pos)))
2735         code.put_gotref(self.py_result())
2736
2737
2738 class CallNode(ExprNode):
2739
2740     # allow overriding the default 'may_be_none' behaviour
2741     may_return_none = None
2742
2743     def may_be_none(self):
2744         if self.may_return_none is not None:
2745             return self.may_return_none
2746         return ExprNode.may_be_none(self)
2747
2748     def analyse_as_type_constructor(self, env):
2749         type = self.function.analyse_as_type(env)
2750         if type and type.is_struct_or_union:
2751             args, kwds = self.explicit_args_kwds()
2752             items = []
2753             for arg, member in zip(args, type.scope.var_entries):
2754                 items.append(DictItemNode(pos=arg.pos, key=StringNode(pos=arg.pos, value=member.name), value=arg))
2755             if kwds:
2756                 items += kwds.key_value_pairs
2757             self.key_value_pairs = items
2758             self.__class__ = DictNode
2759             self.analyse_types(env)
2760             self.coerce_to(type, env)
2761             return True
2762         elif type and type.is_cpp_class:
2763             for arg in self.args:
2764                 arg.analyse_types(env)
2765             constructor = type.scope.lookup("<init>")
2766             self.function = RawCNameExprNode(self.function.pos, constructor.type)
2767             self.function.entry = constructor
2768             self.function.set_cname(type.declaration_code(""))
2769             self.analyse_c_function_call(env)
2770             return True
2771
2772     def is_lvalue(self):
2773         return self.type.is_reference
2774
2775     def nogil_check(self, env):
2776         func_type = self.function_type()
2777         if func_type.is_pyobject:
2778             self.gil_error()
2779         elif not getattr(func_type, 'nogil', False):
2780             self.gil_error()
2781
2782     gil_message = "Calling gil-requiring function"
2783
2784
2785 class SimpleCallNode(CallNode):
2786     #  Function call without keyword, * or ** args.
2787     #
2788     #  function       ExprNode
2789     #  args           [ExprNode]
2790     #  arg_tuple      ExprNode or None     used internally
2791     #  self           ExprNode or None     used internally
2792     #  coerced_self   ExprNode or None     used internally
2793     #  wrapper_call   bool                 used internally
2794     #  has_optional_args   bool            used internally
2795     #  nogil          bool                 used internally
2796
2797     subexprs = ['self', 'coerced_self', 'function', 'args', 'arg_tuple']
2798
2799     self = None
2800     coerced_self = None
2801     arg_tuple = None
2802     wrapper_call = False
2803     has_optional_args = False
2804     nogil = False
2805     analysed = False
2806
2807     def compile_time_value(self, denv):
2808         function = self.function.compile_time_value(denv)
2809         args = [arg.compile_time_value(denv) for arg in self.args]
2810         try:
2811             return function(*args)
2812         except Exception, e:
2813             self.compile_time_value_error(e)
2814
2815     def type_dependencies(self, env):
2816         # TODO: Update when Danilo's C++ code merged in to handle the
2817         # the case of function overloading.
2818         return self.function.type_dependencies(env)
2819
2820     def infer_type(self, env):
2821         function = self.function
2822         func_type = function.infer_type(env)
2823         if isinstance(self.function, NewExprNode):
2824             return PyrexTypes.CPtrType(self.function.class_type)
2825         if func_type.is_ptr:
2826             func_type = func_type.base_type
2827         if func_type.is_cfunction:
2828             return func_type.return_type
2829         elif func_type is type_type:
2830             if function.is_name and function.entry and function.entry.type:
2831                 result_type = function.entry.type
2832                 if result_type.is_extension_type:
2833                     return result_type
2834                 elif result_type.is_builtin_type:
2835                     if function.entry.name == 'float':
2836                         return PyrexTypes.c_double_type
2837                     elif function.entry.name in Builtin.types_that_construct_their_instance:
2838                         return result_type
2839         return py_object_type
2840
2841     def analyse_as_type(self, env):
2842         attr = self.function.as_cython_attribute()
2843         if attr == 'pointer':
2844             if len(self.args) != 1:
2845                 error(self.args.pos, "only one type allowed.")
2846             else:
2847                 type = self.args[0].analyse_as_type(env)
2848                 if not type:
2849                     error(self.args[0].pos, "Unknown type")
2850                 else:
2851                     return PyrexTypes.CPtrType(type)
2852
2853     def explicit_args_kwds(self):
2854         return self.args, None
2855
2856     def analyse_types(self, env):
2857         if self.analyse_as_type_constructor(env):
2858             return
2859         if self.analysed:
2860             return
2861         self.analysed = True
2862         function = self.function
2863         function.is_called = 1
2864         self.function.analyse_types(env)
2865         if function.is_attribute and function.entry and function.entry.is_cmethod:
2866             # Take ownership of the object from which the attribute
2867             # was obtained, because we need to pass it as 'self'.
2868             self.self = function.obj
2869             function.obj = CloneNode(self.self)
2870         func_type = self.function_type()
2871         if func_type.is_pyobject:
2872             self.arg_tuple = TupleNode(self.pos, args = self.args)
2873             self.arg_tuple.analyse_types(env)
2874             self.args = None
2875             if func_type is Builtin.type_type and function.is_name and \
2876                    function.entry and \
2877                    function.entry.is_builtin and \
2878                    function.entry.name in Builtin.types_that_construct_their_instance:
2879                 # calling a builtin type that returns a specific object type
2880                 if function.entry.name == 'float':
2881                     # the following will come true later on in a transform
2882                     self.type = PyrexTypes.c_double_type
2883                     self.result_ctype = PyrexTypes.c_double_type
2884                 else:
2885                     self.type = Builtin.builtin_types[function.entry.name]
2886                     self.result_ctype = py_object_type
2887                 self.may_return_none = False
2888             elif function.is_name and function.type_entry:
2889                 # We are calling an extension type constructor.  As
2890                 # long as we do not support __new__(), the result type
2891                 # is clear
2892                 self.type = function.type_entry.type
2893                 self.result_ctype = py_object_type
2894                 self.may_return_none = False
2895             else:
2896                 self.type = py_object_type
2897             self.is_temp = 1
2898         else:
2899             for arg in self.args:
2900                 arg.analyse_types(env)
2901             if self.self and func_type.args:
2902                 # Coerce 'self' to the type expected by the method.
2903                 self_arg = func_type.args[0]
2904                 if self_arg.not_none: # C methods must do the None test for self at *call* time
2905                     self.self = self.self.as_none_safe_node(
2906                         "'NoneType' object has no attribute '%s'" % self.function.entry.name,
2907                         'PyExc_AttributeError')
2908                 expected_type = self_arg.type
2909                 self.coerced_self = CloneNode(self.self).coerce_to(
2910                     expected_type, env)
2911                 # Insert coerced 'self' argument into argument list.
2912                 self.args.insert(0, self.coerced_self)
2913             self.analyse_c_function_call(env)
2914
2915     def function_type(self):
2916         # Return the type of the function being called, coercing a function
2917         # pointer to a function if necessary.
2918         func_type = self.function.type
2919         if func_type.is_ptr:
2920             func_type = func_type.base_type
2921         return func_type
2922
2923     def is_simple(self):
2924         # C function calls could be considered simple, but they may
2925         # have side-effects that may hit when multiple operations must
2926         # be effected in order, e.g. when constructing the argument
2927         # sequence for a function call or comparing values.
2928         return False
2929
2930     def analyse_c_function_call(self, env):
2931         if self.function.type is error_type:
2932             self.type = error_type
2933             return
2934         if self.function.type.is_cpp_class:
2935             overloaded_entry = self.function.type.scope.lookup("operator()")
2936             if overloaded_entry is None:
2937                 self.type = PyrexTypes.error_type
2938                 self.result_code = "<error>"
2939                 return
2940         elif hasattr(self.function, 'entry'):
2941             overloaded_entry = self.function.entry
2942         else:
2943             overloaded_entry = None
2944         if overloaded_entry:
2945             entry = PyrexTypes.best_match(self.args, overloaded_entry.all_alternatives(), self.pos)
2946             if not entry:
2947                 self.type = PyrexTypes.error_type
2948                 self.result_code = "<error>"
2949                 return
2950             self.function.entry = entry
2951             self.function.type = entry.type
2952             func_type = self.function_type()
2953         else:
2954             func_type = self.function_type()
2955             if not func_type.is_cfunction:
2956                 error(self.pos, "Calling non-function type '%s'" % func_type)
2957                 self.type = PyrexTypes.error_type
2958                 self.result_code = "<error>"
2959                 return
2960         # Check no. of args
2961         max_nargs = len(func_type.args)
2962         expected_nargs = max_nargs - func_type.optional_arg_count
2963         actual_nargs = len(self.args)
2964         if func_type.optional_arg_count and expected_nargs != actual_nargs:
2965             self.has_optional_args = 1
2966             self.is_temp = 1
2967         # Coerce arguments
2968         some_args_in_temps = False
2969         for i in xrange(min(max_nargs, actual_nargs)):
2970             formal_type = func_type.args[i].type
2971             arg = self.args[i].coerce_to(formal_type, env)
2972             if arg.is_temp:
2973                 if i > 0:
2974                     # first argument in temp doesn't impact subsequent arguments
2975                     some_args_in_temps = True
2976             elif arg.type.is_pyobject and not env.nogil:
2977                 if i == 0 and self.self is not None:
2978                     # a method's cloned "self" argument is ok
2979                     pass
2980                 elif arg.is_name and arg.entry and arg.entry.is_local and not arg.entry.in_closure:
2981                     # plain local variables are ok
2982                     pass
2983                 else:
2984                     # we do not safely own the argument's reference,
2985                     # but we must make sure it cannot be collected
2986                     # before we return from the function, so we create
2987                     # an owned temp reference to it
2988                     if i > 0: # first argument doesn't matter
2989                         some_args_in_temps = True
2990                     arg = arg.coerce_to_temp(env)
2991             self.args[i] = arg
2992         # handle additional varargs parameters
2993         for i in xrange(max_nargs, actual_nargs):
2994             arg = self.args[i]
2995             if arg.type.is_pyobject:
2996                 arg_ctype = arg.type.default_coerced_ctype()
2997                 if arg_ctype is None:
2998                     error(self.args[i].pos,
2999                           "Python object cannot be passed as a varargs parameter")
3000                 else:
3001                     self.args[i] = arg = arg.coerce_to(arg_ctype, env)
3002             if arg.is_temp and i > 0:
3003                 some_args_in_temps = True
3004         if some_args_in_temps:
3005             # if some args are temps and others are not, they may get
3006             # constructed in the wrong order (temps first) => make
3007             # sure they are either all temps or all not temps (except
3008             # for the last argument, which is evaluated last in any
3009             # case)
3010             for i in xrange(actual_nargs-1):
3011                 if i == 0 and self.self is not None:
3012                     continue # self is ok
3013                 arg = self.args[i]
3014                 if arg.is_name and arg.entry and (
3015                     (arg.entry.is_local and not arg.entry.in_closure)
3016                     or arg.entry.type.is_cfunction):
3017                     # local variables and C functions are safe
3018                     pass
3019                 elif env.nogil and arg.type.is_pyobject:
3020                     # can't copy a Python reference into a temp in nogil
3021                     # env (this is safe: a construction would fail in
3022                     # nogil anyway)
3023                     pass
3024                 else:
3025                     self.args[i] = arg.coerce_to_temp(env)
3026         # Calc result type and code fragment
3027         if isinstance(self.function, NewExprNode):
3028             self.type = PyrexTypes.CPtrType(self.function.class_type)
3029         else:
3030             self.type = func_type.return_type
3031         if self.type.is_pyobject:
3032             self.result_ctype = py_object_type
3033             self.is_temp = 1
3034         elif func_type.exception_value is not None \
3035                  or func_type.exception_check:
3036             self.is_temp = 1
3037         # Called in 'nogil' context?
3038         self.nogil = env.nogil
3039         if (self.nogil and
3040             func_type.exception_check and
3041             func_type.exception_check != '+'):
3042             env.use_utility_code(pyerr_occurred_withgil_utility_code)
3043         # C++ exception handler
3044         if func_type.exception_check == '+':
3045             if func_type.exception_value is None:
3046                 env.use_utility_code(cpp_exception_utility_code)
3047
3048     def calculate_result_code(self):
3049         return self.c_call_code()
3050
3051     def c_call_code(self):
3052         func_type = self.function_type()
3053         if self.type is PyrexTypes.error_type or not func_type.is_cfunction:
3054             return "<error>"
3055         formal_args = func_type.args
3056         arg_list_code = []
3057         args = list(zip(formal_args, self.args))
3058         max_nargs = len(func_type.args)
3059         expected_nargs = max_nargs - func_type.optional_arg_count
3060         actual_nargs = len(self.args)
3061         for formal_arg, actual_arg in args[:expected_nargs]:
3062                 arg_code = actual_arg.result_as(formal_arg.type)
3063                 arg_list_code.append(arg_code)
3064
3065         if func_type.is_overridable:
3066             arg_list_code.append(str(int(self.wrapper_call or self.function.entry.is_unbound_cmethod)))
3067
3068         if func_type.optional_arg_count:
3069             if expected_nargs == actual_nargs:
3070                 optional_args = 'NULL'
3071             else:
3072                 optional_args = "&%s" % self.opt_arg_struct
3073             arg_list_code.append(optional_args)
3074
3075         for actual_arg in self.args[len(formal_args):]:
3076             arg_list_code.append(actual_arg.result())
3077         result = "%s(%s)" % (self.function.result(),
3078             ', '.join(arg_list_code))
3079         return result
3080
3081     def generate_result_code(self, code):
3082         func_type = self.function_type()
3083         if func_type.is_pyobject:
3084             arg_code = self.arg_tuple.py_result()
3085             code.putln(
3086                 "%s = PyObject_Call(%s, %s, NULL); %s" % (
3087                     self.result(),
3088                     self.function.py_result(),
3089                     arg_code,
3090                     code.error_goto_if_null(self.result(), self.pos)))
3091             code.put_gotref(self.py_result())
3092         elif func_type.is_cfunction:
3093             if self.has_optional_args:
3094                 actual_nargs = len(self.args)
3095                 expected_nargs = len(func_type.args) - func_type.optional_arg_count
3096                 self.opt_arg_struct = code.funcstate.allocate_temp(
3097                     func_type.op_arg_struct.base_type, manage_ref=True)
3098                 code.putln("%s.%s = %s;" % (
3099                         self.opt_arg_struct,
3100                         Naming.pyrex_prefix + "n",
3101                         len(self.args) - expected_nargs))
3102                 args = list(zip(func_type.args, self.args))
3103                 for formal_arg, actual_arg in args[expected_nargs:actual_nargs]:
3104                     code.putln("%s.%s = %s;" % (
3105                             self.opt_arg_struct,
3106                             func_type.opt_arg_cname(formal_arg.name),
3107                             actual_arg.result_as(formal_arg.type)))
3108             exc_checks = []
3109             if self.type.is_pyobject and self.is_temp:
3110                 exc_checks.append("!%s" % self.result())
3111             else:
3112                 exc_val = func_type.exception_value
3113                 exc_check = func_type.exception_check
3114                 if exc_val is not None:
3115                     exc_checks.append("%s == %s" % (self.result(), exc_val))
3116                 if exc_check:
3117                     if self.nogil:
3118                         exc_checks.append("__Pyx_ErrOccurredWithGIL()")
3119                     else:
3120                         exc_checks.append("PyErr_Occurred()")
3121             if self.is_temp or exc_checks:
3122                 rhs = self.c_call_code()
3123                 if self.result():
3124                     lhs = "%s = " % self.result()
3125                     if self.is_temp and self.type.is_pyobject:
3126                         #return_type = self.type # func_type.return_type
3127                         #print "SimpleCallNode.generate_result_code: casting", rhs, \
3128                         #    "from", return_type, "to pyobject" ###
3129                         rhs = typecast(py_object_type, self.type, rhs)
3130                 else:
3131                     lhs = ""
3132                 if func_type.exception_check == '+':
3133                     if func_type.exception_value is None:
3134                         raise_py_exception = "__Pyx_CppExn2PyErr()"
3135                     elif func_type.exception_value.type.is_pyobject:
3136                         raise_py_exception = ' try { throw; } catch(const std::exception& exn) { PyErr_SetString(%s, exn.what()); } catch(...) { PyErr_SetNone(%s); }' % (
3137                             func_type.exception_value.entry.cname,
3138                             func_type.exception_value.entry.cname)
3139                     else:
3140                         raise_py_exception = '%s(); if (!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError , "Error converting c++ exception.")' % func_type.exception_value.entry.cname
3141                     if self.nogil:
3142                         raise_py_exception = 'Py_BLOCK_THREADS; %s; Py_UNBLOCK_THREADS' % raise_py_exception
3143                     code.putln(
3144                     "try {%s%s;} catch(...) {%s; %s}" % (
3145                         lhs,
3146                         rhs,
3147                         raise_py_exception,
3148                         code.error_goto(self.pos)))
3149                 else:
3150                     if exc_checks:
3151                         goto_error = code.error_goto_if(" && ".join(exc_checks), self.pos)
3152                     else:
3153                         goto_error = ""
3154                     code.putln("%s%s; %s" % (lhs, rhs, goto_error))
3155                 if self.type.is_pyobject and self.result():
3156                     code.put_gotref(self.py_result())
3157             if self.has_optional_args:
3158                 code.funcstate.release_temp(self.opt_arg_struct)
3159
3160
3161 class PythonCapiFunctionNode(ExprNode):
3162     subexprs = []
3163     def __init__(self, pos, py_name, cname, func_type, utility_code = None):
3164         self.pos = pos
3165         self.name = py_name
3166         self.cname = cname
3167         self.type = func_type
3168         self.utility_code = utility_code
3169
3170     def analyse_types(self, env):
3171         pass
3172
3173     def generate_result_code(self, code):
3174         if self.utility_code:
3175             code.globalstate.use_utility_code(self.utility_code)
3176
3177     def calculate_result_code(self):
3178         return self.cname
3179
3180 class PythonCapiCallNode(SimpleCallNode):
3181     # Python C-API Function call (only created in transforms)
3182
3183     # By default, we assume that the call never returns None, as this
3184     # is true for most C-API functions in CPython.  If this does not
3185     # apply to a call, set the following to True (or None to inherit
3186     # the default behaviour).
3187     may_return_none = False
3188
3189     def __init__(self, pos, function_name, func_type,
3190                  utility_code = None, py_name=None, **kwargs):
3191         self.type = func_type.return_type
3192         self.result_ctype = self.type
3193         self.function = PythonCapiFunctionNode(
3194             pos, py_name, function_name, func_type,
3195             utility_code = utility_code)
3196         # call this last so that we can override the constructed
3197         # attributes above with explicit keyword arguments if required
3198         SimpleCallNode.__init__(self, pos, **kwargs)
3199
3200
3201 class GeneralCallNode(CallNode):
3202     #  General Python function call, including keyword,
3203     #  * and ** arguments.
3204     #
3205     #  function         ExprNode
3206     #  positional_args  ExprNode          Tuple of positional arguments
3207     #  keyword_args     ExprNode or None  Dict of keyword arguments
3208     #  starstar_arg     ExprNode or None  Dict of extra keyword args
3209
3210     type = py_object_type
3211
3212     subexprs = ['function', 'positional_args', 'keyword_args', 'starstar_arg']
3213
3214     nogil_check = Node.gil_error
3215
3216     def compile_time_value(self, denv):
3217         function = self.function.compile_time_value(denv)
3218         positional_args = self.positional_args.compile_time_value(denv)
3219         keyword_args = self.keyword_args.compile_time_value(denv)
3220         starstar_arg = self.starstar_arg.compile_time_value(denv)
3221         try:
3222             keyword_args.update(starstar_arg)
3223             return function(*positional_args, **keyword_args)
3224         except Exception, e:
3225             self.compile_time_value_error(e)
3226
3227     def explicit_args_kwds(self):
3228         if self.starstar_arg or not isinstance(self.positional_args, TupleNode):
3229             raise CompileError(self.pos,
3230                 'Compile-time keyword arguments must be explicit.')
3231         return self.positional_args.args, self.keyword_args
3232
3233     def analyse_types(self, env):
3234         if self.analyse_as_type_constructor(env):
3235             return
3236         self.function.analyse_types(env)
3237         self.positional_args.analyse_types(env)
3238         if self.keyword_args:
3239             self.keyword_args.analyse_types(env)
3240         if self.starstar_arg:
3241             self.starstar_arg.analyse_types(env)
3242         if not self.function.type.is_pyobject:
3243             if self.function.type.is_error:
3244                 self.type = error_type
3245                 return
3246             if hasattr(self.function, 'entry') and not self.function.entry.as_variable:
3247                 error(self.pos, "Keyword and starred arguments not allowed in cdef functions.")
3248             else:
3249                 self.function = self.function.coerce_to_pyobject(env)
3250         self.positional_args = \
3251             self.positional_args.coerce_to_pyobject(env)
3252         if self.starstar_arg:
3253             self.starstar_arg = \
3254                 self.starstar_arg.coerce_to_pyobject(env)
3255         function = self.function
3256         if function.is_name and function.type_entry:
3257             # We are calling an extension type constructor.  As long
3258             # as we do not support __new__(), the result type is clear
3259             self.type = function.type_entry.type
3260             self.result_ctype = py_object_type
3261             self.may_return_none = False
3262         else:
3263             self.type = py_object_type
3264         self.is_temp = 1
3265
3266     def generate_result_code(self, code):
3267         if self.type.is_error: return
3268         kwargs_call_function = "PyEval_CallObjectWithKeywords"
3269         if self.keyword_args and self.starstar_arg:
3270             code.put_error_if_neg(self.pos,
3271                 "PyDict_Update(%s, %s)" % (
3272                     self.keyword_args.py_result(),
3273                     self.starstar_arg.py_result()))
3274             keyword_code = self.keyword_args.py_result()
3275         elif self.keyword_args:
3276             keyword_code = self.keyword_args.py_result()
3277         elif self.starstar_arg:
3278             keyword_code = self.starstar_arg.py_result()
3279             if self.starstar_arg.type is not Builtin.dict_type:
3280                 # CPython supports calling functions with non-dicts, so do we
3281                 code.globalstate.use_utility_code(kwargs_call_utility_code)
3282                 kwargs_call_function = "__Pyx_PyEval_CallObjectWithKeywords"
3283         else:
3284             keyword_code = None
3285         if not keyword_code:
3286             call_code = "PyObject_Call(%s, %s, NULL)" % (
3287                 self.function.py_result(),
3288                 self.positional_args.py_result())
3289         else:
3290             call_code = "%s(%s, %s, %s)" % (
3291                 kwargs_call_function,
3292                 self.function.py_result(),
3293                 self.positional_args.py_result(),
3294                 keyword_code)
3295         code.putln(
3296             "%s = %s; %s" % (
3297                 self.result(),
3298                 call_code,
3299                 code.error_goto_if_null(self.result(), self.pos)))
3300         code.put_gotref(self.py_result())
3301
3302
3303 class AsTupleNode(ExprNode):
3304     #  Convert argument to tuple. Used for normalising
3305     #  the * argument of a function call.
3306     #
3307     #  arg    ExprNode
3308
3309     subexprs = ['arg']
3310
3311     def calculate_constant_result(self):
3312         self.constant_result = tuple(self.base.constant_result)
3313
3314     def compile_time_value(self, denv):
3315         arg = self.arg.compile_time_value(denv)
3316         try:
3317             return tuple(arg)
3318         except Exception, e:
3319             self.compile_time_value_error(e)
3320
3321     def analyse_types(self, env):
3322         self.arg.analyse_types(env)
3323         self.arg = self.arg.coerce_to_pyobject(env)
3324         self.type = tuple_type
3325         self.is_temp = 1
3326
3327     def may_be_none(self):
3328         return False
3329
3330     nogil_check = Node.gil_error
3331     gil_message = "Constructing Python tuple"
3332
3333     def generate_result_code(self, code):
3334         code.putln(
3335             "%s = PySequence_Tuple(%s); %s" % (
3336                 self.result(),
3337                 self.arg.py_result(),
3338                 code.error_goto_if_null(self.result(), self.pos)))
3339         code.put_gotref(self.py_result())
3340
3341
3342 class AttributeNode(ExprNode):
3343     #  obj.attribute
3344     #
3345     #  obj          ExprNode
3346     #  attribute    string
3347     #  needs_none_check boolean        Used if obj is an extension type.
3348     #                                  If set to True, it is known that the type is not None.
3349     #
3350     #  Used internally:
3351     #
3352     #  is_py_attr           boolean   Is a Python getattr operation
3353     #  member               string    C name of struct member
3354     #  is_called            boolean   Function call is being done on result
3355     #  entry                Entry     Symbol table entry of attribute
3356
3357     is_attribute = 1
3358     subexprs = ['obj']
3359
3360     type = PyrexTypes.error_type
3361     entry = None
3362     is_called = 0
3363     needs_none_check = True
3364
3365     def as_cython_attribute(self):
3366         if isinstance(self.obj, NameNode) and self.obj.is_cython_module:
3367             return self.attribute
3368         cy = self.obj.as_cython_attribute()
3369         if cy:
3370             return "%s.%s" % (cy, self.attribute)
3371
3372     def coerce_to(self, dst_type, env):
3373         #  If coercing to a generic pyobject and this is a cpdef function
3374         #  we can create the corresponding attribute
3375         if dst_type is py_object_type:
3376             entry = self.entry
3377             if entry and entry.is_cfunction and entry.as_variable:
3378                 # must be a cpdef function
3379                 self.is_temp = 1
3380                 self.entry = entry.as_variable
3381                 self.analyse_as_python_attribute(env)
3382                 return self
3383         return ExprNode.coerce_to(self, dst_type, env)
3384
3385     def calculate_constant_result(self):
3386         attr = self.attribute
3387         if attr.startswith("__") and attr.endswith("__"):
3388             return
3389         self.constant_result = getattr(self.obj.constant_result, attr)
3390
3391     def compile_time_value(self, denv):
3392         attr = self.attribute
3393         if attr.startswith("__") and attr.endswith("__"):
3394             error(self.pos,
3395                   "Invalid attribute name '%s' in compile-time expression" % attr)
3396             return None
3397         obj = self.obj.compile_time_value(denv)
3398         try:
3399             return getattr(obj, attr)
3400         except Exception, e:
3401             self.compile_time_value_error(e)
3402
3403     def type_dependencies(self, env):
3404         return self.obj.type_dependencies(env)
3405
3406     def infer_type(self, env):
3407         if self.analyse_as_cimported_attribute(env, 0):
3408             return self.entry.type
3409         elif self.analyse_as_unbound_cmethod(env):
3410             return self.entry.type
3411         else:
3412             obj_type = self.obj.infer_type(env)
3413             self.analyse_attribute(env, obj_type = obj_type)
3414             if obj_type.is_builtin_type and self.type.is_cfunction:
3415                 # special case: C-API replacements for C methods of
3416                 # builtin types cannot be inferred as C functions as
3417                 # that would prevent their use as bound methods
3418                 self.type = py_object_type
3419                 return py_object_type
3420             return self.type
3421
3422     def analyse_target_declaration(self, env):
3423         pass
3424
3425     def analyse_target_types(self, env):
3426         self.analyse_types(env, target = 1)
3427
3428     def analyse_types(self, env, target = 0):
3429         if self.analyse_as_cimported_attribute(env, target):
3430             return
3431         if not target and self.analyse_as_unbound_cmethod(env):
3432             return
3433         self.analyse_as_ordinary_attribute(env, target)
3434
3435     def analyse_as_cimported_attribute(self, env, target):
3436         # Try to interpret this as a reference to an imported
3437         # C const, type, var or function. If successful, mutates
3438         # this node into a NameNode and returns 1, otherwise
3439         # returns 0.
3440         module_scope = self.obj.analyse_as_module(env)
3441         if module_scope:
3442             entry = module_scope.lookup_here(self.attribute)
3443             if entry and (
3444                 entry.is_cglobal or entry.is_cfunction
3445                 or entry.is_type or entry.is_const):
3446                     self.mutate_into_name_node(env, entry, target)
3447                     return 1
3448         return 0
3449
3450     def analyse_as_unbound_cmethod(self, env):
3451         # Try to interpret this as a reference to an unbound
3452         # C method of an extension type. If successful, mutates
3453         # this node into a NameNode and returns 1, otherwise
3454         # returns 0.
3455         type = self.obj.analyse_as_extension_type(env)
3456         if type:
3457             entry = type.scope.lookup_here(self.attribute)
3458             if entry and entry.is_cmethod:
3459                 # Create a temporary entry describing the C method
3460                 # as an ordinary function.
3461                 ubcm_entry = Symtab.Entry(entry.name,
3462                     "%s->%s" % (type.vtabptr_cname, entry.cname),
3463                     entry.type)
3464                 ubcm_entry.is_cfunction = 1
3465                 ubcm_entry.func_cname = entry.func_cname
3466                 ubcm_entry.is_unbound_cmethod = 1
3467                 self.mutate_into_name_node(env, ubcm_entry, None)
3468                 return 1
3469         return 0
3470
3471     def analyse_as_type(self, env):
3472         module_scope = self.obj.analyse_as_module(env)
3473         if module_scope:
3474             return module_scope.lookup_type(self.attribute)
3475         if not isinstance(self.obj, (UnicodeNode, StringNode, BytesNode)):
3476             base_type = self.obj.analyse_as_type(env)
3477             if base_type and hasattr(base_type, 'scope') and base_type.scope is not None:
3478                 return base_type.scope.lookup_type(self.attribute)
3479         return None
3480
3481     def analyse_as_extension_type(self, env):
3482         # Try to interpret this as a reference to an extension type
3483         # in a cimported module. Returns the extension type, or None.
3484         module_scope = self.obj.analyse_as_module(env)
3485         if module_scope:
3486             entry = module_scope.lookup_here(self.attribute)
3487             if entry and entry.is_type and entry.type.is_extension_type:
3488                 return entry.type
3489         return None
3490
3491     def analyse_as_module(self, env):
3492         # Try to interpret this as a reference to a cimported module
3493         # in another cimported module. Returns the module scope, or None.
3494         module_scope = self.obj.analyse_as_module(env)
3495         if module_scope:
3496             entry = module_scope.lookup_here(self.attribute)
3497             if entry and entry.as_module:
3498                 return entry.as_module
3499         return None
3500
3501     def mutate_into_name_node(self, env, entry, target):
3502         # Mutate this node into a NameNode and complete the
3503         # analyse_types phase.
3504         self.__class__ = NameNode
3505         self.name = self.attribute
3506         self.entry = entry
3507         del self.obj
3508         del self.attribute
3509         if target:
3510             NameNode.analyse_target_types(self, env)
3511         else:
3512             NameNode.analyse_rvalue_entry(self, env)
3513
3514     def analyse_as_ordinary_attribute(self, env, target):
3515         self.obj.analyse_types(env)
3516         self.analyse_attribute(env)
3517         if self.entry and self.entry.is_cmethod and not self.is_called:
3518 #            error(self.pos, "C method can only be called")
3519             pass
3520         ## Reference to C array turns into pointer to first element.
3521         #while self.type.is_array:
3522         #    self.type = self.type.element_ptr_type()
3523         if self.is_py_attr:
3524             if not target:
3525                 self.is_temp = 1
3526                 self.result_ctype = py_object_type
3527         elif target and self.obj.type.is_builtin_type:
3528             error(self.pos, "Assignment to an immutable object field")
3529
3530     def analyse_attribute(self, env, obj_type = None):
3531         # Look up attribute and set self.type and self.member.
3532         self.is_py_attr = 0
3533         self.member = self.attribute
3534         if obj_type is None:
3535             if self.obj.type.is_string:
3536                 self.obj = self.obj.coerce_to_pyobject(env)
3537             obj_type = self.obj.type
3538         else:
3539             if obj_type.is_string:
3540                 obj_type = py_object_type
3541         if obj_type.is_ptr or obj_type.is_array:
3542             obj_type = obj_type.base_type
3543             self.op = "->"
3544         elif obj_type.is_extension_type or obj_type.is_builtin_type:
3545             self.op = "->"
3546         else:
3547             self.op = "."
3548         if obj_type.has_attributes:
3549             entry = None
3550             if obj_type.attributes_known():
3551                 entry = obj_type.scope.lookup_here(self.attribute)
3552                 if entry and entry.is_member:
3553                     entry = None
3554             else:
3555                 error(self.pos,
3556                     "Cannot select attribute of incomplete type '%s'"
3557                     % obj_type)
3558                 self.type = PyrexTypes.error_type
3559                 return
3560             self.entry = entry
3561             if entry:
3562                 if obj_type.is_extension_type and entry.name == "__weakref__":
3563                     error(self.pos, "Illegal use of special attribute __weakref__")
3564                 # methods need the normal attribute lookup
3565                 # because they do not have struct entries
3566                 if entry.is_variable or entry.is_cmethod:
3567                     self.type = entry.type
3568                     self.member = entry.cname
3569                     return
3570                 else:
3571                     # If it's not a variable or C method, it must be a Python
3572                     # method of an extension type, so we treat it like a Python
3573                     # attribute.
3574                     pass
3575         # If we get here, the base object is not a struct/union/extension
3576         # type, or it is an extension type and the attribute is either not
3577         # declared or is declared as a Python method. Treat it as a Python
3578         # attribute reference.
3579         self.analyse_as_python_attribute(env, obj_type)
3580
3581     def analyse_as_python_attribute(self, env, obj_type = None):
3582         if obj_type is None:
3583             obj_type = self.obj.type
3584         self.member = self.attribute
3585         self.type = py_object_type
3586         self.is_py_attr = 1
3587         if not obj_type.is_pyobject and not obj_type.is_error:
3588             if obj_type.can_coerce_to_pyobject(env):
3589                 self.obj = self.obj.coerce_to_pyobject(env)
3590             else:
3591                 error(self.pos,
3592                       "Object of type '%s' has no attribute '%s'" %
3593                       (obj_type, self.attribute))
3594
3595     def nogil_check(self, env):
3596         if self.is_py_attr:
3597             self.gil_error()
3598
3599     gil_message = "Accessing Python attribute"
3600
3601     def is_simple(self):
3602         if self.obj:
3603             return self.result_in_temp() or self.obj.is_simple()
3604         else:
3605             return NameNode.is_simple(self)
3606
3607     def is_lvalue(self):
3608         if self.obj:
3609             return 1
3610         else:
3611             return NameNode.is_lvalue(self)
3612
3613     def is_ephemeral(self):
3614         if self.obj:
3615             return self.obj.is_ephemeral()
3616         else:
3617             return NameNode.is_ephemeral(self)
3618
3619     def calculate_result_code(self):
3620         #print "AttributeNode.calculate_result_code:", self.member ###
3621         #print "...obj node =", self.obj, "code", self.obj.result() ###
3622         #print "...obj type", self.obj.type, "ctype", self.obj.ctype() ###
3623         obj = self.obj
3624         obj_code = obj.result_as(obj.type)
3625         #print "...obj_code =", obj_code ###
3626         if self.entry and self.entry.is_cmethod:
3627             if obj.type.is_extension_type:
3628                 return "((struct %s *)%s%s%s)->%s" % (
3629                     obj.type.vtabstruct_cname, obj_code, self.op,
3630                     obj.type.vtabslot_cname, self.member)
3631             else:
3632                 return self.member
3633         elif obj.type.is_complex:
3634             return "__Pyx_C%s(%s)" % (self.member.upper(), obj_code)
3635         else:
3636             if obj.type.is_builtin_type and self.entry and self.entry.is_variable:
3637                 # accessing a field of a builtin type, need to cast better than result_as() does
3638                 obj_code = obj.type.cast_code(obj.result(), to_object_struct = True)
3639             return "%s%s%s" % (obj_code, self.op, self.member)
3640
3641     def generate_result_code(self, code):
3642         interned_attr_cname = code.intern_identifier(self.attribute)
3643         if self.is_py_attr:
3644             code.putln(
3645                 '%s = PyObject_GetAttr(%s, %s); %s' % (
3646                     self.result(),
3647                     self.obj.py_result(),
3648                     interned_attr_cname,
3649                     code.error_goto_if_null(self.result(), self.pos)))
3650             code.put_gotref(self.py_result())
3651         else:
3652             # result_code contains what is needed, but we may need to insert
3653             # a check and raise an exception
3654             if (self.obj.type.is_extension_type
3655                   and self.needs_none_check
3656                   and code.globalstate.directives['nonecheck']):
3657                 self.put_nonecheck(code)
3658
3659     def generate_assignment_code(self, rhs, code):
3660         interned_attr_cname = code.intern_identifier(self.attribute)
3661         self.obj.generate_evaluation_code(code)
3662         if self.is_py_attr:
3663             code.put_error_if_neg(self.pos,
3664                 'PyObject_SetAttr(%s, %s, %s)' % (
3665                     self.obj.py_result(),
3666                     interned_attr_cname,
3667                     rhs.py_result()))
3668             rhs.generate_disposal_code(code)
3669             rhs.free_temps(code)
3670         elif self.obj.type.is_complex:
3671             code.putln("__Pyx_SET_C%s(%s, %s);" % (
3672                 self.member.upper(),
3673                 self.obj.result_as(self.obj.type),
3674                 rhs.result_as(self.ctype())))
3675         else:
3676             if (self.obj.type.is_extension_type
3677                   and self.needs_none_check
3678                   and code.globalstate.directives['nonecheck']):
3679                 self.put_nonecheck(code)
3680
3681             select_code = self.result()
3682             if self.type.is_pyobject and self.use_managed_ref:
3683                 rhs.make_owned_reference(code)
3684                 code.put_giveref(rhs.py_result())
3685                 code.put_gotref(select_code)
3686                 code.put_decref(select_code, self.ctype())
3687             code.putln(
3688                 "%s = %s;" % (
3689                     select_code,
3690                     rhs.result_as(self.ctype())))
3691                     #rhs.result()))
3692             rhs.generate_post_assignment_code(code)
3693             rhs.free_temps(code)
3694         self.obj.generate_disposal_code(code)
3695         self.obj.free_temps(code)
3696
3697     def generate_deletion_code(self, code):
3698         interned_attr_cname = code.intern_identifier(self.attribute)
3699         self.obj.generate_evaluation_code(code)
3700         if self.is_py_attr or (isinstance(self.entry.scope, Symtab.PropertyScope)
3701                                and u'__del__' in self.entry.scope.entries):
3702             code.put_error_if_neg(self.pos,
3703                 'PyObject_DelAttr(%s, %s)' % (
3704                     self.obj.py_result(),
3705                     interned_attr_cname))
3706         else:
3707             error(self.pos, "Cannot delete C attribute of extension type")
3708         self.obj.generate_disposal_code(code)
3709         self.obj.free_temps(code)
3710
3711     def annotate(self, code):
3712         if self.is_py_attr:
3713             code.annotate(self.pos, AnnotationItem('py_attr', 'python attribute', size=len(self.attribute)))
3714         else:
3715             code.annotate(self.pos, AnnotationItem('c_attr', 'c attribute', size=len(self.attribute)))
3716
3717     def put_nonecheck(self, code):
3718         code.globalstate.use_utility_code(raise_noneattr_error_utility_code)
3719         code.putln("if (%s) {" % code.unlikely("%s == Py_None") % self.obj.result_as(PyrexTypes.py_object_type))
3720         code.putln("__Pyx_RaiseNoneAttributeError(\"%s\");" % self.attribute)
3721         code.putln(code.error_goto(self.pos))
3722         code.putln("}")
3723
3724
3725 #-------------------------------------------------------------------
3726 #
3727 #  Constructor nodes
3728 #
3729 #-------------------------------------------------------------------
3730
3731 class StarredTargetNode(ExprNode):
3732     #  A starred expression like "*a"
3733     #
3734     #  This is only allowed in sequence assignment targets such as
3735     #
3736     #      a, *b = (1,2,3,4)    =>     a = 1 ; b = [2,3,4]
3737     #
3738     #  and will be removed during type analysis (or generate an error
3739     #  if it's found at unexpected places).
3740     #
3741     #  target          ExprNode
3742
3743     subexprs = ['target']
3744     is_starred = 1
3745     type = py_object_type
3746     is_temp = 1
3747
3748     def __init__(self, pos, target):
3749         self.pos = pos
3750         self.target = target
3751
3752     def analyse_declarations(self, env):
3753         error(self.pos, "can use starred expression only as assignment target")
3754         self.target.analyse_declarations(env)
3755
3756     def analyse_types(self, env):
3757         error(self.pos, "can use starred expression only as assignment target")
3758         self.target.analyse_types(env)
3759         self.type = self.target.type
3760
3761     def analyse_target_declaration(self, env):
3762         self.target.analyse_target_declaration(env)
3763
3764     def analyse_target_types(self, env):
3765         self.target.analyse_target_types(env)
3766         self.type = self.target.type
3767
3768     def calculate_result_code(self):
3769         return ""
3770
3771     def generate_result_code(self, code):
3772         pass
3773
3774
3775 class SequenceNode(ExprNode):
3776     #  Base class for list and tuple constructor nodes.
3777     #  Contains common code for performing sequence unpacking.
3778     #
3779     #  args                    [ExprNode]
3780     #  iterator                ExprNode
3781     #  unpacked_items          [ExprNode] or None
3782     #  coerced_unpacked_items  [ExprNode] or None
3783
3784     subexprs = ['args']
3785
3786     is_sequence_constructor = 1
3787     unpacked_items = None
3788
3789     def compile_time_value_list(self, denv):
3790         return [arg.compile_time_value(denv) for arg in self.args]
3791
3792     def replace_starred_target_node(self):
3793         # replace a starred node in the targets by the contained expression
3794         self.starred_assignment = False
3795         args = []
3796         for arg in self.args:
3797             if arg.is_starred:
3798                 if self.starred_assignment:
3799                     error(arg.pos, "more than 1 starred expression in assignment")
3800                 self.starred_assignment = True
3801                 arg = arg.target
3802                 arg.is_starred = True
3803             args.append(arg)
3804         self.args = args
3805
3806     def analyse_target_declaration(self, env):
3807         self.replace_starred_target_node()
3808         for arg in self.args:
3809             arg.analyse_target_declaration(env)
3810
3811     def analyse_types(self, env, skip_children=False):
3812         for i in range(len(self.args)):
3813             arg = self.args[i]
3814             if not skip_children: arg.analyse_types(env)
3815             self.args[i] = arg.coerce_to_pyobject(env)
3816         self.is_temp = 1
3817         # not setting self.type here, subtypes do this
3818
3819     def may_be_none(self):
3820         return False
3821
3822     def analyse_target_types(self, env):
3823         self.iterator = PyTempNode(self.pos, env)
3824         self.unpacked_items = []
3825         self.coerced_unpacked_items = []
3826         for arg in self.args:
3827             arg.analyse_target_types(env)
3828             if arg.is_starred:
3829                 if not arg.type.assignable_from(Builtin.list_type):
3830                     error(arg.pos,
3831                           "starred target must have Python object (list) type")
3832                 if arg.type is py_object_type:
3833                     arg.type = Builtin.list_type
3834             unpacked_item = PyTempNode(self.pos, env)
3835             coerced_unpacked_item = unpacked_item.coerce_to(arg.type, env)
3836             self.unpacked_items.append(unpacked_item)
3837             self.coerced_unpacked_items.append(coerced_unpacked_item)
3838         self.type = py_object_type
3839
3840     def generate_result_code(self, code):
3841         self.generate_operation_code(code)
3842
3843     def generate_assignment_code(self, rhs, code):
3844         if self.starred_assignment:
3845             self.generate_starred_assignment_code(rhs, code)
3846         else:
3847             self.generate_parallel_assignment_code(rhs, code)
3848
3849         for item in self.unpacked_items:
3850             item.release(code)
3851         rhs.free_temps(code)
3852
3853     def generate_parallel_assignment_code(self, rhs, code):
3854         # Need to work around the fact that generate_evaluation_code
3855         # allocates the temps in a rather hacky way -- the assignment
3856         # is evaluated twice, within each if-block.
3857
3858         if rhs.type is tuple_type:
3859             tuple_check = "likely(%s != Py_None)"
3860         else:
3861             tuple_check = "PyTuple_CheckExact(%s)"
3862         code.putln(
3863             "if (%s && likely(PyTuple_GET_SIZE(%s) == %s)) {" % (
3864                 tuple_check % rhs.py_result(),
3865                 rhs.py_result(),
3866                 len(self.args)))
3867         code.putln("PyObject* tuple = %s;" % rhs.py_result())
3868         for item in self.unpacked_items:
3869             item.allocate(code)
3870         for i in range(len(self.args)):
3871             item = self.unpacked_items[i]
3872             code.put(
3873                 "%s = PyTuple_GET_ITEM(tuple, %s); " % (
3874                     item.result(),
3875                     i))
3876             code.put_incref(item.result(), item.ctype())
3877             value_node = self.coerced_unpacked_items[i]
3878             value_node.generate_evaluation_code(code)
3879         rhs.generate_disposal_code(code)
3880
3881         for i in range(len(self.args)):
3882             self.args[i].generate_assignment_code(
3883                 self.coerced_unpacked_items[i], code)
3884
3885         code.putln("} else {")
3886
3887         if rhs.type is tuple_type:
3888             code.globalstate.use_utility_code(tuple_unpacking_error_code)
3889             code.putln("__Pyx_UnpackTupleError(%s, %s);" % (
3890                         rhs.py_result(), len(self.args)))
3891             code.putln(code.error_goto(self.pos))
3892         else:
3893             code.globalstate.use_utility_code(unpacking_utility_code)
3894
3895             self.iterator.allocate(code)
3896             code.putln(
3897                 "%s = PyObject_GetIter(%s); %s" % (
3898                     self.iterator.result(),
3899                     rhs.py_result(),
3900                     code.error_goto_if_null(self.iterator.result(), self.pos)))
3901             code.put_gotref(self.iterator.py_result())
3902             rhs.generate_disposal_code(code)
3903             for i in range(len(self.args)):
3904                 item = self.unpacked_items[i]
3905                 unpack_code = "__Pyx_UnpackItem(%s, %d)" % (
3906                     self.iterator.py_result(), i)
3907                 code.putln(
3908                     "%s = %s; %s" % (
3909                         item.result(),
3910                         typecast(item.ctype(), py_object_type, unpack_code),
3911                         code.error_goto_if_null(item.result(), self.pos)))
3912                 code.put_gotref(item.py_result())
3913                 value_node = self.coerced_unpacked_items[i]
3914                 value_node.generate_evaluation_code(code)
3915             code.put_error_if_neg(self.pos, "__Pyx_EndUnpack(%s, %d)" % (
3916                 self.iterator.py_result(),
3917                 len(self.args)))
3918             if debug_disposal_code:
3919                 print("UnpackNode.generate_assignment_code:")
3920                 print("...generating disposal code for %s" % self.iterator)
3921             self.iterator.generate_disposal_code(code)
3922             self.iterator.free_temps(code)
3923             self.iterator.release(code)
3924
3925             for i in range(len(self.args)):
3926                 self.args[i].generate_assignment_code(
3927                     self.coerced_unpacked_items[i], code)
3928
3929         code.putln("}")
3930
3931     def generate_starred_assignment_code(self, rhs, code):
3932         code.globalstate.use_utility_code(unpacking_utility_code)
3933
3934         for i, arg in enumerate(self.args):
3935             if arg.is_starred:
3936                 starred_target = self.unpacked_items[i]
3937                 fixed_args_left  = self.args[:i]
3938                 fixed_args_right = self.args[i+1:]
3939                 break
3940
3941         self.iterator.allocate(code)
3942         code.putln(
3943             "%s = PyObject_GetIter(%s); %s" % (
3944                 self.iterator.result(),
3945                 rhs.py_result(),
3946                 code.error_goto_if_null(self.iterator.result(), self.pos)))
3947         code.put_gotref(self.iterator.py_result())
3948         rhs.generate_disposal_code(code)
3949
3950         for item in self.unpacked_items:
3951             item.allocate(code)
3952         for i in range(len(fixed_args_left)):
3953             item = self.unpacked_items[i]
3954             unpack_code = "__Pyx_UnpackItem(%s, %d)" % (
3955                 self.iterator.py_result(), i)
3956             code.putln(
3957                 "%s = %s; %s" % (
3958                     item.result(),
3959                     typecast(item.ctype(), py_object_type, unpack_code),
3960                     code.error_goto_if_null(item.result(), self.pos)))
3961             code.put_gotref(item.py_result())
3962             value_node = self.coerced_unpacked_items[i]
3963             value_node.generate_evaluation_code(code)
3964
3965         target_list = starred_target.result()
3966         code.putln("%s = PySequence_List(%s); %s" % (
3967             target_list, self.iterator.py_result(),
3968             code.error_goto_if_null(target_list, self.pos)))
3969         code.put_gotref(target_list)
3970         if fixed_args_right:
3971             code.globalstate.use_utility_code(raise_need_more_values_to_unpack)
3972             unpacked_right_args = self.unpacked_items[-len(fixed_args_right):]
3973             code.putln("if (unlikely(PyList_GET_SIZE(%s) < %d)) {" % (
3974                 (target_list, len(unpacked_right_args))))
3975             code.put("__Pyx_RaiseNeedMoreValuesError(%d+PyList_GET_SIZE(%s)); %s" % (
3976                      len(fixed_args_left), target_list,
3977                      code.error_goto(self.pos)))
3978             code.putln('}')
3979             for i, (arg, coerced_arg) in enumerate(zip(unpacked_right_args[::-1],
3980                                                        self.coerced_unpacked_items[::-1])):
3981                 code.putln(
3982                     "%s = PyList_GET_ITEM(%s, PyList_GET_SIZE(%s)-1); " % (
3983                         arg.py_result(),
3984                         target_list, target_list))
3985                 # resize the list the hard way
3986                 code.putln("((PyVarObject*)%s)->ob_size--;" % target_list)
3987                 code.put_gotref(arg.py_result())
3988                 coerced_arg.generate_evaluation_code(code)
3989
3990         self.iterator.generate_disposal_code(code)
3991         self.iterator.free_temps(code)
3992         self.iterator.release(code)
3993
3994         for i in range(len(self.args)):
3995             self.args[i].generate_assignment_code(
3996                 self.coerced_unpacked_items[i], code)
3997
3998     def annotate(self, code):
3999         for arg in self.args:
4000             arg.annotate(code)
4001         if self.unpacked_items:
4002             for arg in self.unpacked_items:
4003                 arg.annotate(code)
4004             for arg in self.coerced_unpacked_items:
4005                 arg.annotate(code)
4006
4007
4008 class TupleNode(SequenceNode):
4009     #  Tuple constructor.
4010
4011     type = tuple_type
4012
4013     gil_message = "Constructing Python tuple"
4014
4015     def analyse_types(self, env, skip_children=False):
4016         if len(self.args) == 0:
4017             self.is_temp = 0
4018             self.is_literal = 1
4019         else:
4020             SequenceNode.analyse_types(self, env, skip_children)
4021             for child in self.args:
4022                 if not child.is_literal:
4023                     break
4024             else:
4025                 self.is_temp = 0
4026                 self.is_literal = 1
4027
4028     def is_simple(self):
4029         # either temp or constant => always simple
4030         return True
4031
4032     def calculate_result_code(self):
4033         if len(self.args) > 0:
4034             return self.result_code
4035         else:
4036             return Naming.empty_tuple
4037
4038     def calculate_constant_result(self):
4039         self.constant_result = tuple([
4040                 arg.constant_result for arg in self.args])
4041
4042     def compile_time_value(self, denv):
4043         values = self.compile_time_value_list(denv)
4044         try:
4045             return tuple(values)
4046         except Exception, e:
4047             self.compile_time_value_error(e)
4048
4049     def generate_operation_code(self, code):
4050         if len(self.args) == 0:
4051             # result_code is Naming.empty_tuple
4052             return
4053         if self.is_literal:
4054             # non-empty cached tuple => result is global constant,
4055             # creation code goes into separate code writer
4056             self.result_code = code.get_py_const(py_object_type, 'tuple_', cleanup_level=2)
4057             code = code.get_cached_constants_writer()
4058             code.mark_pos(self.pos)
4059
4060         code.putln(
4061             "%s = PyTuple_New(%s); %s" % (
4062                 self.result(),
4063                 len(self.args),
4064                 code.error_goto_if_null(self.result(), self.pos)))
4065         code.put_gotref(self.py_result())
4066         for i in range(len(self.args)):
4067             arg = self.args[i]
4068             if not arg.result_in_temp():
4069                 code.put_incref(arg.result(), arg.ctype())
4070             code.putln(
4071                 "PyTuple_SET_ITEM(%s, %s, %s);" % (
4072                     self.result(),
4073                     i,
4074                     arg.py_result()))
4075             code.put_giveref(arg.py_result())
4076         if self.is_literal:
4077             code.put_giveref(self.py_result())
4078
4079     def generate_subexpr_disposal_code(self, code):
4080         # We call generate_post_assignment_code here instead
4081         # of generate_disposal_code, because values were stored
4082         # in the tuple using a reference-stealing operation.
4083         for arg in self.args:
4084             arg.generate_post_assignment_code(code)
4085             # Should NOT call free_temps -- this is invoked by the default
4086             # generate_evaluation_code which will do that.
4087
4088
4089 class ListNode(SequenceNode):
4090     #  List constructor.
4091
4092     # obj_conversion_errors    [PyrexError]   used internally
4093     # orignial_args            [ExprNode]     used internally
4094
4095     obj_conversion_errors = []
4096     type = list_type
4097
4098     gil_message = "Constructing Python list"
4099
4100     def type_dependencies(self, env):
4101         return ()
4102
4103     def infer_type(self, env):
4104         # TOOD: Infer non-object list arrays.
4105         return list_type
4106
4107     def analyse_expressions(self, env):
4108         SequenceNode.analyse_expressions(self, env)
4109         self.coerce_to_pyobject(env)
4110
4111     def analyse_types(self, env):
4112         hold_errors()
4113         self.original_args = list(self.args)
4114         SequenceNode.analyse_types(self, env)
4115         self.obj_conversion_errors = held_errors()
4116         release_errors(ignore=True)
4117
4118     def coerce_to(self, dst_type, env):
4119         if dst_type.is_pyobject:
4120             for err in self.obj_conversion_errors:
4121                 report_error(err)
4122             self.obj_conversion_errors = []
4123             if not self.type.subtype_of(dst_type):
4124                 error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
4125         elif dst_type.is_ptr and dst_type.base_type is not PyrexTypes.c_void_type:
4126             base_type = dst_type.base_type
4127             self.type = PyrexTypes.CArrayType(base_type, len(self.args))
4128             for i in range(len(self.original_args)):
4129                 arg = self.args[i]
4130                 if isinstance(arg, CoerceToPyTypeNode):
4131                     arg = arg.arg
4132                 self.args[i] = arg.coerce_to(base_type, env)
4133         elif dst_type.is_struct:
4134             if len(self.args) > len(dst_type.scope.var_entries):
4135                 error(self.pos, "Too may members for '%s'" % dst_type)
4136             else:
4137                 if len(self.args) < len(dst_type.scope.var_entries):
4138                     warning(self.pos, "Too few members for '%s'" % dst_type, 1)
4139                 for i, (arg, member) in enumerate(zip(self.original_args, dst_type.scope.var_entries)):
4140                     if isinstance(arg, CoerceToPyTypeNode):
4141                         arg = arg.arg
4142                     self.args[i] = arg.coerce_to(member.type, env)
4143             self.type = dst_type
4144         else:
4145             self.type = error_type
4146             error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
4147         return self
4148
4149     def release_temp(self, env):
4150         if self.type.is_array:
4151             # To be valid C++, we must allocate the memory on the stack
4152             # manually and be sure not to reuse it for something else.
4153             pass
4154         else:
4155             SequenceNode.release_temp(self, env)
4156
4157     def calculate_constant_result(self):
4158         self.constant_result = [
4159             arg.constant_result for arg in self.args]
4160
4161     def compile_time_value(self, denv):
4162         return self.compile_time_value_list(denv)
4163
4164     def generate_operation_code(self, code):
4165         if self.type.is_pyobject:
4166             for err in self.obj_conversion_errors:
4167                 report_error(err)
4168             code.putln("%s = PyList_New(%s); %s" %
4169                 (self.result(),
4170                 len(self.args),
4171                 code.error_goto_if_null(self.result(), self.pos)))
4172             code.put_gotref(self.py_result())
4173             for i in range(len(self.args)):
4174                 arg = self.args[i]
4175                 #if not arg.is_temp:
4176                 if not arg.result_in_temp():
4177                     code.put_incref(arg.result(), arg.ctype())
4178                 code.putln("PyList_SET_ITEM(%s, %s, %s);" %
4179                     (self.result(),
4180                     i,
4181                     arg.py_result()))
4182                 code.put_giveref(arg.py_result())
4183         elif self.type.is_array:
4184             for i, arg in enumerate(self.args):
4185                 code.putln("%s[%s] = %s;" % (
4186                                 self.result(),
4187                                 i,
4188                                 arg.result()))
4189         elif self.type.is_struct:
4190             for arg, member in zip(self.args, self.type.scope.var_entries):
4191                 code.putln("%s.%s = %s;" % (
4192                         self.result(),
4193                         member.cname,
4194                         arg.result()))
4195         else:
4196             raise InternalError("List type never specified")
4197
4198     def generate_subexpr_disposal_code(self, code):
4199         # We call generate_post_assignment_code here instead
4200         # of generate_disposal_code, because values were stored
4201         # in the list using a reference-stealing operation.
4202         for arg in self.args:
4203             arg.generate_post_assignment_code(code)
4204             # Should NOT call free_temps -- this is invoked by the default
4205             # generate_evaluation_code which will do that.
4206
4207
4208 class ScopedExprNode(ExprNode):
4209     # Abstract base class for ExprNodes that have their own local
4210     # scope, such as generator expressions.
4211     #
4212     # expr_scope    Scope  the inner scope of the expression
4213
4214     subexprs = []
4215     expr_scope = None
4216
4217     # does this node really have a local scope, e.g. does it leak loop
4218     # variables or not?  non-leaking Py3 behaviour is default, except
4219     # for list comprehensions where the behaviour differs in Py2 and
4220     # Py3 (set in Parsing.py based on parser context)
4221     has_local_scope = True
4222
4223     def init_scope(self, outer_scope, expr_scope=None):
4224         if expr_scope is not None:
4225             self.expr_scope = expr_scope
4226         elif self.has_local_scope:
4227             self.expr_scope = Symtab.GeneratorExpressionScope(outer_scope)
4228         else:
4229             self.expr_scope = None
4230
4231     def analyse_declarations(self, env):
4232         self.init_scope(env)
4233
4234     def analyse_scoped_declarations(self, env):
4235         # this is called with the expr_scope as env
4236         pass
4237
4238     def analyse_types(self, env):
4239         # no recursion here, the children will be analysed separately below
4240         pass
4241
4242     def analyse_scoped_expressions(self, env):
4243         # this is called with the expr_scope as env
4244         pass
4245
4246     def generate_evaluation_code(self, code):
4247         # set up local variables and free their references on exit
4248         generate_inner_evaluation_code = super(ScopedExprNode, self).generate_evaluation_code
4249         if not self.has_local_scope or not self.expr_scope.var_entries:
4250             # no local variables => delegate, done
4251             generate_inner_evaluation_code(code)
4252             return
4253
4254         code.putln('{ /* enter inner scope */')
4255         py_entries = []
4256         for entry in self.expr_scope.var_entries:
4257             if not entry.in_closure:
4258                 code.put_var_declaration(entry)
4259                 if entry.type.is_pyobject and entry.used:
4260                     py_entries.append(entry)
4261         if not py_entries:
4262             # no local Python references => no cleanup required
4263             generate_inner_evaluation_code(code)
4264             code.putln('} /* exit inner scope */')
4265             return
4266         for entry in py_entries:
4267             code.put_init_var_to_py_none(entry)
4268
4269         # must free all local Python references at each exit point
4270         old_loop_labels = tuple(code.new_loop_labels())
4271         old_error_label = code.new_error_label()
4272
4273         generate_inner_evaluation_code(code)
4274
4275         # normal (non-error) exit
4276         for entry in py_entries:
4277             code.put_var_decref(entry)
4278
4279         # error/loop body exit points
4280         exit_scope = code.new_label('exit_scope')
4281         code.put_goto(exit_scope)
4282         for label, old_label in ([(code.error_label, old_error_label)] +
4283                                  list(zip(code.get_loop_labels(), old_loop_labels))):
4284             if code.label_used(label):
4285                 code.put_label(label)
4286                 for entry in py_entries:
4287                     code.put_var_decref(entry)
4288                 code.put_goto(old_label)
4289         code.put_label(exit_scope)
4290         code.putln('} /* exit inner scope */')
4291
4292         code.set_loop_labels(old_loop_labels)
4293         code.error_label = old_error_label
4294
4295
4296 class ComprehensionNode(ScopedExprNode):
4297     subexprs = ["target"]
4298     child_attrs = ["loop", "append"]
4299
4300     def infer_type(self, env):
4301         return self.target.infer_type(env)
4302
4303     def analyse_declarations(self, env):
4304         self.append.target = self # this is used in the PyList_Append of the inner loop
4305         self.init_scope(env)
4306
4307     def analyse_scoped_declarations(self, env):
4308         self.loop.analyse_declarations(env)
4309
4310     def analyse_types(self, env):
4311         self.target.analyse_expressions(env)
4312         self.type = self.target.type
4313         if not self.has_local_scope:
4314             self.loop.analyse_expressions(env)
4315
4316     def analyse_scoped_expressions(self, env):
4317         if self.has_local_scope:
4318             self.loop.analyse_expressions(env)
4319
4320     def may_be_none(self):
4321         return False
4322
4323     def calculate_result_code(self):
4324         return self.target.result()
4325
4326     def generate_result_code(self, code):
4327         self.generate_operation_code(code)
4328
4329     def generate_operation_code(self, code):
4330         self.loop.generate_execution_code(code)
4331
4332     def annotate(self, code):
4333         self.loop.annotate(code)
4334
4335
4336 class ComprehensionAppendNode(Node):
4337     # Need to be careful to avoid infinite recursion:
4338     # target must not be in child_attrs/subexprs
4339
4340     child_attrs = ['expr']
4341
4342     type = PyrexTypes.c_int_type
4343
4344     def analyse_expressions(self, env):
4345         self.expr.analyse_expressions(env)
4346         if not self.expr.type.is_pyobject:
4347             self.expr = self.expr.coerce_to_pyobject(env)
4348
4349     def generate_execution_code(self, code):
4350         if self.target.type is list_type:
4351             function = "PyList_Append"
4352         elif self.target.type is set_type:
4353             function = "PySet_Add"
4354         else:
4355             raise InternalError(
4356                 "Invalid type for comprehension node: %s" % self.target.type)
4357
4358         self.expr.generate_evaluation_code(code)
4359         code.putln(code.error_goto_if("%s(%s, (PyObject*)%s)" % (
4360             function,
4361             self.target.result(),
4362             self.expr.result()
4363             ), self.pos))
4364         self.expr.generate_disposal_code(code)
4365         self.expr.free_temps(code)
4366
4367     def generate_function_definitions(self, env, code):
4368         self.expr.generate_function_definitions(env, code)
4369
4370     def annotate(self, code):
4371         self.expr.annotate(code)
4372
4373 class DictComprehensionAppendNode(ComprehensionAppendNode):
4374     child_attrs = ['key_expr', 'value_expr']
4375
4376     def analyse_expressions(self, env):
4377         self.key_expr.analyse_expressions(env)
4378         if not self.key_expr.type.is_pyobject:
4379             self.key_expr = self.key_expr.coerce_to_pyobject(env)
4380         self.value_expr.analyse_expressions(env)
4381         if not self.value_expr.type.is_pyobject:
4382             self.value_expr = self.value_expr.coerce_to_pyobject(env)
4383
4384     def generate_execution_code(self, code):
4385         self.key_expr.generate_evaluation_code(code)
4386         self.value_expr.generate_evaluation_code(code)
4387         code.putln(code.error_goto_if("PyDict_SetItem(%s, (PyObject*)%s, (PyObject*)%s)" % (
4388             self.target.result(),
4389             self.key_expr.result(),
4390             self.value_expr.result()
4391             ), self.pos))
4392         self.key_expr.generate_disposal_code(code)
4393         self.key_expr.free_temps(code)
4394         self.value_expr.generate_disposal_code(code)
4395         self.value_expr.free_temps(code)
4396
4397     def generate_function_definitions(self, env, code):
4398         self.key_expr.generate_function_definitions(env, code)
4399         self.value_expr.generate_function_definitions(env, code)
4400
4401     def annotate(self, code):
4402         self.key_expr.annotate(code)
4403         self.value_expr.annotate(code)
4404
4405
4406 class GeneratorExpressionNode(ScopedExprNode):
4407     # A generator expression, e.g.  (i for i in range(10))
4408     #
4409     # Result is a generator.
4410     #
4411     # loop      ForStatNode   the for-loop, containing a YieldExprNode
4412
4413     child_attrs = ["loop"]
4414
4415     type = py_object_type
4416
4417     def analyse_scoped_declarations(self, env):
4418         self.loop.analyse_declarations(env)
4419
4420     def analyse_types(self, env):
4421         if not self.has_local_scope:
4422             self.loop.analyse_expressions(env)
4423         self.is_temp = True
4424
4425     def analyse_scoped_expressions(self, env):
4426         if self.has_local_scope:
4427             self.loop.analyse_expressions(env)
4428
4429     def may_be_none(self):
4430         return False
4431
4432     def annotate(self, code):
4433         self.loop.annotate(code)
4434
4435
4436 class InlinedGeneratorExpressionNode(GeneratorExpressionNode):
4437     # An inlined generator expression for which the result is
4438     # calculated inside of the loop.  This will only be created by
4439     # transforms when replacing builtin calls on generator
4440     # expressions.
4441     #
4442     # loop           ForStatNode      the for-loop, not containing any YieldExprNodes
4443     # result_node    ResultRefNode    the reference to the result value temp
4444     # orig_func      String           the name of the builtin function this node replaces
4445
4446     child_attrs = ["loop"]
4447     loop_analysed = False
4448
4449     def infer_type(self, env):
4450         return self.result_node.infer_type(env)
4451
4452     def analyse_types(self, env):
4453         if not self.has_local_scope:
4454             self.loop_analysed = True
4455             self.loop.analyse_expressions(env)
4456         self.type = self.result_node.type
4457         self.is_temp = True
4458
4459     def analyse_scoped_expressions(self, env):
4460         self.loop_analysed = True
4461         GeneratorExpressionNode.analyse_scoped_expressions(self, env)
4462
4463     def coerce_to(self, dst_type, env):
4464         if self.orig_func == 'sum' and dst_type.is_numeric and not self.loop_analysed:
4465             # We can optimise by dropping the aggregation variable and
4466             # the add operations into C.  This can only be done safely
4467             # before analysing the loop body, after that, the result
4468             # reference type will have infected expressions and
4469             # assignments.
4470             self.result_node.type = self.type = dst_type
4471             return self
4472         return GeneratorExpressionNode.coerce_to(self, dst_type, env)
4473
4474     def generate_result_code(self, code):
4475         self.result_node.result_code = self.result()
4476         self.loop.generate_execution_code(code)
4477
4478
4479 class SetNode(ExprNode):
4480     #  Set constructor.
4481
4482     type = set_type
4483
4484     subexprs = ['args']
4485
4486     gil_message = "Constructing Python set"
4487
4488     def analyse_types(self, env):
4489         for i in range(len(self.args)):
4490             arg = self.args[i]
4491             arg.analyse_types(env)
4492             self.args[i] = arg.coerce_to_pyobject(env)
4493         self.type = set_type
4494         self.is_temp = 1
4495
4496     def may_be_none(self):
4497         return False
4498
4499     def calculate_constant_result(self):
4500         self.constant_result = set([
4501                 arg.constant_result for arg in self.args])
4502
4503     def compile_time_value(self, denv):
4504         values = [arg.compile_time_value(denv) for arg in self.args]
4505         try:
4506             return set(values)
4507         except Exception, e:
4508             self.compile_time_value_error(e)
4509
4510     def generate_evaluation_code(self, code):
4511         code.globalstate.use_utility_code(Builtin.py23_set_utility_code)
4512         self.allocate_temp_result(code)
4513         code.putln(
4514             "%s = PySet_New(0); %s" % (
4515                 self.result(),
4516                 code.error_goto_if_null(self.result(), self.pos)))
4517         code.put_gotref(self.py_result())
4518         for arg in self.args:
4519             arg.generate_evaluation_code(code)
4520             code.putln(
4521                 code.error_goto_if_neg(
4522                     "PySet_Add(%s, %s)" % (self.result(), arg.py_result()),
4523                     self.pos))
4524             arg.generate_disposal_code(code)
4525             arg.free_temps(code)
4526
4527
4528 class DictNode(ExprNode):
4529     #  Dictionary constructor.
4530     #
4531     #  key_value_pairs  [DictItemNode]
4532     #
4533     # obj_conversion_errors    [PyrexError]   used internally
4534
4535     subexprs = ['key_value_pairs']
4536     is_temp = 1
4537     type = dict_type
4538
4539     obj_conversion_errors = []
4540
4541     def calculate_constant_result(self):
4542         self.constant_result = dict([
4543                 item.constant_result for item in self.key_value_pairs])
4544
4545     def compile_time_value(self, denv):
4546         pairs = [(item.key.compile_time_value(denv), item.value.compile_time_value(denv))
4547             for item in self.key_value_pairs]
4548         try:
4549             return dict(pairs)
4550         except Exception, e:
4551             self.compile_time_value_error(e)
4552
4553     def type_dependencies(self, env):
4554         return ()
4555
4556     def infer_type(self, env):
4557         # TOOD: Infer struct constructors.
4558         return dict_type
4559
4560     def analyse_types(self, env):
4561         hold_errors()
4562         for item in self.key_value_pairs:
4563             item.analyse_types(env)
4564         self.obj_conversion_errors = held_errors()
4565         release_errors(ignore=True)
4566
4567     def may_be_none(self):
4568         return False
4569
4570     def coerce_to(self, dst_type, env):
4571         if dst_type.is_pyobject:
4572             self.release_errors()
4573             if not self.type.subtype_of(dst_type):
4574                 error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
4575         elif dst_type.is_struct_or_union:
4576             self.type = dst_type
4577             if not dst_type.is_struct and len(self.key_value_pairs) != 1:
4578                 error(self.pos, "Exactly one field must be specified to convert to union '%s'" % dst_type)
4579             elif dst_type.is_struct and len(self.key_value_pairs) < len(dst_type.scope.var_entries):
4580                 warning(self.pos, "Not all members given for struct '%s'" % dst_type, 1)
4581             for item in self.key_value_pairs:
4582                 if isinstance(item.key, CoerceToPyTypeNode):
4583                     item.key = item.key.arg
4584                 if not isinstance(item.key, (UnicodeNode, StringNode, BytesNode)):
4585                     error(item.key.pos, "Invalid struct field identifier")
4586                     item.key = StringNode(item.key.pos, value="<error>")
4587                 else:
4588                     key = str(item.key.value) # converts string literals to unicode in Py3
4589                     member = dst_type.scope.lookup_here(key)
4590                     if not member:
4591                         error(item.key.pos, "struct '%s' has no field '%s'" % (dst_type, key))
4592                     else:
4593                         value = item.value
4594                         if isinstance(value, CoerceToPyTypeNode):
4595                             value = value.arg
4596                         item.value = value.coerce_to(member.type, env)
4597         else:
4598             self.type = error_type
4599             error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
4600         return self
4601
4602     def release_errors(self):
4603         for err in self.obj_conversion_errors:
4604             report_error(err)
4605         self.obj_conversion_errors = []
4606
4607     gil_message = "Constructing Python dict"
4608
4609     def generate_evaluation_code(self, code):
4610         #  Custom method used here because key-value
4611         #  pairs are evaluated and used one at a time.
4612         code.mark_pos(self.pos)
4613         self.allocate_temp_result(code)
4614         if self.type.is_pyobject:
4615             self.release_errors()
4616             code.putln(
4617                 "%s = PyDict_New(); %s" % (
4618                     self.result(),
4619                     code.error_goto_if_null(self.result(), self.pos)))
4620             code.put_gotref(self.py_result())
4621         for item in self.key_value_pairs:
4622             item.generate_evaluation_code(code)
4623             if self.type.is_pyobject:
4624                 code.put_error_if_neg(self.pos,
4625                     "PyDict_SetItem(%s, %s, %s)" % (
4626                         self.result(),
4627                         item.key.py_result(),
4628                         item.value.py_result()))
4629             else:
4630                 code.putln("%s.%s = %s;" % (
4631                         self.result(),
4632                         item.key.value,
4633                         item.value.result()))
4634             item.generate_disposal_code(code)
4635             item.free_temps(code)
4636
4637     def annotate(self, code):
4638         for item in self.key_value_pairs:
4639             item.annotate(code)
4640
4641 class DictItemNode(ExprNode):
4642     # Represents a single item in a DictNode
4643     #
4644     # key          ExprNode
4645     # value        ExprNode
4646     subexprs = ['key', 'value']
4647
4648     nogil_check = None # Parent DictNode takes care of it
4649
4650     def calculate_constant_result(self):
4651         self.constant_result = (
4652             self.key.constant_result, self.value.constant_result)
4653
4654     def analyse_types(self, env):
4655         self.key.analyse_types(env)
4656         self.value.analyse_types(env)
4657         self.key = self.key.coerce_to_pyobject(env)
4658         self.value = self.value.coerce_to_pyobject(env)
4659
4660     def generate_evaluation_code(self, code):
4661         self.key.generate_evaluation_code(code)
4662         self.value.generate_evaluation_code(code)
4663
4664     def generate_disposal_code(self, code):
4665         self.key.generate_disposal_code(code)
4666         self.value.generate_disposal_code(code)
4667
4668     def free_temps(self, code):
4669         self.key.free_temps(code)
4670         self.value.free_temps(code)
4671
4672     def __iter__(self):
4673         return iter([self.key, self.value])
4674
4675 class ModuleNameMixin(object):
4676     def set_mod_name(self, env):
4677         self.module_name = env.global_scope().qualified_name
4678
4679     def get_py_mod_name(self, code):
4680         return code.get_py_string_const(
4681                  self.module_name, identifier=True)
4682
4683 class ClassNode(ExprNode, ModuleNameMixin):
4684     #  Helper class used in the implementation of Python
4685     #  class definitions. Constructs a class object given
4686     #  a name, tuple of bases and class dictionary.
4687     #
4688     #  name         EncodedString      Name of the class
4689     #  bases        ExprNode           Base class tuple
4690     #  dict         ExprNode           Class dict (not owned by this node)
4691     #  doc          ExprNode or None   Doc string
4692     #  module_name  EncodedString      Name of defining module
4693
4694     subexprs = ['bases', 'doc']
4695
4696     def analyse_types(self, env):
4697         self.bases.analyse_types(env)
4698         if self.doc:
4699             self.doc.analyse_types(env)
4700             self.doc = self.doc.coerce_to_pyobject(env)
4701         self.type = py_object_type
4702         self.is_temp = 1
4703         env.use_utility_code(create_class_utility_code);
4704         #TODO(craig,haoyu) This should be moved to a better place
4705         self.set_mod_name(env)
4706
4707     def may_be_none(self):
4708         return True
4709
4710     gil_message = "Constructing Python class"
4711
4712     def generate_result_code(self, code):
4713         cname = code.intern_identifier(self.name)
4714
4715         if self.doc:
4716             code.put_error_if_neg(self.pos,
4717                 'PyDict_SetItemString(%s, "__doc__", %s)' % (
4718                     self.dict.py_result(),
4719                     self.doc.py_result()))
4720         py_mod_name = self.get_py_mod_name(code)
4721         code.putln(
4722             '%s = __Pyx_CreateClass(%s, %s, %s, %s); %s' % (
4723                 self.result(),
4724                 self.bases.py_result(),
4725                 self.dict.py_result(),
4726                 cname,
4727                 py_mod_name,
4728                 code.error_goto_if_null(self.result(), self.pos)))
4729         code.put_gotref(self.py_result())
4730
4731
4732 class Py3ClassNode(ExprNode):
4733     #  Helper class used in the implementation of Python3+
4734     #  class definitions. Constructs a class object given
4735     #  a name, tuple of bases and class dictionary.
4736     #
4737     #  name         EncodedString      Name of the class
4738     #  dict         ExprNode           Class dict (not owned by this node)
4739     #  module_name  EncodedString      Name of defining module
4740
4741     subexprs = []
4742
4743     def analyse_types(self, env):
4744         self.type = py_object_type
4745         self.is_temp = 1
4746
4747     def may_be_none(self):
4748         return True
4749
4750     gil_message = "Constructing Python class"
4751
4752     def generate_result_code(self, code):
4753         code.globalstate.use_utility_code(create_py3class_utility_code)
4754         cname = code.intern_identifier(self.name)
4755         code.putln(
4756             '%s = __Pyx_Py3ClassCreate(%s, %s, %s, %s, %s); %s' % (
4757                 self.result(),
4758                 self.metaclass.result(),
4759                 cname,
4760                 self.bases.py_result(),
4761                 self.dict.py_result(),
4762                 self.mkw.py_result(),
4763                 code.error_goto_if_null(self.result(), self.pos)))
4764         code.put_gotref(self.py_result())
4765
4766 class KeywordArgsNode(ExprNode):
4767     # Helper class for keyword arguments
4768     #
4769     # keyword_args ExprNode or None     Keyword arguments
4770     # starstar_arg ExprNode or None     Extra arguments
4771
4772     subexprs = ['keyword_args', 'starstar_arg']
4773
4774     def analyse_types(self, env):
4775         if self.keyword_args:
4776             self.keyword_args.analyse_types(env)
4777         if self.starstar_arg:
4778             self.starstar_arg.analyse_types(env)
4779             # make sure we have a Python object as **kwargs mapping
4780             self.starstar_arg = \
4781                 self.starstar_arg.coerce_to_pyobject(env)
4782         self.type = py_object_type
4783         self.is_temp = 1
4784
4785     gil_message = "Constructing Keyword Args"
4786
4787     def generate_result_code(self, code):
4788         if self.keyword_args and self.starstar_arg:
4789             code.put_error_if_neg(self.pos,
4790                 "PyDict_Update(%s, %s)" % (
4791                     self.keyword_args.py_result(),
4792                     self.starstar_arg.py_result()))
4793         if self.keyword_args:
4794             code.putln("%s = %s;" % (self.result(), self.keyword_args.result()))
4795             code.put_incref(self.keyword_args.result(), self.keyword_args.ctype())
4796         elif self.starstar_arg:
4797             code.putln(
4798                 "%s = PyDict_Copy(%s); %s" % (
4799                     self.result(),
4800                     self.starstar_arg.py_result(),
4801                     code.error_goto_if_null(self.result(), self.pos)))
4802             code.put_gotref(self.py_result())
4803         else:
4804             code.putln(
4805                 "%s = PyDict_New(); %s" % (
4806                     self.result(),
4807                     code.error_goto_if_null(self.result(), self.pos)))
4808             code.put_gotref(self.py_result())
4809
4810 class PyClassMetaclassNode(ExprNode):
4811     # Helper class holds Python3 metaclass object
4812     #
4813     #  bases        ExprNode           Base class tuple (not owned by this node)
4814     #  mkw          ExprNode           Class keyword arguments (not owned by this node)
4815
4816     subexprs = []
4817
4818     def analyse_types(self, env):
4819         self.type = py_object_type
4820         self.is_temp = True
4821
4822     def may_be_none(self):
4823         return True
4824
4825     def generate_result_code(self, code):
4826         code.putln(
4827             "%s = __Pyx_Py3MetaclassGet(%s, %s); %s" % (
4828                 self.result(),
4829                 self.bases.result(),
4830                 self.mkw.result(),
4831                 code.error_goto_if_null(self.result(), self.pos)))
4832         code.put_gotref(self.py_result())
4833
4834 class PyClassNamespaceNode(ExprNode, ModuleNameMixin):
4835     # Helper class holds Python3 namespace object
4836     #
4837     # All this are not owned by this node
4838     #  metaclass    ExprNode           Metaclass object
4839     #  bases        ExprNode           Base class tuple
4840     #  mkw          ExprNode           Class keyword arguments
4841     #  doc          ExprNode or None   Doc string (owned)
4842
4843     subexprs = ['doc']
4844
4845     def analyse_types(self, env):
4846         self.bases.analyse_types(env)
4847         if self.doc:
4848             self.doc.analyse_types(env)
4849             self.doc = self.doc.coerce_to_pyobject(env)
4850         self.type = py_object_type
4851         self.is_temp = 1
4852         #TODO(craig,haoyu) This should be moved to a better place
4853         self.set_mod_name(env)
4854
4855     def may_be_none(self):
4856         return True
4857
4858     def generate_result_code(self, code):
4859         cname = code.intern_identifier(self.name)
4860         py_mod_name = self.get_py_mod_name(code)
4861         if self.doc:
4862             doc_code = self.doc.result()
4863         else:
4864             doc_code = '(PyObject *) NULL'
4865         code.putln(
4866             "%s = __Pyx_Py3MetaclassPrepare(%s, %s, %s, %s, %s, %s); %s" % (
4867                 self.result(),
4868                 self.metaclass.result(),
4869                 self.bases.result(),
4870                 cname,
4871                 self.mkw.result(),
4872                 py_mod_name,
4873                 doc_code,
4874                 code.error_goto_if_null(self.result(), self.pos)))
4875         code.put_gotref(self.py_result())
4876
4877 class BoundMethodNode(ExprNode):
4878     #  Helper class used in the implementation of Python
4879     #  class definitions. Constructs an bound method
4880     #  object from a class and a function.
4881     #
4882     #  function      ExprNode   Function object
4883     #  self_object   ExprNode   self object
4884
4885     subexprs = ['function']
4886
4887     def analyse_types(self, env):
4888         self.function.analyse_types(env)
4889         self.type = py_object_type
4890         self.is_temp = 1
4891
4892     gil_message = "Constructing an bound method"
4893
4894     def generate_result_code(self, code):
4895         code.putln(
4896             "%s = PyMethod_New(%s, %s, (PyObject*)%s->ob_type); %s" % (
4897                 self.result(),
4898                 self.function.py_result(),
4899                 self.self_object.py_result(),
4900                 self.self_object.py_result(),
4901                 code.error_goto_if_null(self.result(), self.pos)))
4902         code.put_gotref(self.py_result())
4903
4904 class UnboundMethodNode(ExprNode):
4905     #  Helper class used in the implementation of Python
4906     #  class definitions. Constructs an unbound method
4907     #  object from a class and a function.
4908     #
4909     #  function      ExprNode   Function object
4910
4911     type = py_object_type
4912     is_temp = 1
4913
4914     subexprs = ['function']
4915
4916     def analyse_types(self, env):
4917         self.function.analyse_types(env)
4918
4919     def may_be_none(self):
4920         return False
4921
4922     gil_message = "Constructing an unbound method"
4923
4924     def generate_result_code(self, code):
4925         class_cname = code.pyclass_stack[-1].classobj.result()
4926         code.putln(
4927             "%s = PyMethod_New(%s, 0, %s); %s" % (
4928                 self.result(),
4929                 self.function.py_result(),
4930                 class_cname,
4931                 code.error_goto_if_null(self.result(), self.pos)))
4932         code.put_gotref(self.py_result())
4933
4934
4935 class PyCFunctionNode(ExprNode, ModuleNameMixin):
4936     #  Helper class used in the implementation of Python
4937     #  class definitions. Constructs a PyCFunction object
4938     #  from a PyMethodDef struct.
4939     #
4940     #  pymethdef_cname   string             PyMethodDef structure
4941     #  self_object       ExprNode or None
4942     #  binding           bool
4943     #  module_name       EncodedString      Name of defining module
4944
4945     subexprs = []
4946     self_object = None
4947     binding = False
4948
4949     type = py_object_type
4950     is_temp = 1
4951
4952     def analyse_types(self, env):
4953         if self.binding:
4954             env.use_utility_code(binding_cfunc_utility_code)
4955
4956         #TODO(craig,haoyu) This should be moved to a better place
4957         self.set_mod_name(env)
4958
4959     def may_be_none(self):
4960         return False
4961
4962     gil_message = "Constructing Python function"
4963
4964     def self_result_code(self):
4965         if self.self_object is None:
4966             self_result = "NULL"
4967         else:
4968             self_result = self.self_object.py_result()
4969         return self_result
4970
4971     def generate_result_code(self, code):
4972         if self.binding:
4973             constructor = "%s_NewEx" % Naming.binding_cfunc
4974         else:
4975             constructor = "PyCFunction_NewEx"
4976         py_mod_name = self.get_py_mod_name(code)
4977         code.putln(
4978             '%s = %s(&%s, %s, %s); %s' % (
4979                 self.result(),
4980                 constructor,
4981                 self.pymethdef_cname,
4982                 self.self_result_code(),
4983                 py_mod_name,
4984                 code.error_goto_if_null(self.result(), self.pos)))
4985         code.put_gotref(self.py_result())
4986
4987 class InnerFunctionNode(PyCFunctionNode):
4988     # Special PyCFunctionNode that depends on a closure class
4989     #
4990
4991     binding = True
4992     needs_self_code = True
4993
4994     def self_result_code(self):
4995         if self.needs_self_code:
4996             return "((PyObject*)%s)" % (Naming.cur_scope_cname)
4997         return "NULL"
4998
4999 class LambdaNode(InnerFunctionNode):
5000     # Lambda expression node (only used as a function reference)
5001     #
5002     # args          [CArgDeclNode]         formal arguments
5003     # star_arg      PyArgDeclNode or None  * argument
5004     # starstar_arg  PyArgDeclNode or None  ** argument
5005     # lambda_name   string                 a module-globally unique lambda name
5006     # result_expr   ExprNode
5007     # def_node      DefNode                the underlying function 'def' node
5008
5009     child_attrs = ['def_node']
5010
5011     def_node = None
5012     name = StringEncoding.EncodedString('<lambda>')
5013
5014     def analyse_declarations(self, env):
5015         self.def_node.analyse_declarations(env)
5016         self.pymethdef_cname = self.def_node.entry.pymethdef_cname
5017         env.add_lambda_def(self.def_node)
5018
5019 class YieldExprNode(ExprNode):
5020     # Yield expression node
5021     #
5022     # arg         ExprNode   the value to return from the generator
5023     # label_name  string     name of the C label used for this yield
5024
5025     subexprs = ['arg']
5026     type = py_object_type
5027
5028     def analyse_types(self, env):
5029         self.is_temp = 1
5030         if self.arg is not None:
5031             self.arg.analyse_types(env)
5032             if not self.arg.type.is_pyobject:
5033                 self.arg = self.arg.coerce_to_pyobject(env)
5034         error(self.pos, "Generators are not supported")
5035
5036     def generate_result_code(self, code):
5037         self.label_name = code.new_label('resume_from_yield')
5038         code.use_label(self.label_name)
5039         code.putln("/* FIXME: save temporary variables */")
5040         code.putln("/* FIXME: return from function, yielding value */")
5041         code.put_label(self.label_name)
5042         code.putln("/* FIXME: restore temporary variables and  */")
5043         code.putln("/* FIXME: extract sent value from closure */")
5044
5045
5046 #-------------------------------------------------------------------
5047 #
5048 #  Unary operator nodes
5049 #
5050 #-------------------------------------------------------------------
5051
5052 compile_time_unary_operators = {
5053     'not': operator.not_,
5054     '~': operator.inv,
5055     '-': operator.neg,
5056     '+': operator.pos,
5057 }
5058
5059 class UnopNode(ExprNode):
5060     #  operator     string
5061     #  operand      ExprNode
5062     #
5063     #  Processing during analyse_expressions phase:
5064     #
5065     #    analyse_c_operation
5066     #      Called when the operand is not a pyobject.
5067     #      - Check operand type and coerce if needed.
5068     #      - Determine result type and result code fragment.
5069     #      - Allocate temporary for result if needed.
5070
5071     subexprs = ['operand']
5072     infix = True
5073
5074     def calculate_constant_result(self):
5075         func = compile_time_unary_operators[self.operator]
5076         self.constant_result = func(self.operand.constant_result)
5077
5078     def compile_time_value(self, denv):
5079         func = compile_time_unary_operators.get(self.operator)
5080         if not func:
5081             error(self.pos,
5082                 "Unary '%s' not supported in compile-time expression"
5083                     % self.operator)
5084         operand = self.operand.compile_time_value(denv)
5085         try:
5086             return func(operand)
5087         except Exception, e:
5088             self.compile_time_value_error(e)
5089
5090     def infer_type(self, env):
5091         operand_type = self.operand.infer_type(env)
5092         if operand_type.is_pyobject:
5093             return py_object_type
5094         else:
5095             return operand_type
5096
5097     def analyse_types(self, env):
5098         self.operand.analyse_types(env)
5099         if self.is_py_operation():
5100             self.coerce_operand_to_pyobject(env)
5101             self.type = py_object_type
5102             self.is_temp = 1
5103         elif self.is_cpp_operation():
5104             self.analyse_cpp_operation(env)
5105         else:
5106             self.analyse_c_operation(env)
5107
5108     def check_const(self):
5109         return self.operand.check_const()
5110
5111     def is_py_operation(self):
5112         return self.operand.type.is_pyobject
5113
5114     def nogil_check(self, env):
5115         if self.is_py_operation():
5116             self.gil_error()
5117
5118     def is_cpp_operation(self):
5119         type = self.operand.type
5120         return type.is_cpp_class
5121
5122     def coerce_operand_to_pyobject(self, env):
5123         self.operand = self.operand.coerce_to_pyobject(env)
5124
5125     def generate_result_code(self, code):
5126         if self.operand.type.is_pyobject:
5127             self.generate_py_operation_code(code)
5128
5129     def generate_py_operation_code(self, code):
5130         function = self.py_operation_function()
5131         code.putln(
5132             "%s = %s(%s); %s" % (
5133                 self.result(),
5134                 function,
5135                 self.operand.py_result(),
5136                 code.error_goto_if_null(self.result(), self.pos)))
5137         code.put_gotref(self.py_result())
5138
5139     def type_error(self):
5140         if not self.operand.type.is_error:
5141             error(self.pos, "Invalid operand type for '%s' (%s)" %
5142                 (self.operator, self.operand.type))
5143         self.type = PyrexTypes.error_type
5144
5145     def analyse_cpp_operation(self, env):
5146         type = self.operand.type
5147         if type.is_ptr:
5148             type = type.base_type
5149         function = type.scope.lookup("operator%s" % self.operator)
5150         if not function:
5151             error(self.pos, "'%s' operator not defined for %s"
5152                 % (self.operator, type))
5153             self.type_error()
5154             return
5155         func_type = function.type
5156         if func_type.is_ptr:
5157             func_type = func_type.base_type
5158         self.type = func_type.return_type
5159
5160
5161 class NotNode(ExprNode):
5162     #  'not' operator
5163     #
5164     #  operand   ExprNode
5165
5166     type = PyrexTypes.c_bint_type
5167
5168     subexprs = ['operand']
5169
5170     def calculate_constant_result(self):
5171         self.constant_result = not self.operand.constant_result
5172
5173     def compile_time_value(self, denv):
5174         operand = self.operand.compile_time_value(denv)
5175         try:
5176             return not operand
5177         except Exception, e:
5178             self.compile_time_value_error(e)
5179
5180     def infer_type(self, env):
5181         return PyrexTypes.c_bint_type
5182
5183     def analyse_types(self, env):
5184         self.operand.analyse_types(env)
5185         self.operand = self.operand.coerce_to_boolean(env)
5186
5187     def calculate_result_code(self):
5188         return "(!%s)" % self.operand.result()
5189
5190     def generate_result_code(self, code):
5191         pass
5192
5193
5194 class UnaryPlusNode(UnopNode):
5195     #  unary '+' operator
5196
5197     operator = '+'
5198
5199     def analyse_c_operation(self, env):
5200         self.type = self.operand.type
5201
5202     def py_operation_function(self):
5203         return "PyNumber_Positive"
5204
5205     def calculate_result_code(self):
5206         if self.is_cpp_operation():
5207             return "(+%s)" % self.operand.result()
5208         else:
5209             return self.operand.result()
5210
5211
5212 class UnaryMinusNode(UnopNode):
5213     #  unary '-' operator
5214
5215     operator = '-'
5216
5217     def analyse_c_operation(self, env):
5218         if self.operand.type.is_numeric:
5219             self.type = self.operand.type
5220         else:
5221             self.type_error()
5222         if self.type.is_complex:
5223             self.infix = False
5224
5225     def py_operation_function(self):
5226         return "PyNumber_Negative"
5227
5228     def calculate_result_code(self):
5229         if self.infix:
5230             return "(-%s)" % self.operand.result()
5231         else:
5232             return "%s(%s)" % (self.operand.type.unary_op('-'), self.operand.result())
5233
5234     def get_constant_c_result_code(self):
5235         value = self.operand.get_constant_c_result_code()
5236         if value:
5237             return "(-%s)" % (value)
5238
5239 class TildeNode(UnopNode):
5240     #  unary '~' operator
5241
5242     def analyse_c_operation(self, env):
5243         if self.operand.type.is_int:
5244             self.type = self.operand.type
5245         else:
5246             self.type_error()
5247
5248     def py_operation_function(self):
5249         return "PyNumber_Invert"
5250
5251     def calculate_result_code(self):
5252         return "(~%s)" % self.operand.result()
5253
5254
5255 class CUnopNode(UnopNode):
5256
5257     def is_py_operation(self):
5258         return False
5259
5260 class DereferenceNode(CUnopNode):
5261     #  unary * operator
5262
5263     operator = '*'
5264
5265     def analyse_c_operation(self, env):
5266         if self.operand.type.is_ptr:
5267             self.type = self.operand.type.base_type
5268         else:
5269             self.type_error()
5270
5271     def calculate_result_code(self):
5272         return "(*%s)" % self.operand.result()
5273
5274
5275 class DecrementIncrementNode(CUnopNode):
5276     #  unary ++/-- operator
5277
5278     def analyse_c_operation(self, env):
5279         if self.operand.type.is_ptr or self.operand.type.is_numeric:
5280             self.type = self.operand.type
5281         else:
5282             self.type_error()
5283
5284     def calculate_result_code(self):
5285         if self.is_prefix:
5286             return "(%s%s)" % (self.operator, self.operand.result())
5287         else:
5288             return "(%s%s)" % (self.operand.result(), self.operator)
5289
5290 def inc_dec_constructor(is_prefix, operator):
5291     return lambda pos, **kwds: DecrementIncrementNode(pos, is_prefix=is_prefix, operator=operator, **kwds)
5292
5293
5294 class AmpersandNode(ExprNode):
5295     #  The C address-of operator.
5296     #
5297     #  operand  ExprNode
5298
5299     subexprs = ['operand']
5300
5301     def infer_type(self, env):
5302         return PyrexTypes.c_ptr_type(self.operand.infer_type(env))
5303
5304     def analyse_types(self, env):
5305         self.operand.analyse_types(env)
5306         argtype = self.operand.type
5307         if not (argtype.is_cfunction or self.operand.is_lvalue()):
5308             self.error("Taking address of non-lvalue")
5309             return
5310         if argtype.is_pyobject:
5311             self.error("Cannot take address of Python variable")
5312             return
5313         self.type = PyrexTypes.c_ptr_type(argtype)
5314
5315     def check_const(self):
5316         return self.operand.check_const_addr()
5317
5318     def error(self, mess):
5319         error(self.pos, mess)
5320         self.type = PyrexTypes.error_type
5321         self.result_code = "<error>"
5322
5323     def calculate_result_code(self):
5324         return "(&%s)" % self.operand.result()
5325
5326     def generate_result_code(self, code):
5327         pass
5328
5329
5330 unop_node_classes = {
5331     "+":  UnaryPlusNode,
5332     "-":  UnaryMinusNode,
5333     "~":  TildeNode,
5334 }
5335
5336 def unop_node(pos, operator, operand):
5337     # Construct unnop node of appropriate class for
5338     # given operator.
5339     if isinstance(operand, IntNode) and operator == '-':
5340         return IntNode(pos = operand.pos, value = str(-Utils.str_to_number(operand.value)))
5341     elif isinstance(operand, UnopNode) and operand.operator == operator:
5342         warning(pos, "Python has no increment/decrement operator: %s%sx = %s(%sx) = x" % ((operator,)*4), 5)
5343     return unop_node_classes[operator](pos,
5344         operator = operator,
5345         operand = operand)
5346
5347
5348 class TypecastNode(ExprNode):
5349     #  C type cast
5350     #
5351     #  operand      ExprNode
5352     #  base_type    CBaseTypeNode
5353     #  declarator   CDeclaratorNode
5354     #
5355     #  If used from a transform, one can if wanted specify the attribute
5356     #  "type" directly and leave base_type and declarator to None
5357
5358     subexprs = ['operand']
5359     base_type = declarator = type = None
5360
5361     def type_dependencies(self, env):
5362         return ()
5363
5364     def infer_type(self, env):
5365         if self.type is None:
5366             base_type = self.base_type.analyse(env)
5367             _, self.type = self.declarator.analyse(base_type, env)
5368         return self.type
5369
5370     def analyse_types(self, env):
5371         if self.type is None:
5372             base_type = self.base_type.analyse(env)
5373             _, self.type = self.declarator.analyse(base_type, env)
5374         if self.type.is_cfunction:
5375             error(self.pos,
5376                 "Cannot cast to a function type")
5377             self.type = PyrexTypes.error_type
5378         self.operand.analyse_types(env)
5379         to_py = self.type.is_pyobject
5380         from_py = self.operand.type.is_pyobject
5381         if from_py and not to_py and self.operand.is_ephemeral() and not self.type.is_numeric:
5382             error(self.pos, "Casting temporary Python object to non-numeric non-Python type")
5383         if to_py and not from_py:
5384             if self.type is bytes_type and self.operand.type.is_int:
5385                 # FIXME: the type cast node isn't needed in this case
5386                 # and can be dropped once analyse_types() can return a
5387                 # different node
5388                 self.operand = CoerceIntToBytesNode(self.operand, env)
5389             elif self.operand.type.can_coerce_to_pyobject(env):
5390                 self.result_ctype = py_object_type
5391                 self.operand = self.operand.coerce_to_pyobject(env)
5392             else:
5393                 if self.operand.type.is_ptr:
5394                     if not (self.operand.type.base_type.is_void or self.operand.type.base_type.is_struct):
5395                         error(self.pos, "Python objects cannot be cast from pointers of primitive types")
5396                 else:
5397                     # Should this be an error?
5398                     warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.operand.type, self.type))
5399                 self.operand = self.operand.coerce_to_simple(env)
5400         elif from_py and not to_py:
5401             if self.type.create_from_py_utility_code(env):
5402                 self.operand = self.operand.coerce_to(self.type, env)
5403             elif self.type.is_ptr:
5404                 if not (self.type.base_type.is_void or self.type.base_type.is_struct):
5405                     error(self.pos, "Python objects cannot be cast to pointers of primitive types")
5406             else:
5407                 warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.type, self.operand.type))
5408         elif from_py and to_py:
5409             if self.typecheck and self.type.is_extension_type:
5410                 self.operand = PyTypeTestNode(self.operand, self.type, env, notnone=True)
5411         elif self.type.is_complex and self.operand.type.is_complex:
5412             self.operand = self.operand.coerce_to_simple(env)
5413
5414     def is_simple(self):
5415         # either temp or a C cast => no side effects
5416         return True
5417
5418     def nogil_check(self, env):
5419         if self.type and self.type.is_pyobject and self.is_temp:
5420             self.gil_error()
5421
5422     def check_const(self):
5423         return self.operand.check_const()
5424
5425     def calculate_constant_result(self):
5426         # we usually do not know the result of a type cast at code
5427         # generation time
5428         pass
5429
5430     def calculate_result_code(self):
5431         if self.type.is_complex:
5432             operand_result = self.operand.result()
5433             if self.operand.type.is_complex:
5434                 real_part = self.type.real_type.cast_code("__Pyx_CREAL(%s)" % operand_result)
5435                 imag_part = self.type.real_type.cast_code("__Pyx_CIMAG(%s)" % operand_result)
5436             else:
5437                 real_part = self.type.real_type.cast_code(operand_result)
5438                 imag_part = "0"
5439             return "%s(%s, %s)" % (
5440                     self.type.from_parts,
5441                     real_part,
5442                     imag_part)
5443         else:
5444             return self.type.cast_code(self.operand.result())
5445
5446     def get_constant_c_result_code(self):
5447         operand_result = self.operand.get_constant_c_result_code()
5448         if operand_result:
5449             return self.type.cast_code(operand_result)
5450
5451     def result_as(self, type):
5452         if self.type.is_pyobject and not self.is_temp:
5453             #  Optimise away some unnecessary casting
5454             return self.operand.result_as(type)
5455         else:
5456             return ExprNode.result_as(self, type)
5457
5458     def generate_result_code(self, code):
5459         if self.is_temp:
5460             code.putln(
5461                 "%s = (PyObject *)%s;" % (
5462                     self.result(),
5463                     self.operand.result()))
5464             code.put_incref(self.result(), self.ctype())
5465
5466
5467 class SizeofNode(ExprNode):
5468     #  Abstract base class for sizeof(x) expression nodes.
5469
5470     type = PyrexTypes.c_size_t_type
5471
5472     def check_const(self):
5473         return True
5474
5475     def generate_result_code(self, code):
5476         pass
5477
5478
5479 class SizeofTypeNode(SizeofNode):
5480     #  C sizeof function applied to a type
5481     #
5482     #  base_type   CBaseTypeNode
5483     #  declarator  CDeclaratorNode
5484
5485     subexprs = []
5486     arg_type = None
5487
5488     def analyse_types(self, env):
5489         # we may have incorrectly interpreted a dotted name as a type rather than an attribute
5490         # this could be better handled by more uniformly treating types as runtime-available objects
5491         if 0 and self.base_type.module_path:
5492             path = self.base_type.module_path
5493             obj = env.lookup(path[0])
5494             if obj.as_module is None:
5495                 operand = NameNode(pos=self.pos, name=path[0])
5496                 for attr in path[1:]:
5497                     operand = AttributeNode(pos=self.pos, obj=operand, attribute=attr)
5498                 operand = AttributeNode(pos=self.pos, obj=operand, attribute=self.base_type.name)
5499                 self.operand = operand
5500                 self.__class__ = SizeofVarNode
5501                 self.analyse_types(env)
5502                 return
5503         if self.arg_type is None:
5504             base_type = self.base_type.analyse(env)
5505             _, arg_type = self.declarator.analyse(base_type, env)
5506             self.arg_type = arg_type
5507         self.check_type()
5508
5509     def check_type(self):
5510         arg_type = self.arg_type
5511         if arg_type.is_pyobject and not arg_type.is_extension_type:
5512             error(self.pos, "Cannot take sizeof Python object")
5513         elif arg_type.is_void:
5514             error(self.pos, "Cannot take sizeof void")
5515         elif not arg_type.is_complete():
5516             error(self.pos, "Cannot take sizeof incomplete type '%s'" % arg_type)
5517
5518     def calculate_result_code(self):
5519         if self.arg_type.is_extension_type:
5520             # the size of the pointer is boring
5521             # we want the size of the actual struct
5522             arg_code = self.arg_type.declaration_code("", deref=1)
5523         else:
5524             arg_code = self.arg_type.declaration_code("")
5525         return "(sizeof(%s))" % arg_code
5526
5527
5528 class SizeofVarNode(SizeofNode):
5529     #  C sizeof function applied to a variable
5530     #
5531     #  operand   ExprNode
5532
5533     subexprs = ['operand']
5534
5535     def analyse_types(self, env):
5536         # We may actually be looking at a type rather than a variable...
5537         # If we are, traditional analysis would fail...
5538         operand_as_type = self.operand.analyse_as_type(env)
5539         if operand_as_type:
5540             self.arg_type = operand_as_type
5541             self.__class__ = SizeofTypeNode
5542             self.check_type()
5543         else:
5544             self.operand.analyse_types(env)
5545
5546     def calculate_result_code(self):
5547         return "(sizeof(%s))" % self.operand.result()
5548
5549     def generate_result_code(self, code):
5550         pass
5551
5552 class TypeofNode(ExprNode):
5553     #  Compile-time type of an expression, as a string.
5554     #
5555     #  operand   ExprNode
5556     #  literal   StringNode # internal
5557
5558     literal = None
5559     type = py_object_type
5560
5561     subexprs = ['literal'] # 'operand' will be ignored after type analysis!
5562
5563     def analyse_types(self, env):
5564         self.operand.analyse_types(env)
5565         self.literal = StringNode(
5566             self.pos, value=StringEncoding.EncodedString(str(self.operand.type)))
5567         self.literal.analyse_types(env)
5568         self.literal = self.literal.coerce_to_pyobject(env)
5569
5570     def may_be_none(self):
5571         return False
5572
5573     def generate_evaluation_code(self, code):
5574         self.literal.generate_evaluation_code(code)
5575
5576     def calculate_result_code(self):
5577         return self.literal.calculate_result_code()
5578
5579 #-------------------------------------------------------------------
5580 #
5581 #  Binary operator nodes
5582 #
5583 #-------------------------------------------------------------------
5584
5585 def _not_in(x, seq):
5586     return x not in seq
5587
5588 compile_time_binary_operators = {
5589     '<': operator.lt,
5590     '<=': operator.le,
5591     '==': operator.eq,
5592     '!=': operator.ne,
5593     '>=': operator.ge,
5594     '>': operator.gt,
5595     'is': operator.is_,
5596     'is_not': operator.is_not,
5597     '+': operator.add,
5598     '&': operator.and_,
5599     '/': operator.truediv,
5600     '//': operator.floordiv,
5601     '<<': operator.lshift,
5602     '%': operator.mod,
5603     '*': operator.mul,
5604     '|': operator.or_,
5605     '**': operator.pow,
5606     '>>': operator.rshift,
5607     '-': operator.sub,
5608     '^': operator.xor,
5609     'in': operator.contains,
5610     'not_in': _not_in,
5611 }
5612
5613 def get_compile_time_binop(node):
5614     func = compile_time_binary_operators.get(node.operator)
5615     if not func:
5616         error(node.pos,
5617             "Binary '%s' not supported in compile-time expression"
5618                 % node.operator)
5619     return func
5620
5621 class BinopNode(ExprNode):
5622     #  operator     string
5623     #  operand1     ExprNode
5624     #  operand2     ExprNode
5625     #
5626     #  Processing during analyse_expressions phase:
5627     #
5628     #    analyse_c_operation
5629     #      Called when neither operand is a pyobject.
5630     #      - Check operand types and coerce if needed.
5631     #      - Determine result type and result code fragment.
5632     #      - Allocate temporary for result if needed.
5633
5634     subexprs = ['operand1', 'operand2']
5635     inplace = False
5636
5637     def calculate_constant_result(self):
5638         func = compile_time_binary_operators[self.operator]
5639         self.constant_result = func(
5640             self.operand1.constant_result,
5641             self.operand2.constant_result)
5642
5643     def compile_time_value(self, denv):
5644         func = get_compile_time_binop(self)
5645         operand1 = self.operand1.compile_time_value(denv)
5646         operand2 = self.operand2.compile_time_value(denv)
5647         try:
5648             return func(operand1, operand2)
5649         except Exception, e:
5650             self.compile_time_value_error(e)
5651
5652     def infer_type(self, env):
5653         return self.result_type(self.operand1.infer_type(env),
5654                                 self.operand2.infer_type(env))
5655
5656     def analyse_types(self, env):
5657         self.operand1.analyse_types(env)
5658         self.operand2.analyse_types(env)
5659         self.analyse_operation(env)
5660
5661     def analyse_operation(self, env):
5662         if self.is_py_operation():
5663             self.coerce_operands_to_pyobjects(env)
5664             self.type = self.result_type(self.operand1.type,
5665                                          self.operand2.type)
5666             assert self.type.is_pyobject
5667             self.is_temp = 1
5668         elif self.is_cpp_operation():
5669             self.analyse_cpp_operation(env)
5670         else:
5671             self.analyse_c_operation(env)
5672
5673     def is_py_operation(self):
5674         return self.is_py_operation_types(self.operand1.type, self.operand2.type)
5675
5676     def is_py_operation_types(self, type1, type2):
5677         return type1.is_pyobject or type2.is_pyobject
5678
5679     def is_cpp_operation(self):
5680         return (self.operand1.type.is_cpp_class
5681             or self.operand2.type.is_cpp_class)
5682
5683     def analyse_cpp_operation(self, env):
5684         type1 = self.operand1.type
5685         type2 = self.operand2.type
5686         entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
5687         if not entry:
5688             self.type_error()
5689             return
5690         func_type = entry.type
5691         if func_type.is_ptr:
5692             func_type = func_type.base_type
5693         if len(func_type.args) == 1:
5694             self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
5695         else:
5696             self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
5697             self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
5698         self.type = func_type.return_type
5699
5700     def result_type(self, type1, type2):
5701         if self.is_py_operation_types(type1, type2):
5702             if type2.is_string:
5703                 type2 = Builtin.bytes_type
5704             if type1.is_string:
5705                 type1 = Builtin.bytes_type
5706             elif self.operator == '%' \
5707                      and type1 in (Builtin.str_type, Builtin.unicode_type):
5708                 # note that  b'%s' % b'abc'  doesn't work in Py3
5709                 return type1
5710             if type1.is_builtin_type:
5711                 if type1 is type2:
5712                     if self.operator in '**%+|&^':
5713                         # FIXME: at least these operators should be safe - others?
5714                         return type1
5715                 elif self.operator == '*':
5716                     if type1 in (Builtin.bytes_type, Builtin.str_type, Builtin.unicode_type):
5717                         return type1
5718                     # multiplication of containers/numbers with an
5719                     # integer value always (?) returns the same type
5720                     if type2.is_int:
5721                         return type1
5722             elif type2.is_builtin_type and type1.is_int and self.operator == '*':
5723                 # multiplication of containers/numbers with an
5724                 # integer value always (?) returns the same type
5725                 return type2
5726             return py_object_type
5727         else:
5728             return self.compute_c_result_type(type1, type2)
5729
5730     def nogil_check(self, env):
5731         if self.is_py_operation():
5732             self.gil_error()
5733
5734     def coerce_operands_to_pyobjects(self, env):
5735         self.operand1 = self.operand1.coerce_to_pyobject(env)
5736         self.operand2 = self.operand2.coerce_to_pyobject(env)
5737
5738     def check_const(self):
5739         return self.operand1.check_const() and self.operand2.check_const()
5740
5741     def generate_result_code(self, code):
5742         #print "BinopNode.generate_result_code:", self.operand1, self.operand2 ###
5743         if self.operand1.type.is_pyobject:
5744             function = self.py_operation_function()
5745             if self.operator == '**':
5746                 extra_args = ", Py_None"
5747             else:
5748                 extra_args = ""
5749             code.putln(
5750                 "%s = %s(%s, %s%s); %s" % (
5751                     self.result(),
5752                     function,
5753                     self.operand1.py_result(),
5754                     self.operand2.py_result(),
5755                     extra_args,
5756                     code.error_goto_if_null(self.result(), self.pos)))
5757             code.put_gotref(self.py_result())
5758
5759     def type_error(self):
5760         if not (self.operand1.type.is_error
5761                 or self.operand2.type.is_error):
5762             error(self.pos, "Invalid operand types for '%s' (%s; %s)" %
5763                 (self.operator, self.operand1.type,
5764                     self.operand2.type))
5765         self.type = PyrexTypes.error_type
5766
5767
5768 class CBinopNode(BinopNode):
5769
5770     def analyse_types(self, env):
5771         BinopNode.analyse_types(self, env)
5772         if self.is_py_operation():
5773             self.type = PyrexTypes.error_type
5774
5775     def py_operation_function():
5776         return ""
5777
5778     def calculate_result_code(self):
5779         return "(%s %s %s)" % (
5780             self.operand1.result(),
5781             self.operator,
5782             self.operand2.result())
5783
5784
5785 def c_binop_constructor(operator):
5786     def make_binop_node(pos, **operands):
5787         return CBinopNode(pos, operator=operator, **operands)
5788     return make_binop_node
5789
5790 class NumBinopNode(BinopNode):
5791     #  Binary operation taking numeric arguments.
5792
5793     infix = True
5794
5795     def analyse_c_operation(self, env):
5796         type1 = self.operand1.type
5797         type2 = self.operand2.type
5798         self.type = self.compute_c_result_type(type1, type2)
5799         if not self.type:
5800             self.type_error()
5801             return
5802         if self.type.is_complex:
5803             self.infix = False
5804         if not self.infix or (type1.is_numeric and type2.is_numeric):
5805             self.operand1 = self.operand1.coerce_to(self.type, env)
5806             self.operand2 = self.operand2.coerce_to(self.type, env)
5807
5808     def compute_c_result_type(self, type1, type2):
5809         if self.c_types_okay(type1, type2):
5810             widest_type = PyrexTypes.widest_numeric_type(type1, type2)
5811             if widest_type is PyrexTypes.c_bint_type:
5812                 if self.operator not in '|^&':
5813                     # False + False == 0 # not False!
5814                     widest_type = PyrexTypes.c_int_type
5815             return widest_type
5816         else:
5817             return None
5818
5819     def get_constant_c_result_code(self):
5820         value1 = self.operand1.get_constant_c_result_code()
5821         value2 = self.operand2.get_constant_c_result_code()
5822         if value1 and value2:
5823             return "(%s %s %s)" % (value1, self.operator, value2)
5824         else:
5825             return None
5826
5827     def c_types_okay(self, type1, type2):
5828         #print "NumBinopNode.c_types_okay:", type1, type2 ###
5829         return (type1.is_numeric  or type1.is_enum) \
5830             and (type2.is_numeric  or type2.is_enum)
5831
5832     def calculate_result_code(self):
5833         if self.infix:
5834             return "(%s %s %s)" % (
5835                 self.operand1.result(),
5836                 self.operator,
5837                 self.operand2.result())
5838         else:
5839             func = self.type.binary_op(self.operator)
5840             if func is None:
5841                 error(self.pos, "binary operator %s not supported for %s" % (self.operator, self.type))
5842             return "%s(%s, %s)" % (
5843                 func,
5844                 self.operand1.result(),
5845                 self.operand2.result())
5846
5847     def is_py_operation_types(self, type1, type2):
5848         return (type1 is PyrexTypes.c_py_unicode_type or
5849                 type2 is PyrexTypes.c_py_unicode_type or
5850                 BinopNode.is_py_operation_types(self, type1, type2))
5851
5852     def py_operation_function(self):
5853         fuction = self.py_functions[self.operator]
5854         if self.inplace:
5855             fuction = fuction.replace('PyNumber_', 'PyNumber_InPlace')
5856         return fuction
5857
5858     py_functions = {
5859         "|":        "PyNumber_Or",
5860         "^":        "PyNumber_Xor",
5861         "&":        "PyNumber_And",
5862         "<<":       "PyNumber_Lshift",
5863         ">>":       "PyNumber_Rshift",
5864         "+":        "PyNumber_Add",
5865         "-":        "PyNumber_Subtract",
5866         "*":        "PyNumber_Multiply",
5867         "/":        "__Pyx_PyNumber_Divide",
5868         "//":       "PyNumber_FloorDivide",
5869         "%":        "PyNumber_Remainder",
5870         "**":       "PyNumber_Power"
5871     }
5872
5873 class IntBinopNode(NumBinopNode):
5874     #  Binary operation taking integer arguments.
5875
5876     def c_types_okay(self, type1, type2):
5877         #print "IntBinopNode.c_types_okay:", type1, type2 ###
5878         return (type1.is_int or type1.is_enum) \
5879             and (type2.is_int or type2.is_enum)
5880
5881
5882 class AddNode(NumBinopNode):
5883     #  '+' operator.
5884
5885     def is_py_operation_types(self, type1, type2):
5886         if type1.is_string and type2.is_string:
5887             return 1
5888         else:
5889             return NumBinopNode.is_py_operation_types(self, type1, type2)
5890
5891     def compute_c_result_type(self, type1, type2):
5892         #print "AddNode.compute_c_result_type:", type1, self.operator, type2 ###
5893         if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
5894             return type1
5895         elif (type2.is_ptr or type2.is_array) and (type1.is_int or type1.is_enum):
5896             return type2
5897         else:
5898             return NumBinopNode.compute_c_result_type(
5899                 self, type1, type2)
5900
5901
5902 class SubNode(NumBinopNode):
5903     #  '-' operator.
5904
5905     def compute_c_result_type(self, type1, type2):
5906         if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
5907             return type1
5908         elif (type1.is_ptr or type1.is_array) and (type2.is_ptr or type2.is_array):
5909             return PyrexTypes.c_int_type
5910         else:
5911             return NumBinopNode.compute_c_result_type(
5912                 self, type1, type2)
5913
5914
5915 class MulNode(NumBinopNode):
5916     #  '*' operator.
5917
5918     def is_py_operation_types(self, type1, type2):
5919         if (type1.is_string and type2.is_int) \
5920             or (type2.is_string and type1.is_int):
5921                 return 1
5922         else:
5923             return NumBinopNode.is_py_operation_types(self, type1, type2)
5924
5925
5926 class DivNode(NumBinopNode):
5927     #  '/' or '//' operator.
5928
5929     cdivision = None
5930     truedivision = None   # == "unknown" if operator == '/'
5931     ctruedivision = False
5932     cdivision_warnings = False
5933     zerodivision_check = None
5934
5935     def find_compile_time_binary_operator(self, op1, op2):
5936         func = compile_time_binary_operators[self.operator]
5937         if self.operator == '/' and self.truedivision is None:
5938             # => true div for floats, floor div for integers
5939             if isinstance(op1, (int,long)) and isinstance(op2, (int,long)):
5940                 func = compile_time_binary_operators['//']
5941         return func
5942
5943     def calculate_constant_result(self):
5944         op1 = self.operand1.constant_result
5945         op2 = self.operand2.constant_result
5946         func = self.find_compile_time_binary_operator(op1, op2)
5947         self.constant_result = func(
5948             self.operand1.constant_result,
5949             self.operand2.constant_result)
5950
5951     def compile_time_value(self, denv):
5952         operand1 = self.operand1.compile_time_value(denv)
5953         operand2 = self.operand2.compile_time_value(denv)
5954         try:
5955             func = self.find_compile_time_binary_operator(
5956                 self, operand1, operand2)
5957             return func(operand1, operand2)
5958         except Exception, e:
5959             self.compile_time_value_error(e)
5960
5961     def analyse_operation(self, env):
5962         if self.cdivision or env.directives['cdivision']:
5963             self.ctruedivision = False
5964         else:
5965             self.ctruedivision = self.truedivision
5966         NumBinopNode.analyse_operation(self, env)
5967         if self.is_cpp_operation():
5968             self.cdivision = True
5969         if not self.type.is_pyobject:
5970             self.zerodivision_check = (
5971                 self.cdivision is None and not env.directives['cdivision']
5972                 and (not self.operand2.has_constant_result() or
5973                      self.operand2.constant_result == 0))
5974             if self.zerodivision_check or env.directives['cdivision_warnings']:
5975                 # Need to check ahead of time to warn or raise zero division error
5976                 self.operand1 = self.operand1.coerce_to_simple(env)
5977                 self.operand2 = self.operand2.coerce_to_simple(env)
5978                 if env.nogil:
5979                     error(self.pos, "Pythonic division not allowed without gil, consider using cython.cdivision(True)")
5980
5981     def compute_c_result_type(self, type1, type2):
5982         if self.operator == '/' and self.ctruedivision:
5983             if not type1.is_float and not type2.is_float:
5984                 widest_type = PyrexTypes.widest_numeric_type(type1, PyrexTypes.c_double_type)
5985                 widest_type = PyrexTypes.widest_numeric_type(type2, widest_type)
5986                 return widest_type
5987         return NumBinopNode.compute_c_result_type(self, type1, type2)
5988
5989     def zero_division_message(self):
5990         if self.type.is_int:
5991             return "integer division or modulo by zero"
5992         else:
5993             return "float division"
5994
5995     def generate_evaluation_code(self, code):
5996         if not self.type.is_pyobject and not self.type.is_complex:
5997             if self.cdivision is None:
5998                 self.cdivision = (code.globalstate.directives['cdivision']
5999                                     or not self.type.signed
6000                                     or self.type.is_float)
6001             if not self.cdivision:
6002                 code.globalstate.use_utility_code(div_int_utility_code.specialize(self.type))
6003         NumBinopNode.generate_evaluation_code(self, code)
6004         self.generate_div_warning_code(code)
6005
6006     def generate_div_warning_code(self, code):
6007         if not self.type.is_pyobject:
6008             if self.zerodivision_check:
6009                 if not self.infix:
6010                     zero_test = "%s(%s)" % (self.type.unary_op('zero'), self.operand2.result())
6011                 else:
6012                     zero_test = "%s == 0" % self.operand2.result()
6013                 code.putln("if (unlikely(%s)) {" % zero_test)
6014                 code.putln('PyErr_Format(PyExc_ZeroDivisionError, "%s");' % self.zero_division_message())
6015                 code.putln(code.error_goto(self.pos))
6016                 code.putln("}")
6017                 if self.type.is_int and self.type.signed and self.operator != '%':
6018                     code.globalstate.use_utility_code(division_overflow_test_code)
6019                     code.putln("else if (sizeof(%s) == sizeof(long) && unlikely(%s == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(%s))) {" % (
6020                                     self.type.declaration_code(''),
6021                                     self.operand2.result(),
6022                                     self.operand1.result()))
6023                     code.putln('PyErr_Format(PyExc_OverflowError, "value too large to perform division");')
6024                     code.putln(code.error_goto(self.pos))
6025                     code.putln("}")
6026             if code.globalstate.directives['cdivision_warnings'] and self.operator != '/':
6027                 code.globalstate.use_utility_code(cdivision_warning_utility_code)
6028                 code.putln("if ((%s < 0) ^ (%s < 0)) {" % (
6029                                 self.operand1.result(),
6030                                 self.operand2.result()))
6031                 code.putln(code.set_error_info(self.pos));
6032                 code.put("if (__Pyx_cdivision_warning()) ")
6033                 code.put_goto(code.error_label)
6034                 code.putln("}")
6035
6036     def calculate_result_code(self):
6037         if self.type.is_complex:
6038             return NumBinopNode.calculate_result_code(self)
6039         elif self.type.is_float and self.operator == '//':
6040             return "floor(%s / %s)" % (
6041                 self.operand1.result(),
6042                 self.operand2.result())
6043         elif self.truedivision or self.cdivision:
6044             op1 = self.operand1.result()
6045             op2 = self.operand2.result()
6046             if self.truedivision:
6047                 if self.type != self.operand1.type:
6048                     op1 = self.type.cast_code(op1)
6049                 if self.type != self.operand2.type:
6050                     op2 = self.type.cast_code(op2)
6051             return "(%s / %s)" % (op1, op2)
6052         else:
6053             return "__Pyx_div_%s(%s, %s)" % (
6054                     self.type.specialization_name(),
6055                     self.operand1.result(),
6056                     self.operand2.result())
6057
6058
6059 class ModNode(DivNode):
6060     #  '%' operator.
6061
6062     def is_py_operation_types(self, type1, type2):
6063         return (type1.is_string
6064             or type2.is_string
6065             or NumBinopNode.is_py_operation_types(self, type1, type2))
6066
6067     def zero_division_message(self):
6068         if self.type.is_int:
6069             return "integer division or modulo by zero"
6070         else:
6071             return "float divmod()"
6072
6073     def generate_evaluation_code(self, code):
6074         if not self.type.is_pyobject:
6075             if self.cdivision is None:
6076                 self.cdivision = code.globalstate.directives['cdivision'] or not self.type.signed
6077             if not self.cdivision:
6078                 if self.type.is_int:
6079                     code.globalstate.use_utility_code(mod_int_utility_code.specialize(self.type))
6080                 else:
6081                     code.globalstate.use_utility_code(
6082                         mod_float_utility_code.specialize(self.type, math_h_modifier=self.type.math_h_modifier))
6083         NumBinopNode.generate_evaluation_code(self, code)
6084         self.generate_div_warning_code(code)
6085
6086     def calculate_result_code(self):
6087         if self.cdivision:
6088             if self.type.is_float:
6089                 return "fmod%s(%s, %s)" % (
6090                     self.type.math_h_modifier,
6091                     self.operand1.result(),
6092                     self.operand2.result())
6093             else:
6094                 return "(%s %% %s)" % (
6095                     self.operand1.result(),
6096                     self.operand2.result())
6097         else:
6098             return "__Pyx_mod_%s(%s, %s)" % (
6099                     self.type.specialization_name(),
6100                     self.operand1.result(),
6101                     self.operand2.result())
6102
6103 class PowNode(NumBinopNode):
6104     #  '**' operator.
6105
6106     def analyse_c_operation(self, env):
6107         NumBinopNode.analyse_c_operation(self, env)
6108         if self.type.is_complex:
6109             if self.type.real_type.is_float:
6110                 self.operand1 = self.operand1.coerce_to(self.type, env)
6111                 self.operand2 = self.operand2.coerce_to(self.type, env)
6112                 self.pow_func = "__Pyx_c_pow" + self.type.real_type.math_h_modifier
6113             else:
6114                 error(self.pos, "complex int powers not supported")
6115                 self.pow_func = "<error>"
6116         elif self.type.is_float:
6117             self.pow_func = "pow" + self.type.math_h_modifier
6118         else:
6119             self.pow_func = "__Pyx_pow_%s" % self.type.declaration_code('').replace(' ', '_')
6120             env.use_utility_code(
6121                     int_pow_utility_code.specialize(func_name=self.pow_func,
6122                                                 type=self.type.declaration_code('')))
6123
6124     def calculate_result_code(self):
6125         # Work around MSVC overloading ambiguity.
6126         def typecast(operand):
6127             if self.type == operand.type:
6128                 return operand.result()
6129             else:
6130                 return self.type.cast_code(operand.result())
6131         return "%s(%s, %s)" % (
6132             self.pow_func,
6133             typecast(self.operand1),
6134             typecast(self.operand2))
6135
6136
6137 # Note: This class is temporarily "shut down" into an ineffective temp
6138 # allocation mode.
6139 #
6140 # More sophisticated temp reuse was going on before, one could have a
6141 # look at adding this again after /all/ classes are converted to the
6142 # new temp scheme. (The temp juggling cannot work otherwise).
6143 class BoolBinopNode(ExprNode):
6144     #  Short-circuiting boolean operation.
6145     #
6146     #  operator     string
6147     #  operand1     ExprNode
6148     #  operand2     ExprNode
6149
6150     subexprs = ['operand1', 'operand2']
6151
6152     def infer_type(self, env):
6153         type1 = self.operand1.infer_type(env)
6154         type2 = self.operand2.infer_type(env)
6155         return PyrexTypes.independent_spanning_type(type1, type2)
6156
6157     def may_be_none(self):
6158         if self.operator == 'or':
6159             return self.operand2.may_be_none()
6160         else:
6161             return self.operand1.may_be_none() or self.operand2.may_be_none()
6162
6163     def calculate_constant_result(self):
6164         if self.operator == 'and':
6165             self.constant_result = \
6166                 self.operand1.constant_result and \
6167                 self.operand2.constant_result
6168         else:
6169             self.constant_result = \
6170                 self.operand1.constant_result or \
6171                 self.operand2.constant_result
6172
6173     def compile_time_value(self, denv):
6174         if self.operator == 'and':
6175             return self.operand1.compile_time_value(denv) \
6176                 and self.operand2.compile_time_value(denv)
6177         else:
6178             return self.operand1.compile_time_value(denv) \
6179                 or self.operand2.compile_time_value(denv)
6180
6181     def coerce_to_boolean(self, env):
6182         return BoolBinopNode(
6183             self.pos,
6184             operator = self.operator,
6185             operand1 = self.operand1.coerce_to_boolean(env),
6186             operand2 = self.operand2.coerce_to_boolean(env),
6187             type = PyrexTypes.c_bint_type,
6188             is_temp = self.is_temp)
6189
6190     def analyse_types(self, env):
6191         self.operand1.analyse_types(env)
6192         self.operand2.analyse_types(env)
6193         self.type = PyrexTypes.independent_spanning_type(self.operand1.type, self.operand2.type)
6194         self.operand1 = self.operand1.coerce_to(self.type, env)
6195         self.operand2 = self.operand2.coerce_to(self.type, env)
6196
6197         # For what we're about to do, it's vital that
6198         # both operands be temp nodes.
6199         self.operand1 = self.operand1.coerce_to_simple(env)
6200         self.operand2 = self.operand2.coerce_to_simple(env)
6201         self.is_temp = 1
6202
6203     gil_message = "Truth-testing Python object"
6204
6205     def check_const(self):
6206         return self.operand1.check_const() and self.operand2.check_const()
6207
6208     def generate_evaluation_code(self, code):
6209         code.mark_pos(self.pos)
6210         self.operand1.generate_evaluation_code(code)
6211         test_result, uses_temp = self.generate_operand1_test(code)
6212         if self.operator == 'and':
6213             sense = ""
6214         else:
6215             sense = "!"
6216         code.putln(
6217             "if (%s%s) {" % (
6218                 sense,
6219                 test_result))
6220         if uses_temp:
6221             code.funcstate.release_temp(test_result)
6222         self.operand1.generate_disposal_code(code)
6223         self.operand2.generate_evaluation_code(code)
6224         self.allocate_temp_result(code)
6225         self.operand2.make_owned_reference(code)
6226         code.putln("%s = %s;" % (self.result(), self.operand2.result()))
6227         self.operand2.generate_post_assignment_code(code)
6228         self.operand2.free_temps(code)
6229         code.putln("} else {")
6230         self.operand1.make_owned_reference(code)
6231         code.putln("%s = %s;" % (self.result(), self.operand1.result()))
6232         self.operand1.generate_post_assignment_code(code)
6233         self.operand1.free_temps(code)
6234         code.putln("}")
6235
6236     def generate_operand1_test(self, code):
6237         #  Generate code to test the truth of the first operand.
6238         if self.type.is_pyobject:
6239             test_result = code.funcstate.allocate_temp(PyrexTypes.c_bint_type,
6240                                                        manage_ref=False)
6241             code.putln(
6242                 "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
6243                     test_result,
6244                     self.operand1.py_result(),
6245                     code.error_goto_if_neg(test_result, self.pos)))
6246         else:
6247             test_result = self.operand1.result()
6248         return (test_result, self.type.is_pyobject)
6249
6250
6251 class CondExprNode(ExprNode):
6252     #  Short-circuiting conditional expression.
6253     #
6254     #  test        ExprNode
6255     #  true_val    ExprNode
6256     #  false_val   ExprNode
6257
6258     true_val = None
6259     false_val = None
6260
6261     subexprs = ['test', 'true_val', 'false_val']
6262
6263     def type_dependencies(self, env):
6264         return self.true_val.type_dependencies(env) + self.false_val.type_dependencies(env)
6265
6266     def infer_type(self, env):
6267         return PyrexTypes.independent_spanning_type(self.true_val.infer_type(env),
6268                                                     self.false_val.infer_type(env))
6269
6270     def calculate_constant_result(self):
6271         if self.test.constant_result:
6272             self.constant_result = self.true_val.constant_result
6273         else:
6274             self.constant_result = self.false_val.constant_result
6275
6276     def analyse_types(self, env):
6277         self.test.analyse_types(env)
6278         self.test = self.test.coerce_to_boolean(env)
6279         self.true_val.analyse_types(env)
6280         self.false_val.analyse_types(env)
6281         self.type = PyrexTypes.independent_spanning_type(self.true_val.type, self.false_val.type)
6282         if self.true_val.type.is_pyobject or self.false_val.type.is_pyobject:
6283             self.true_val = self.true_val.coerce_to(self.type, env)
6284             self.false_val = self.false_val.coerce_to(self.type, env)
6285         self.is_temp = 1
6286         if self.type == PyrexTypes.error_type:
6287             self.type_error()
6288
6289     def type_error(self):
6290         if not (self.true_val.type.is_error or self.false_val.type.is_error):
6291             error(self.pos, "Incompatable types in conditional expression (%s; %s)" %
6292                 (self.true_val.type, self.false_val.type))
6293         self.type = PyrexTypes.error_type
6294
6295     def check_const(self):
6296         return (self.test.check_const()
6297             and self.true_val.check_const()
6298             and self.false_val.check_const())
6299
6300     def generate_evaluation_code(self, code):
6301         # Because subexprs may not be evaluated we can use a more optimal
6302         # subexpr allocation strategy than the default, so override evaluation_code.
6303
6304         code.mark_pos(self.pos)
6305         self.allocate_temp_result(code)
6306         self.test.generate_evaluation_code(code)
6307         code.putln("if (%s) {" % self.test.result() )
6308         self.eval_and_get(code, self.true_val)
6309         code.putln("} else {")
6310         self.eval_and_get(code, self.false_val)
6311         code.putln("}")
6312         self.test.generate_disposal_code(code)
6313         self.test.free_temps(code)
6314
6315     def eval_and_get(self, code, expr):
6316         expr.generate_evaluation_code(code)
6317         expr.make_owned_reference(code)
6318         code.putln("%s = %s;" % (self.result(), expr.result()))
6319         expr.generate_post_assignment_code(code)
6320         expr.free_temps(code)
6321
6322 richcmp_constants = {
6323     "<" : "Py_LT",
6324     "<=": "Py_LE",
6325     "==": "Py_EQ",
6326     "!=": "Py_NE",
6327     "<>": "Py_NE",
6328     ">" : "Py_GT",
6329     ">=": "Py_GE",
6330 }
6331
6332 class CmpNode(object):
6333     #  Mixin class containing code common to PrimaryCmpNodes
6334     #  and CascadedCmpNodes.
6335
6336     special_bool_cmp_function = None
6337
6338     def infer_type(self, env):
6339         # TODO: Actually implement this (after merging with -unstable).
6340         return py_object_type
6341
6342     def calculate_cascaded_constant_result(self, operand1_result):
6343         func = compile_time_binary_operators[self.operator]
6344         operand2_result = self.operand2.constant_result
6345         result = func(operand1_result, operand2_result)
6346         if self.cascade:
6347             self.cascade.calculate_cascaded_constant_result(operand2_result)
6348             if self.cascade.constant_result:
6349                 self.constant_result = result and self.cascade.constant_result
6350         else:
6351             self.constant_result = result
6352
6353     def cascaded_compile_time_value(self, operand1, denv):
6354         func = get_compile_time_binop(self)
6355         operand2 = self.operand2.compile_time_value(denv)
6356         try:
6357             result = func(operand1, operand2)
6358         except Exception, e:
6359             self.compile_time_value_error(e)
6360             result = None
6361         if result:
6362             cascade = self.cascade
6363             if cascade:
6364                 # FIXME: I bet this must call cascaded_compile_time_value()
6365                 result = result and cascade.cascaded_compile_time_value(operand2, denv)
6366         return result
6367
6368     def is_cpp_comparison(self):
6369         return self.operand1.type.is_cpp_class or self.operand2.type.is_cpp_class
6370
6371     def find_common_int_type(self, env, op, operand1, operand2):
6372         # type1 != type2 and at least one of the types is not a C int
6373         type1 = operand1.type
6374         type2 = operand2.type
6375         type1_can_be_int = False
6376         type2_can_be_int = False
6377
6378         if isinstance(operand1, (StringNode, BytesNode, UnicodeNode)) \
6379                and operand1.can_coerce_to_char_literal():
6380             type1_can_be_int = True
6381         if isinstance(operand2, (StringNode, BytesNode, UnicodeNode)) \
6382                  and operand2.can_coerce_to_char_literal():
6383             type2_can_be_int = True
6384
6385         if type1.is_int:
6386             if type2_can_be_int:
6387                 return type1
6388         elif type2.is_int:
6389             if type1_can_be_int:
6390                 return type2
6391         elif type1_can_be_int:
6392             if type2_can_be_int:
6393                 return PyrexTypes.c_uchar_type
6394
6395         return None
6396
6397     def find_common_type(self, env, op, operand1, common_type=None):
6398         operand2 = self.operand2
6399         type1 = operand1.type
6400         type2 = operand2.type
6401
6402         new_common_type = None
6403
6404         # catch general errors
6405         if type1 == str_type and (type2.is_string or type2 in (bytes_type, unicode_type)) or \
6406                type2 == str_type and (type1.is_string or type1 in (bytes_type, unicode_type)):
6407             error(self.pos, "Comparisons between bytes/unicode and str are not portable to Python 3")
6408             new_common_type = error_type
6409
6410         # try to use numeric comparisons where possible
6411         elif type1.is_complex or type2.is_complex:
6412             if op not in ('==', '!='):
6413                 error(self.pos, "complex types are unordered")
6414                 new_common_type = error_type
6415             if type1.is_pyobject:
6416                 new_common_type = type1
6417             elif type2.is_pyobject:
6418                 new_common_type = type2
6419             else:
6420                 new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
6421         elif type1.is_numeric and type2.is_numeric:
6422             new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
6423         elif common_type is None or not common_type.is_pyobject:
6424             new_common_type = self.find_common_int_type(env, op, operand1, operand2)
6425
6426         if new_common_type is None:
6427             # fall back to generic type compatibility tests
6428             if type1 == type2:
6429                 new_common_type = type1
6430             elif type1.is_pyobject or type2.is_pyobject:
6431                 if type2.is_numeric or type2.is_string:
6432                     if operand2.check_for_coercion_error(type1):
6433                         new_common_type = error_type
6434                     else:
6435                         new_common_type = py_object_type
6436                 elif type1.is_numeric or type1.is_string:
6437                     if operand1.check_for_coercion_error(type2):
6438                         new_common_type = error_type
6439                     else:
6440                         new_common_type = py_object_type
6441                 elif py_object_type.assignable_from(type1) and py_object_type.assignable_from(type2):
6442                     new_common_type = py_object_type
6443                 else:
6444                     # one Python type and one non-Python type, not assignable
6445                     self.invalid_types_error(operand1, op, operand2)
6446                     new_common_type = error_type
6447             elif type1.assignable_from(type2):
6448                 new_common_type = type1
6449             elif type2.assignable_from(type1):
6450                 new_common_type = type2
6451             else:
6452                 # C types that we couldn't handle up to here are an error
6453                 self.invalid_types_error(operand1, op, operand2)
6454                 new_common_type = error_type
6455
6456         if new_common_type.is_string and (isinstance(operand1, BytesNode) or
6457                                           isinstance(operand2, BytesNode)):
6458             # special case when comparing char* to bytes literal: must
6459             # compare string values!
6460             new_common_type = bytes_type
6461
6462         # recursively merge types
6463         if common_type is None or new_common_type.is_error:
6464             common_type = new_common_type
6465         else:
6466             # we could do a lot better by splitting the comparison
6467             # into a non-Python part and a Python part, but this is
6468             # safer for now
6469             common_type = PyrexTypes.spanning_type(common_type, new_common_type)
6470
6471         if self.cascade:
6472             common_type = self.cascade.find_common_type(env, self.operator, operand2, common_type)
6473
6474         return common_type
6475
6476     def invalid_types_error(self, operand1, op, operand2):
6477         error(self.pos, "Invalid types for '%s' (%s, %s)" %
6478               (op, operand1.type, operand2.type))
6479
6480     def is_python_comparison(self):
6481         return (not self.is_ptr_contains()
6482             and not self.is_c_string_contains()
6483             and (self.has_python_operands()
6484                  or (self.cascade and self.cascade.is_python_comparison())
6485                  or self.operator in ('in', 'not_in')))
6486
6487     def coerce_operands_to(self, dst_type, env):
6488         operand2 = self.operand2
6489         if operand2.type != dst_type:
6490             self.operand2 = operand2.coerce_to(dst_type, env)
6491         if self.cascade:
6492             self.cascade.coerce_operands_to(dst_type, env)
6493
6494     def is_python_result(self):
6495         return ((self.has_python_operands() and
6496                  self.special_bool_cmp_function is None and
6497                  self.operator not in ('is', 'is_not', 'in', 'not_in') and
6498                  not self.is_c_string_contains() and
6499                  not self.is_ptr_contains())
6500             or (self.cascade and self.cascade.is_python_result()))
6501
6502     def is_c_string_contains(self):
6503         return self.operator in ('in', 'not_in') and \
6504                ((self.operand1.type.is_int
6505                  and (self.operand2.type.is_string or self.operand2.type is bytes_type)) or
6506                 (self.operand1.type is PyrexTypes.c_py_unicode_type
6507                  and self.operand2.type is unicode_type))
6508
6509     def is_ptr_contains(self):
6510         if self.operator in ('in', 'not_in'):
6511             container_type = self.operand2.type
6512             return (container_type.is_ptr or container_type.is_array) \
6513                 and not container_type.is_string
6514
6515     def find_special_bool_compare_function(self, env):
6516         if self.operator in ('==', '!='):
6517             type1, type2 = self.operand1.type, self.operand2.type
6518             if type1.is_pyobject and type2.is_pyobject:
6519                 if type1 is Builtin.unicode_type or type2 is Builtin.unicode_type:
6520                     env.use_utility_code(pyunicode_equals_utility_code)
6521                     self.special_bool_cmp_function = "__Pyx_PyUnicode_Equals"
6522                     return True
6523         return False
6524
6525     def generate_operation_code(self, code, result_code,
6526             operand1, op , operand2):
6527         if self.type.is_pyobject:
6528             coerce_result = "__Pyx_PyBool_FromLong"
6529         else:
6530             coerce_result = ""
6531         if 'not' in op:
6532             negation = "!"
6533         else:
6534             negation = ""
6535         if self.special_bool_cmp_function:
6536             if operand1.type.is_pyobject:
6537                 result1 = operand1.py_result()
6538             else:
6539                 result1 = operand1.result()
6540             if operand2.type.is_pyobject:
6541                 result2 = operand2.py_result()
6542             else:
6543                 result2 = operand2.result()
6544             code.putln("%s = %s(%s, %s, %s); %s" % (
6545                 result_code,
6546                 self.special_bool_cmp_function,
6547                 result1,
6548                 result2,
6549                 richcmp_constants[op],
6550                 code.error_goto_if_neg(result_code, self.pos)))
6551         elif op == 'in' or op == 'not_in':
6552             code.globalstate.use_utility_code(contains_utility_code)
6553             if self.type.is_pyobject:
6554                 coerce_result = "__Pyx_PyBoolOrNull_FromLong"
6555             if op == 'not_in':
6556                 negation = "__Pyx_NegateNonNeg"
6557             if operand2.type is dict_type:
6558                 method = "PyDict_Contains"
6559             else:
6560                 method = "PySequence_Contains"
6561             if self.type.is_pyobject:
6562                 error_clause = code.error_goto_if_null
6563                 got_ref = "__Pyx_XGOTREF(%s); " % result_code
6564             else:
6565                 error_clause = code.error_goto_if_neg
6566                 got_ref = ""
6567             code.putln(
6568                 "%s = %s(%s(%s(%s, %s))); %s%s" % (
6569                     result_code,
6570                     coerce_result,
6571                     negation,
6572                     method,
6573                     operand2.py_result(),
6574                     operand1.py_result(),
6575                     got_ref,
6576                     error_clause(result_code, self.pos)))
6577         elif (operand1.type.is_pyobject
6578             and op not in ('is', 'is_not')):
6579                 code.putln("%s = PyObject_RichCompare(%s, %s, %s); %s" % (
6580                         result_code,
6581                         operand1.py_result(),
6582                         operand2.py_result(),
6583                         richcmp_constants[op],
6584                         code.error_goto_if_null(result_code, self.pos)))
6585                 code.put_gotref(result_code)
6586         elif operand1.type.is_complex:
6587             if op == "!=":
6588                 negation = "!"
6589             else:
6590                 negation = ""
6591             code.putln("%s = %s(%s%s(%s, %s));" % (
6592                 result_code,
6593                 coerce_result,
6594                 negation,
6595                 operand1.type.unary_op('eq'),
6596                 operand1.result(),
6597                 operand2.result()))
6598         else:
6599             type1 = operand1.type
6600             type2 = operand2.type
6601             if (type1.is_extension_type or type2.is_extension_type) \
6602                     and not type1.same_as(type2):
6603                 common_type = py_object_type
6604             elif type1.is_numeric:
6605                 common_type = PyrexTypes.widest_numeric_type(type1, type2)
6606             else:
6607                 common_type = type1
6608             code1 = operand1.result_as(common_type)
6609             code2 = operand2.result_as(common_type)
6610             code.putln("%s = %s(%s %s %s);" % (
6611                 result_code,
6612                 coerce_result,
6613                 code1,
6614                 self.c_operator(op),
6615                 code2))
6616
6617     def c_operator(self, op):
6618         if op == 'is':
6619             return "=="
6620         elif op == 'is_not':
6621             return "!="
6622         else:
6623             return op
6624
6625 contains_utility_code = UtilityCode(
6626 proto="""
6627 static CYTHON_INLINE long __Pyx_NegateNonNeg(long b) { return unlikely(b < 0) ? b : !b; }
6628 static CYTHON_INLINE PyObject* __Pyx_PyBoolOrNull_FromLong(long b) {
6629     return unlikely(b < 0) ? NULL : __Pyx_PyBool_FromLong(b);
6630 }
6631 """)
6632
6633 char_in_bytes_utility_code = UtilityCode(
6634 proto="""
6635 static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); /*proto*/
6636 """,
6637 impl="""
6638 static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) {
6639     const Py_ssize_t length = PyBytes_GET_SIZE(bytes);
6640     char* char_start = PyBytes_AS_STRING(bytes);
6641     char* pos;
6642     for (pos=char_start; pos < char_start+length; pos++) {
6643         if (character == pos[0]) return 1;
6644     }
6645     return 0;
6646 }
6647 """)
6648
6649 pyunicode_in_unicode_utility_code = UtilityCode(
6650 proto="""
6651 static CYTHON_INLINE int __Pyx_UnicodeContains(PyObject* unicode, Py_UNICODE character); /*proto*/
6652 """,
6653 impl="""
6654 static CYTHON_INLINE int __Pyx_UnicodeContains(PyObject* unicode, Py_UNICODE character) {
6655     const Py_ssize_t length = PyUnicode_GET_SIZE(unicode);
6656     Py_UNICODE* char_start = PyUnicode_AS_UNICODE(unicode);
6657     Py_UNICODE* pos;
6658     for (pos=char_start; pos < char_start+length; pos++) {
6659         if (character == pos[0]) return 1;
6660     }
6661     return 0;
6662 }
6663 """)
6664
6665 pyunicode_equals_utility_code = UtilityCode(
6666 proto="""
6667 static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/
6668 """,
6669 impl="""
6670 static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) {
6671     if (s1 == s2) {   /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */
6672         return (equals == Py_EQ);
6673     } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) {
6674         if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) {
6675             return (equals == Py_NE);
6676         } else if (PyUnicode_GET_SIZE(s1) == 1) {
6677             if (equals == Py_EQ)
6678                 return (PyUnicode_AS_UNICODE(s1)[0] == PyUnicode_AS_UNICODE(s2)[0]);
6679             else
6680                 return (PyUnicode_AS_UNICODE(s1)[0] != PyUnicode_AS_UNICODE(s2)[0]);
6681         } else {
6682             int result = PyUnicode_Compare(s1, s2);
6683             if ((result == -1) && unlikely(PyErr_Occurred()))
6684                 return -1;
6685             return (equals == Py_EQ) ? (result == 0) : (result != 0);
6686         }
6687     } else if ((s1 == Py_None) & (s2 == Py_None)) {
6688         return (equals == Py_EQ);
6689     } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) {
6690         return (equals == Py_NE);
6691     } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) {
6692         return (equals == Py_NE);
6693     } else {
6694         int result;
6695         PyObject* py_result = PyObject_RichCompare(s1, s2, equals);
6696         if (!py_result)
6697             return -1;
6698         result = __Pyx_PyObject_IsTrue(py_result);
6699         Py_DECREF(py_result);
6700         return result;
6701     }
6702 }
6703 """)
6704
6705
6706 class PrimaryCmpNode(ExprNode, CmpNode):
6707     #  Non-cascaded comparison or first comparison of
6708     #  a cascaded sequence.
6709     #
6710     #  operator      string
6711     #  operand1      ExprNode
6712     #  operand2      ExprNode
6713     #  cascade       CascadedCmpNode
6714
6715     #  We don't use the subexprs mechanism, because
6716     #  things here are too complicated for it to handle.
6717     #  Instead, we override all the framework methods
6718     #  which use it.
6719
6720     child_attrs = ['operand1', 'operand2', 'cascade']
6721
6722     cascade = None
6723
6724     def infer_type(self, env):
6725         # TODO: Actually implement this (after merging with -unstable).
6726         return py_object_type
6727
6728     def type_dependencies(self, env):
6729         return ()
6730
6731     def calculate_constant_result(self):
6732         self.calculate_cascaded_constant_result(self.operand1.constant_result)
6733
6734     def compile_time_value(self, denv):
6735         operand1 = self.operand1.compile_time_value(denv)
6736         return self.cascaded_compile_time_value(operand1, denv)
6737
6738     def analyse_types(self, env):
6739         self.operand1.analyse_types(env)
6740         self.operand2.analyse_types(env)
6741         if self.is_cpp_comparison():
6742             self.analyse_cpp_comparison(env)
6743             if self.cascade:
6744                 error(self.pos, "Cascading comparison not yet supported for cpp types.")
6745             return
6746         if self.cascade:
6747             self.cascade.analyse_types(env)
6748
6749         if self.operator in ('in', 'not_in'):
6750             if self.is_c_string_contains():
6751                 self.is_pycmp = False
6752                 common_type = None
6753                 if self.cascade:
6754                     error(self.pos, "Cascading comparison not yet supported for 'int_val in string'.")
6755                     return
6756                 if self.operand2.type is unicode_type:
6757                     env.use_utility_code(pyunicode_in_unicode_utility_code)
6758                 else:
6759                     if self.operand1.type is PyrexTypes.c_uchar_type:
6760                         self.operand1 = self.operand1.coerce_to(PyrexTypes.c_char_type, env)
6761                     if self.operand2.type is not bytes_type:
6762                         self.operand2 = self.operand2.coerce_to(bytes_type, env)
6763                     env.use_utility_code(char_in_bytes_utility_code)
6764                 self.operand2 = self.operand2.as_none_safe_node(
6765                     "argument of type 'NoneType' is not iterable")
6766             elif self.is_ptr_contains():
6767                 if self.cascade:
6768                     error(self.pos, "Cascading comparison not yet supported for 'val in sliced pointer'.")
6769                 self.type = PyrexTypes.c_bint_type
6770                 # Will be transformed by IterationTransform
6771                 return
6772             else:
6773                 if self.operand2.type is dict_type:
6774                     self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
6775                 common_type = py_object_type
6776                 self.is_pycmp = True
6777         elif self.find_special_bool_compare_function(env):
6778             common_type = None # if coercion needed, the method call above has already done it
6779             self.is_pycmp = False # result is bint
6780             self.is_temp = True # must check for error return
6781         else:
6782             common_type = self.find_common_type(env, self.operator, self.operand1)
6783             self.is_pycmp = common_type.is_pyobject
6784
6785         if common_type is not None and not common_type.is_error:
6786             if self.operand1.type != common_type:
6787                 self.operand1 = self.operand1.coerce_to(common_type, env)
6788             self.coerce_operands_to(common_type, env)
6789
6790         if self.cascade:
6791             self.operand2 = self.operand2.coerce_to_simple(env)
6792             self.cascade.coerce_cascaded_operands_to_temp(env)
6793         if self.is_python_result():
6794             self.type = PyrexTypes.py_object_type
6795         else:
6796             self.type = PyrexTypes.c_bint_type
6797         cdr = self.cascade
6798         while cdr:
6799             cdr.type = self.type
6800             cdr = cdr.cascade
6801         if self.is_pycmp or self.cascade:
6802             self.is_temp = 1
6803
6804     def analyse_cpp_comparison(self, env):
6805         type1 = self.operand1.type
6806         type2 = self.operand2.type
6807         entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
6808         if entry is None:
6809             error(self.pos, "Invalid types for '%s' (%s, %s)" %
6810                 (self.operator, type1, type2))
6811             self.type = PyrexTypes.error_type
6812             self.result_code = "<error>"
6813             return
6814         func_type = entry.type
6815         if func_type.is_ptr:
6816             func_type = func_type.base_type
6817         if len(func_type.args) == 1:
6818             self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
6819         else:
6820             self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
6821             self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
6822         self.type = func_type.return_type
6823
6824     def has_python_operands(self):
6825         return (self.operand1.type.is_pyobject
6826             or self.operand2.type.is_pyobject)
6827
6828     def check_const(self):
6829         if self.cascade:
6830             self.not_const()
6831             return False
6832         else:
6833             return self.operand1.check_const() and self.operand2.check_const()
6834
6835     def calculate_result_code(self):
6836         if self.operand1.type.is_complex:
6837             if self.operator == "!=":
6838                 negation = "!"
6839             else:
6840                 negation = ""
6841             return "(%s%s(%s, %s))" % (
6842                 negation,
6843                 self.operand1.type.binary_op('=='),
6844                 self.operand1.result(),
6845                 self.operand2.result())
6846         elif self.is_c_string_contains():
6847             if self.operand2.type is bytes_type:
6848                 method = "__Pyx_BytesContains"
6849             else:
6850                 method = "__Pyx_UnicodeContains"
6851             if self.operator == "not_in":
6852                 negation = "!"
6853             else:
6854                 negation = ""
6855             return "(%s%s(%s, %s))" % (
6856                 negation,
6857                 method,
6858                 self.operand2.result(),
6859                 self.operand1.result())
6860         else:
6861             return "(%s %s %s)" % (
6862                 self.operand1.result(),
6863                 self.c_operator(self.operator),
6864                 self.operand2.result())
6865
6866     def generate_evaluation_code(self, code):
6867         self.operand1.generate_evaluation_code(code)
6868         self.operand2.generate_evaluation_code(code)
6869         if self.is_temp:
6870             self.allocate_temp_result(code)
6871             self.generate_operation_code(code, self.result(),
6872                 self.operand1, self.operator, self.operand2)
6873             if self.cascade:
6874                 self.cascade.generate_evaluation_code(code,
6875                     self.result(), self.operand2)
6876             self.operand1.generate_disposal_code(code)
6877             self.operand1.free_temps(code)
6878             self.operand2.generate_disposal_code(code)
6879             self.operand2.free_temps(code)
6880
6881     def generate_subexpr_disposal_code(self, code):
6882         #  If this is called, it is a non-cascaded cmp,
6883         #  so only need to dispose of the two main operands.
6884         self.operand1.generate_disposal_code(code)
6885         self.operand2.generate_disposal_code(code)
6886
6887     def free_subexpr_temps(self, code):
6888         #  If this is called, it is a non-cascaded cmp,
6889         #  so only need to dispose of the two main operands.
6890         self.operand1.free_temps(code)
6891         self.operand2.free_temps(code)
6892
6893     def annotate(self, code):
6894         self.operand1.annotate(code)
6895         self.operand2.annotate(code)
6896         if self.cascade:
6897             self.cascade.annotate(code)
6898
6899
6900 class CascadedCmpNode(Node, CmpNode):
6901     #  A CascadedCmpNode is not a complete expression node. It
6902     #  hangs off the side of another comparison node, shares
6903     #  its left operand with that node, and shares its result
6904     #  with the PrimaryCmpNode at the head of the chain.
6905     #
6906     #  operator      string
6907     #  operand2      ExprNode
6908     #  cascade       CascadedCmpNode
6909
6910     child_attrs = ['operand2', 'cascade']
6911
6912     cascade = None
6913     constant_result = constant_value_not_set # FIXME: where to calculate this?
6914
6915     def infer_type(self, env):
6916         # TODO: Actually implement this (after merging with -unstable).
6917         return py_object_type
6918
6919     def type_dependencies(self, env):
6920         return ()
6921
6922     def has_constant_result(self):
6923         return self.constant_result is not constant_value_not_set and \
6924                self.constant_result is not not_a_constant
6925
6926     def analyse_types(self, env):
6927         self.operand2.analyse_types(env)
6928         if self.cascade:
6929             self.cascade.analyse_types(env)
6930
6931     def has_python_operands(self):
6932         return self.operand2.type.is_pyobject
6933
6934     def coerce_operands_to_pyobjects(self, env):
6935         self.operand2 = self.operand2.coerce_to_pyobject(env)
6936         if self.operand2.type is dict_type and self.operator in ('in', 'not_in'):
6937             self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
6938         if self.cascade:
6939             self.cascade.coerce_operands_to_pyobjects(env)
6940
6941     def coerce_cascaded_operands_to_temp(self, env):
6942         if self.cascade:
6943             #self.operand2 = self.operand2.coerce_to_temp(env) #CTT
6944             self.operand2 = self.operand2.coerce_to_simple(env)
6945             self.cascade.coerce_cascaded_operands_to_temp(env)
6946
6947     def generate_evaluation_code(self, code, result, operand1):
6948         if self.type.is_pyobject:
6949             code.putln("if (__Pyx_PyObject_IsTrue(%s)) {" % result)
6950             code.put_decref(result, self.type)
6951         else:
6952             code.putln("if (%s) {" % result)
6953         self.operand2.generate_evaluation_code(code)
6954         self.generate_operation_code(code, result,
6955             operand1, self.operator, self.operand2)
6956         if self.cascade:
6957             self.cascade.generate_evaluation_code(
6958                 code, result, self.operand2)
6959         # Cascaded cmp result is always temp
6960         self.operand2.generate_disposal_code(code)
6961         self.operand2.free_temps(code)
6962         code.putln("}")
6963
6964     def annotate(self, code):
6965         self.operand2.annotate(code)
6966         if self.cascade:
6967             self.cascade.annotate(code)
6968
6969
6970 binop_node_classes = {
6971     "or":       BoolBinopNode,
6972     "and":      BoolBinopNode,
6973     "|":        IntBinopNode,
6974     "^":        IntBinopNode,
6975     "&":        IntBinopNode,
6976     "<<":       IntBinopNode,
6977     ">>":       IntBinopNode,
6978     "+":        AddNode,
6979     "-":        SubNode,
6980     "*":        MulNode,
6981     "/":        DivNode,
6982     "//":       DivNode,
6983     "%":        ModNode,
6984     "**":       PowNode
6985 }
6986
6987 def binop_node(pos, operator, operand1, operand2, inplace=False):
6988     # Construct binop node of appropriate class for
6989     # given operator.
6990     return binop_node_classes[operator](pos,
6991         operator = operator,
6992         operand1 = operand1,
6993         operand2 = operand2,
6994         inplace = inplace)
6995
6996 #-------------------------------------------------------------------
6997 #
6998 #  Coercion nodes
6999 #
7000 #  Coercion nodes are special in that they are created during
7001 #  the analyse_types phase of parse tree processing.
7002 #  Their __init__ methods consequently incorporate some aspects
7003 #  of that phase.
7004 #
7005 #-------------------------------------------------------------------
7006
7007 class CoercionNode(ExprNode):
7008     #  Abstract base class for coercion nodes.
7009     #
7010     #  arg       ExprNode       node being coerced
7011
7012     subexprs = ['arg']
7013     constant_result = not_a_constant
7014
7015     def __init__(self, arg):
7016         self.pos = arg.pos
7017         self.arg = arg
7018         if debug_coercion:
7019             print("%s Coercing %s" % (self, self.arg))
7020
7021     def calculate_constant_result(self):
7022         # constant folding can break type coercion, so this is disabled
7023         pass
7024
7025     def annotate(self, code):
7026         self.arg.annotate(code)
7027         if self.arg.type != self.type:
7028             file, line, col = self.pos
7029             code.annotate((file, line, col-1), AnnotationItem(style='coerce', tag='coerce', text='[%s] to [%s]' % (self.arg.type, self.type)))
7030
7031
7032 class CastNode(CoercionNode):
7033     #  Wrap a node in a C type cast.
7034
7035     def __init__(self, arg, new_type):
7036         CoercionNode.__init__(self, arg)
7037         self.type = new_type
7038
7039     def may_be_none(self):
7040         return self.arg.may_be_none()
7041
7042     def calculate_result_code(self):
7043         return self.arg.result_as(self.type)
7044
7045     def generate_result_code(self, code):
7046         self.arg.generate_result_code(code)
7047
7048
7049 class PyTypeTestNode(CoercionNode):
7050     #  This node is used to check that a generic Python
7051     #  object is an instance of a particular extension type.
7052     #  This node borrows the result of its argument node.
7053
7054     def __init__(self, arg, dst_type, env, notnone=False):
7055         #  The arg is know to be a Python object, and
7056         #  the dst_type is known to be an extension type.
7057         assert dst_type.is_extension_type or dst_type.is_builtin_type, "PyTypeTest on non extension type"
7058         CoercionNode.__init__(self, arg)
7059         self.type = dst_type
7060         self.result_ctype = arg.ctype()
7061         self.notnone = notnone
7062
7063     nogil_check = Node.gil_error
7064     gil_message = "Python type test"
7065
7066     def analyse_types(self, env):
7067         pass
7068
7069     def may_be_none(self):
7070         if self.notnone:
7071             return False
7072         return self.arg.may_be_none()
7073
7074     def is_simple(self):
7075         return self.arg.is_simple()
7076
7077     def result_in_temp(self):
7078         return self.arg.result_in_temp()
7079
7080     def is_ephemeral(self):
7081         return self.arg.is_ephemeral()
7082
7083     def calculate_constant_result(self):
7084         # FIXME
7085         pass
7086
7087     def calculate_result_code(self):
7088         return self.arg.result()
7089
7090     def generate_result_code(self, code):
7091         if self.type.typeobj_is_available():
7092             if not self.type.is_builtin_type:
7093                 code.globalstate.use_utility_code(type_test_utility_code)
7094             code.putln(
7095                 "if (!(%s)) %s" % (
7096                     self.type.type_test_code(self.arg.py_result(), self.notnone),
7097                     code.error_goto(self.pos)))
7098         else:
7099             error(self.pos, "Cannot test type of extern C class "
7100                 "without type object name specification")
7101
7102     def generate_post_assignment_code(self, code):
7103         self.arg.generate_post_assignment_code(code)
7104
7105     def free_temps(self, code):
7106         self.arg.free_temps(code)
7107
7108
7109 class NoneCheckNode(CoercionNode):
7110     # This node is used to check that a Python object is not None and
7111     # raises an appropriate exception (as specified by the creating
7112     # transform).
7113
7114     def __init__(self, arg, exception_type_cname, exception_message):
7115         CoercionNode.__init__(self, arg)
7116         self.type = arg.type
7117         self.result_ctype = arg.ctype()
7118         self.exception_type_cname = exception_type_cname
7119         self.exception_message = exception_message
7120
7121     def analyse_types(self, env):
7122         pass
7123
7124     def may_be_none(self):
7125         return False
7126
7127     def is_simple(self):
7128         return self.arg.is_simple()
7129
7130     def result_in_temp(self):
7131         return self.arg.result_in_temp()
7132
7133     def calculate_result_code(self):
7134         return self.arg.result()
7135
7136     def generate_result_code(self, code):
7137         code.putln(
7138             "if (unlikely(%s == Py_None)) {" % self.arg.result())
7139         code.putln('PyErr_SetString(%s, "%s"); %s ' % (
7140             self.exception_type_cname,
7141             StringEncoding.escape_byte_string(
7142                 self.exception_message.encode('UTF-8')),
7143             code.error_goto(self.pos)))
7144         code.putln("}")
7145
7146     def generate_post_assignment_code(self, code):
7147         self.arg.generate_post_assignment_code(code)
7148
7149     def free_temps(self, code):
7150         self.arg.free_temps(code)
7151
7152
7153 class CoerceToPyTypeNode(CoercionNode):
7154     #  This node is used to convert a C data type
7155     #  to a Python object.
7156
7157     type = py_object_type
7158     is_temp = 1
7159
7160     def __init__(self, arg, env, type=py_object_type):
7161         CoercionNode.__init__(self, arg)
7162         if not arg.type.create_to_py_utility_code(env):
7163             error(arg.pos,
7164                   "Cannot convert '%s' to Python object" % arg.type)
7165         if type is py_object_type:
7166             # be specific about some known types
7167             if arg.type.is_string:
7168                 self.type = bytes_type
7169             elif arg.type is PyrexTypes.c_py_unicode_type:
7170                 self.type = unicode_type
7171             elif arg.type.is_complex:
7172                 self.type = Builtin.complex_type
7173         else:
7174             # FIXME: check that the target type and the resulting type are compatible
7175             pass
7176
7177     gil_message = "Converting to Python object"
7178
7179     def may_be_none(self):
7180         # FIXME: is this always safe?
7181         return False
7182
7183     def coerce_to_boolean(self, env):
7184         arg_type = self.arg.type
7185         if (arg_type == PyrexTypes.c_bint_type or
7186             (arg_type.is_pyobject and arg_type.name == 'bool')):
7187             return self.arg.coerce_to_temp(env)
7188         else:
7189             return CoerceToBooleanNode(self, env)
7190
7191     def coerce_to_integer(self, env):
7192         # If not already some C integer type, coerce to longint.
7193         if self.arg.type.is_int:
7194             return self.arg
7195         else:
7196             return self.arg.coerce_to(PyrexTypes.c_long_type, env)
7197
7198     def analyse_types(self, env):
7199         # The arg is always already analysed
7200         pass
7201
7202     def generate_result_code(self, code):
7203         function = self.arg.type.to_py_function
7204         code.putln('%s = %s(%s); %s' % (
7205             self.result(),
7206             function,
7207             self.arg.result(),
7208             code.error_goto_if_null(self.result(), self.pos)))
7209         code.put_gotref(self.py_result())
7210
7211
7212 class CoerceIntToBytesNode(CoerceToPyTypeNode):
7213     #  This node is used to convert a C int type to a Python bytes
7214     #  object.
7215
7216     is_temp = 1
7217
7218     def __init__(self, arg, env):
7219         arg = arg.coerce_to_simple(env)
7220         CoercionNode.__init__(self, arg)
7221         self.type = Builtin.bytes_type
7222
7223     def generate_result_code(self, code):
7224         arg = self.arg
7225         arg_result = arg.result()
7226         if arg.type not in (PyrexTypes.c_char_type,
7227                             PyrexTypes.c_uchar_type,
7228                             PyrexTypes.c_schar_type):
7229             if arg.type.signed:
7230                 code.putln("if ((%s < 0) || (%s > 255)) {" % (
7231                     arg_result, arg_result))
7232             else:
7233                 code.putln("if (%s > 255) {" % arg_result)
7234             code.putln('PyErr_Format(PyExc_OverflowError, '
7235                        '"value too large to pack into a byte"); %s' % (
7236                            code.error_goto(self.pos)))
7237             code.putln('}')
7238         temp = None
7239         if arg.type is not PyrexTypes.c_char_type:
7240             temp = code.funcstate.allocate_temp(PyrexTypes.c_char_type, manage_ref=False)
7241             code.putln("%s = (char)%s;" % (temp, arg_result))
7242             arg_result = temp
7243         code.putln('%s = PyBytes_FromStringAndSize(&%s, 1); %s' % (
7244             self.result(),
7245             arg_result,
7246             code.error_goto_if_null(self.result(), self.pos)))
7247         if temp is not None:
7248             code.funcstate.release_temp(temp)
7249         code.put_gotref(self.py_result())
7250
7251
7252 class CoerceFromPyTypeNode(CoercionNode):
7253     #  This node is used to convert a Python object
7254     #  to a C data type.
7255
7256     def __init__(self, result_type, arg, env):
7257         CoercionNode.__init__(self, arg)
7258         self.type = result_type
7259         self.is_temp = 1
7260         if not result_type.create_from_py_utility_code(env):
7261             error(arg.pos,
7262                   "Cannot convert Python object to '%s'" % result_type)
7263         if self.type.is_string and self.arg.is_ephemeral():
7264             error(arg.pos,
7265                   "Obtaining char * from temporary Python value")
7266
7267     def analyse_types(self, env):
7268         # The arg is always already analysed
7269         pass
7270
7271     def generate_result_code(self, code):
7272         function = self.type.from_py_function
7273         operand = self.arg.py_result()
7274         rhs = "%s(%s)" % (function, operand)
7275         if self.type.is_enum:
7276             rhs = typecast(self.type, c_long_type, rhs)
7277         code.putln('%s = %s; %s' % (
7278             self.result(),
7279             rhs,
7280             code.error_goto_if(self.type.error_condition(self.result()), self.pos)))
7281         if self.type.is_pyobject:
7282             code.put_gotref(self.py_result())
7283
7284
7285 class CoerceToBooleanNode(CoercionNode):
7286     #  This node is used when a result needs to be used
7287     #  in a boolean context.
7288
7289     type = PyrexTypes.c_bint_type
7290
7291     _special_builtins = {
7292         Builtin.list_type    : 'PyList_GET_SIZE',
7293         Builtin.tuple_type   : 'PyTuple_GET_SIZE',
7294         Builtin.bytes_type   : 'PyBytes_GET_SIZE',
7295         Builtin.unicode_type : 'PyUnicode_GET_SIZE',
7296         }
7297
7298     def __init__(self, arg, env):
7299         CoercionNode.__init__(self, arg)
7300         if arg.type.is_pyobject:
7301             self.is_temp = 1
7302
7303     def nogil_check(self, env):
7304         if self.arg.type.is_pyobject and self._special_builtins.get(self.arg.type) is None:
7305             self.gil_error()
7306
7307     gil_message = "Truth-testing Python object"
7308
7309     def check_const(self):
7310         if self.is_temp:
7311             self.not_const()
7312             return False
7313         return self.arg.check_const()
7314
7315     def calculate_result_code(self):
7316         return "(%s != 0)" % self.arg.result()
7317
7318     def generate_result_code(self, code):
7319         if not self.is_temp:
7320             return
7321         test_func = self._special_builtins.get(self.arg.type)
7322         if test_func is not None:
7323             code.putln("%s = (%s != Py_None) && (%s(%s) != 0);" % (
7324                        self.result(),
7325                        self.arg.py_result(),
7326                        test_func,
7327                        self.arg.py_result()))
7328         else:
7329             code.putln(
7330                 "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
7331                     self.result(),
7332                     self.arg.py_result(),
7333                     code.error_goto_if_neg(self.result(), self.pos)))
7334
7335 class CoerceToComplexNode(CoercionNode):
7336
7337     def __init__(self, arg, dst_type, env):
7338         if arg.type.is_complex:
7339             arg = arg.coerce_to_simple(env)
7340         self.type = dst_type
7341         CoercionNode.__init__(self, arg)
7342         dst_type.create_declaration_utility_code(env)
7343
7344     def calculate_result_code(self):
7345         if self.arg.type.is_complex:
7346             real_part = "__Pyx_CREAL(%s)" % self.arg.result()
7347             imag_part = "__Pyx_CIMAG(%s)" % self.arg.result()
7348         else:
7349             real_part = self.arg.result()
7350             imag_part = "0"
7351         return "%s(%s, %s)" % (
7352                 self.type.from_parts,
7353                 real_part,
7354                 imag_part)
7355
7356     def generate_result_code(self, code):
7357         pass
7358
7359 class CoerceToTempNode(CoercionNode):
7360     #  This node is used to force the result of another node
7361     #  to be stored in a temporary. It is only used if the
7362     #  argument node's result is not already in a temporary.
7363
7364     def __init__(self, arg, env):
7365         CoercionNode.__init__(self, arg)
7366         self.type = self.arg.type
7367         self.constant_result = self.arg.constant_result
7368         self.is_temp = 1
7369         if self.type.is_pyobject:
7370             self.result_ctype = py_object_type
7371
7372     gil_message = "Creating temporary Python reference"
7373
7374     def analyse_types(self, env):
7375         # The arg is always already analysed
7376         pass
7377
7378     def coerce_to_boolean(self, env):
7379         self.arg = self.arg.coerce_to_boolean(env)
7380         if self.arg.is_simple():
7381             return self.arg
7382         self.type = self.arg.type
7383         self.result_ctype = self.type
7384         return self
7385
7386     def generate_result_code(self, code):
7387         #self.arg.generate_evaluation_code(code) # Already done
7388         # by generic generate_subexpr_evaluation_code!
7389         code.putln("%s = %s;" % (
7390             self.result(), self.arg.result_as(self.ctype())))
7391         if self.type.is_pyobject and self.use_managed_ref:
7392             code.put_incref(self.result(), self.ctype())
7393
7394
7395 class CloneNode(CoercionNode):
7396     #  This node is employed when the result of another node needs
7397     #  to be used multiple times. The argument node's result must
7398     #  be in a temporary. This node "borrows" the result from the
7399     #  argument node, and does not generate any evaluation or
7400     #  disposal code for it. The original owner of the argument
7401     #  node is responsible for doing those things.
7402
7403     subexprs = [] # Arg is not considered a subexpr
7404     nogil_check = None
7405
7406     def __init__(self, arg):
7407         CoercionNode.__init__(self, arg)
7408         if hasattr(arg, 'type'):
7409             self.type = arg.type
7410             self.result_ctype = arg.result_ctype
7411         if hasattr(arg, 'entry'):
7412             self.entry = arg.entry
7413
7414     def result(self):
7415         return self.arg.result()
7416
7417     def type_dependencies(self, env):
7418         return self.arg.type_dependencies(env)
7419
7420     def infer_type(self, env):
7421         return self.arg.infer_type(env)
7422
7423     def analyse_types(self, env):
7424         self.type = self.arg.type
7425         self.result_ctype = self.arg.result_ctype
7426         self.is_temp = 1
7427         if hasattr(self.arg, 'entry'):
7428             self.entry = self.arg.entry
7429
7430     def is_simple(self):
7431         return True # result is always in a temp (or a name)
7432
7433     def generate_evaluation_code(self, code):
7434         pass
7435
7436     def generate_result_code(self, code):
7437         pass
7438
7439     def generate_disposal_code(self, code):
7440         pass
7441
7442     def free_temps(self, code):
7443         pass
7444
7445
7446 class ModuleRefNode(ExprNode):
7447     # Simple returns the module object
7448
7449     type = py_object_type
7450     is_temp = False
7451     subexprs = []
7452
7453     def analyse_types(self, env):
7454         pass
7455
7456     def may_be_none(self):
7457         return False
7458
7459     def calculate_result_code(self):
7460         return Naming.module_cname
7461
7462     def generate_result_code(self, code):
7463         pass
7464
7465 class DocstringRefNode(ExprNode):
7466     # Extracts the docstring of the body element
7467
7468     subexprs = ['body']
7469     type = py_object_type
7470     is_temp = True
7471
7472     def __init__(self, pos, body):
7473         ExprNode.__init__(self, pos)
7474         assert body.type.is_pyobject
7475         self.body = body
7476
7477     def analyse_types(self, env):
7478         pass
7479
7480     def generate_result_code(self, code):
7481         code.putln('%s = __Pyx_GetAttrString(%s, "__doc__"); %s' % (
7482             self.result(), self.body.result(),
7483             code.error_goto_if_null(self.result(), self.pos)))
7484         code.put_gotref(self.result())
7485
7486
7487
7488 #------------------------------------------------------------------------------------
7489 #
7490 #  Runtime support code
7491 #
7492 #------------------------------------------------------------------------------------
7493
7494 get_name_interned_utility_code = UtilityCode(
7495 proto = """
7496 static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
7497 """,
7498 impl = """
7499 static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
7500     PyObject *result;
7501     result = PyObject_GetAttr(dict, name);
7502     if (!result)
7503         PyErr_SetObject(PyExc_NameError, name);
7504     return result;
7505 }
7506 """)
7507
7508 #------------------------------------------------------------------------------------
7509
7510 import_utility_code = UtilityCode(
7511 proto = """
7512 static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/
7513 """,
7514 impl = """
7515 static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) {
7516     PyObject *py_import = 0;
7517     PyObject *empty_list = 0;
7518     PyObject *module = 0;
7519     PyObject *global_dict = 0;
7520     PyObject *empty_dict = 0;
7521     PyObject *list;
7522     py_import = __Pyx_GetAttrString(%(BUILTINS)s, "__import__");
7523     if (!py_import)
7524         goto bad;
7525     if (from_list)
7526         list = from_list;
7527     else {
7528         empty_list = PyList_New(0);
7529         if (!empty_list)
7530             goto bad;
7531         list = empty_list;
7532     }
7533     global_dict = PyModule_GetDict(%(GLOBALS)s);
7534     if (!global_dict)
7535         goto bad;
7536     empty_dict = PyDict_New();
7537     if (!empty_dict)
7538         goto bad;
7539     module = PyObject_CallFunctionObjArgs(py_import,
7540         name, global_dict, empty_dict, list, NULL);
7541 bad:
7542     Py_XDECREF(empty_list);
7543     Py_XDECREF(py_import);
7544     Py_XDECREF(empty_dict);
7545     return module;
7546 }
7547 """ % {
7548     "BUILTINS": Naming.builtins_cname,
7549     "GLOBALS":  Naming.module_cname,
7550 })
7551
7552 #------------------------------------------------------------------------------------
7553
7554 get_exception_utility_code = UtilityCode(
7555 proto = """
7556 static PyObject *__Pyx_GetExcValue(void); /*proto*/
7557 """,
7558 impl = """
7559 static PyObject *__Pyx_GetExcValue(void) {
7560     PyObject *type = 0, *value = 0, *tb = 0;
7561     PyObject *tmp_type, *tmp_value, *tmp_tb;
7562     PyObject *result = 0;
7563     PyThreadState *tstate = PyThreadState_Get();
7564     PyErr_Fetch(&type, &value, &tb);
7565     PyErr_NormalizeException(&type, &value, &tb);
7566     if (PyErr_Occurred())
7567         goto bad;
7568     if (!value) {
7569         value = Py_None;
7570         Py_INCREF(value);
7571     }
7572     tmp_type = tstate->exc_type;
7573     tmp_value = tstate->exc_value;
7574     tmp_tb = tstate->exc_traceback;
7575     tstate->exc_type = type;
7576     tstate->exc_value = value;
7577     tstate->exc_traceback = tb;
7578     /* Make sure tstate is in a consistent state when we XDECREF
7579     these objects (XDECREF may run arbitrary code). */
7580     Py_XDECREF(tmp_type);
7581     Py_XDECREF(tmp_value);
7582     Py_XDECREF(tmp_tb);
7583     result = value;
7584     Py_XINCREF(result);
7585     type = 0;
7586     value = 0;
7587     tb = 0;
7588 bad:
7589     Py_XDECREF(type);
7590     Py_XDECREF(value);
7591     Py_XDECREF(tb);
7592     return result;
7593 }
7594 """)
7595
7596 #------------------------------------------------------------------------------------
7597
7598 type_test_utility_code = UtilityCode(
7599 proto = """
7600 static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/
7601 """,
7602 impl = """
7603 static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) {
7604     if (unlikely(!type)) {
7605         PyErr_Format(PyExc_SystemError, "Missing type object");
7606         return 0;
7607     }
7608     if (likely(PyObject_TypeCheck(obj, type)))
7609         return 1;
7610     PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s",
7611                  Py_TYPE(obj)->tp_name, type->tp_name);
7612     return 0;
7613 }
7614 """)
7615
7616 #------------------------------------------------------------------------------------
7617
7618 find_py2_metaclass_utility_code = UtilityCode(
7619 proto = '''
7620 static PyObject *__Pyx_FindPy2Metaclass(PyObject *bases); /*proto*/
7621 ''',
7622 impl = '''
7623 static PyObject *__Pyx_FindPy2Metaclass(PyObject *bases) {
7624     PyObject *metaclass;
7625     /* Default metaclass */
7626 #if PY_MAJOR_VERSION < 3
7627     if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7628         PyObject *base = PyTuple_GET_ITEM(bases, 0);
7629         metaclass = PyObject_GetAttrString(base, "__class__");
7630         if (!metaclass) {
7631             PyErr_Clear();
7632             metaclass = (PyObject*) Py_TYPE(base);
7633         }
7634     } else {
7635         metaclass = (PyObject *) &PyClass_Type;
7636     }
7637 #else
7638     if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7639         PyObject *base = PyTuple_GET_ITEM(bases, 0);
7640         metaclass = (PyObject*) Py_TYPE(base);
7641     } else {
7642         metaclass = (PyObject *) &PyType_Type;
7643     }
7644 #endif
7645     Py_INCREF(metaclass);
7646     return metaclass;
7647 }
7648 ''')
7649
7650 create_class_utility_code = UtilityCode(
7651 proto = """
7652 static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name,
7653                                    PyObject *modname); /*proto*/
7654 """,
7655 impl = """
7656 static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name,
7657                                    PyObject *modname) {
7658     PyObject *result;
7659     PyObject *metaclass;
7660
7661     if (PyDict_SetItemString(dict, "__module__", modname) < 0)
7662         return NULL;
7663
7664     /* Python2 __metaclass__ */
7665     metaclass = PyDict_GetItemString(dict, "__metaclass__");
7666     if (metaclass) {
7667         Py_INCREF(metaclass);
7668     } else {
7669         metaclass = __Pyx_FindPy2Metaclass(bases);
7670     }
7671     result = PyObject_CallFunctionObjArgs(metaclass, name, bases, dict, NULL);
7672     Py_DECREF(metaclass);
7673     return result;
7674 }
7675 """,
7676 requires = [find_py2_metaclass_utility_code])
7677
7678 #------------------------------------------------------------------------------------
7679
7680 create_py3class_utility_code = UtilityCode(
7681 proto = """
7682 static PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw); /*proto*/
7683 static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *mkw, PyObject *modname, PyObject *doc); /*proto*/
7684 static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, PyObject *mkw); /*proto*/
7685 """,
7686 impl = """
7687 PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw) {
7688     PyObject *metaclass = PyDict_GetItemString(mkw, "metaclass");
7689     if (metaclass) {
7690         Py_INCREF(metaclass);
7691         if (PyDict_DelItemString(mkw, "metaclass") < 0) {
7692             Py_DECREF(metaclass);
7693             return NULL;
7694         }
7695         return metaclass;
7696     }
7697     return __Pyx_FindPy2Metaclass(bases);
7698 }
7699
7700 PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *mkw,
7701                                     PyObject *modname, PyObject *doc) {
7702     PyObject *prep;
7703     PyObject *pargs;
7704     PyObject *ns;
7705     PyObject *str;
7706
7707     prep = PyObject_GetAttrString(metaclass, "__prepare__");
7708     if (!prep) {
7709         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
7710             return NULL;
7711         PyErr_Clear();
7712         return PyDict_New();
7713     }
7714     pargs = PyTuple_New(2);
7715     if (!pargs) {
7716         Py_DECREF(prep);
7717         return NULL;
7718     }
7719
7720     Py_INCREF(name);
7721     Py_INCREF(bases);
7722     PyTuple_SET_ITEM(pargs, 0, name);
7723     PyTuple_SET_ITEM(pargs, 1, bases);
7724
7725     ns = PyObject_Call(prep, pargs, mkw);
7726
7727     Py_DECREF(prep);
7728     Py_DECREF(pargs);
7729
7730     if (ns == NULL)
7731         return NULL;
7732
7733     /* Required here to emulate assignment order */
7734     /* XXX: use consts here */
7735     #if PY_MAJOR_VERSION >= 3
7736     str = PyUnicode_FromString("__module__");
7737     #else
7738     str = PyString_FromString("__module__");
7739     #endif
7740     if (!str) {
7741         Py_DECREF(ns);
7742         return NULL;
7743     }
7744
7745     if (PyObject_SetItem(ns, str, modname) < 0) {
7746         Py_DECREF(ns);
7747         Py_DECREF(str);
7748         return NULL;
7749     }
7750     Py_DECREF(str);
7751     if (doc) {
7752         #if PY_MAJOR_VERSION >= 3
7753         str = PyUnicode_FromString("__doc__");
7754         #else
7755         str = PyString_FromString("__doc__");
7756         #endif
7757         if (!str) {
7758             Py_DECREF(ns);
7759             return NULL;
7760         }
7761         if (PyObject_SetItem(ns, str, doc) < 0) {
7762             Py_DECREF(ns);
7763             Py_DECREF(str);
7764             return NULL;
7765         }
7766         Py_DECREF(str);
7767     }
7768     return ns;
7769 }
7770
7771 PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, PyObject *mkw) {
7772     PyObject *result;
7773     PyObject *margs = PyTuple_New(3);
7774     if (!margs)
7775         return NULL;
7776     Py_INCREF(name);
7777     Py_INCREF(bases);
7778     Py_INCREF(dict);
7779     PyTuple_SET_ITEM(margs, 0, name);
7780     PyTuple_SET_ITEM(margs, 1, bases);
7781     PyTuple_SET_ITEM(margs, 2, dict);
7782     result = PyObject_Call(metaclass, margs, mkw);
7783     Py_DECREF(margs);
7784     return result;
7785 }
7786 """,
7787 requires = [find_py2_metaclass_utility_code])
7788
7789 #------------------------------------------------------------------------------------
7790
7791 cpp_exception_utility_code = UtilityCode(
7792 proto = """
7793 #ifndef __Pyx_CppExn2PyErr
7794 static void __Pyx_CppExn2PyErr() {
7795   try {
7796     if (PyErr_Occurred())
7797       ; // let the latest Python exn pass through and ignore the current one
7798     else
7799       throw;
7800   } catch (const std::invalid_argument& exn) {
7801     // Catch a handful of different errors here and turn them into the
7802     // equivalent Python errors.
7803     // Change invalid_argument to ValueError
7804     PyErr_SetString(PyExc_ValueError, exn.what());
7805   } catch (const std::out_of_range& exn) {
7806     // Change out_of_range to IndexError
7807     PyErr_SetString(PyExc_IndexError, exn.what());
7808   } catch (const std::exception& exn) {
7809     PyErr_SetString(PyExc_RuntimeError, exn.what());
7810   }
7811   catch (...)
7812   {
7813     PyErr_SetString(PyExc_RuntimeError, "Unknown exception");
7814   }
7815 }
7816 #endif
7817 """,
7818 impl = ""
7819 )
7820
7821 pyerr_occurred_withgil_utility_code= UtilityCode(
7822 proto = """
7823 static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void); /* proto */
7824 """,
7825 impl = """
7826 static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void) {
7827   int err;
7828   #ifdef WITH_THREAD
7829   PyGILState_STATE _save = PyGILState_Ensure();
7830   #endif
7831   err = !!PyErr_Occurred();
7832   #ifdef WITH_THREAD
7833   PyGILState_Release(_save);
7834   #endif
7835   return err;
7836 }
7837 """
7838 )
7839
7840 #------------------------------------------------------------------------------------
7841
7842 raise_noneattr_error_utility_code = UtilityCode(
7843 proto = """
7844 static CYTHON_INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname);
7845 """,
7846 impl = '''
7847 static CYTHON_INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname) {
7848     PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", attrname);
7849 }
7850 ''')
7851
7852 raise_noneindex_error_utility_code = UtilityCode(
7853 proto = """
7854 static CYTHON_INLINE void __Pyx_RaiseNoneIndexingError(void);
7855 """,
7856 impl = '''
7857 static CYTHON_INLINE void __Pyx_RaiseNoneIndexingError(void) {
7858     PyErr_SetString(PyExc_TypeError, "'NoneType' object is unsubscriptable");
7859 }
7860 ''')
7861
7862 raise_none_iter_error_utility_code = UtilityCode(
7863 proto = """
7864 static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void);
7865 """,
7866 impl = '''
7867 static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) {
7868     PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
7869 }
7870 ''')
7871
7872 #------------------------------------------------------------------------------------
7873
7874 getitem_dict_utility_code = UtilityCode(
7875 proto = """
7876 #if PY_MAJOR_VERSION >= 3
7877 static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) {
7878     PyObject *value;
7879     if (unlikely(d == Py_None)) {
7880         __Pyx_RaiseNoneIndexingError();
7881         return NULL;
7882     }
7883     value = PyDict_GetItemWithError(d, key);
7884     if (unlikely(!value)) {
7885         if (!PyErr_Occurred())
7886             PyErr_SetObject(PyExc_KeyError, key);
7887         return NULL;
7888     }
7889     Py_INCREF(value);
7890     return value;
7891 }
7892 #else
7893     #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key)
7894 #endif
7895 """,
7896 requires = [raise_noneindex_error_utility_code])
7897
7898 #------------------------------------------------------------------------------------
7899
7900 getitem_int_pyunicode_utility_code = UtilityCode(
7901 proto = '''
7902 #define __Pyx_GetItemInt_Unicode(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7903                                                __Pyx_GetItemInt_Unicode_Fast(o, i) : \\
7904                                                __Pyx_GetItemInt_Unicode_Generic(o, to_py_func(i)))
7905
7906 static CYTHON_INLINE Py_UNICODE __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i) {
7907     if (likely((0 <= i) & (i < PyUnicode_GET_SIZE(ustring)))) {
7908         return PyUnicode_AS_UNICODE(ustring)[i];
7909     } else if ((-PyUnicode_GET_SIZE(ustring) <= i) & (i < 0)) {
7910         i += PyUnicode_GET_SIZE(ustring);
7911         return PyUnicode_AS_UNICODE(ustring)[i];
7912     } else {
7913         PyErr_SetString(PyExc_IndexError, "string index out of range");
7914         return (Py_UNICODE)-1;
7915     }
7916 }
7917
7918 static CYTHON_INLINE Py_UNICODE __Pyx_GetItemInt_Unicode_Generic(PyObject* ustring, PyObject* j) {
7919     Py_UNICODE uchar;
7920     PyObject *uchar_string;
7921     if (!j) return (Py_UNICODE)-1;
7922     uchar_string = PyObject_GetItem(ustring, j);
7923     Py_DECREF(j);
7924     if (!uchar_string) return (Py_UNICODE)-1;
7925     uchar = PyUnicode_AS_UNICODE(uchar_string)[0];
7926     Py_DECREF(uchar_string);
7927     return uchar;
7928 }
7929 ''')
7930
7931 getitem_int_utility_code = UtilityCode(
7932 proto = """
7933
7934 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) {
7935     PyObject *r;
7936     if (!j) return NULL;
7937     r = PyObject_GetItem(o, j);
7938     Py_DECREF(j);
7939     return r;
7940 }
7941
7942 """ + ''.join([
7943 """
7944 #define __Pyx_GetItemInt_%(type)s(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7945                                                     __Pyx_GetItemInt_%(type)s_Fast(o, i) : \\
7946                                                     __Pyx_GetItemInt_Generic(o, to_py_func(i)))
7947
7948 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_%(type)s_Fast(PyObject *o, Py_ssize_t i) {
7949     if (likely(o != Py_None)) {
7950         if (likely((0 <= i) & (i < Py%(type)s_GET_SIZE(o)))) {
7951             PyObject *r = Py%(type)s_GET_ITEM(o, i);
7952             Py_INCREF(r);
7953             return r;
7954         }
7955         else if ((-Py%(type)s_GET_SIZE(o) <= i) & (i < 0)) {
7956             PyObject *r = Py%(type)s_GET_ITEM(o, Py%(type)s_GET_SIZE(o) + i);
7957             Py_INCREF(r);
7958             return r;
7959         }
7960     }
7961     return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
7962 }
7963 """ % {'type' : type_name} for type_name in ('List', 'Tuple')
7964 ]) + """
7965
7966 #define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7967                                                     __Pyx_GetItemInt_Fast(o, i) : \\
7968                                                     __Pyx_GetItemInt_Generic(o, to_py_func(i)))
7969
7970 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) {
7971     PyObject *r;
7972     if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
7973         r = PyList_GET_ITEM(o, i);
7974         Py_INCREF(r);
7975     }
7976     else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) {
7977         r = PyTuple_GET_ITEM(o, i);
7978         Py_INCREF(r);
7979     }
7980     else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) {
7981         r = PySequence_GetItem(o, i);
7982     }
7983     else {
7984         r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
7985     }
7986     return r;
7987 }
7988 """,
7989 impl = """
7990 """)
7991
7992
7993
7994 #------------------------------------------------------------------------------------
7995
7996 setitem_int_utility_code = UtilityCode(
7997 proto = """
7998 #define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7999                                                     __Pyx_SetItemInt_Fast(o, i, v) : \\
8000                                                     __Pyx_SetItemInt_Generic(o, to_py_func(i), v))
8001
8002 static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) {
8003     int r;
8004     if (!j) return -1;
8005     r = PyObject_SetItem(o, j, v);
8006     Py_DECREF(j);
8007     return r;
8008 }
8009
8010 static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) {
8011     if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
8012         Py_INCREF(v);
8013         Py_DECREF(PyList_GET_ITEM(o, i));
8014         PyList_SET_ITEM(o, i, v);
8015         return 1;
8016     }
8017     else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0)))
8018         return PySequence_SetItem(o, i, v);
8019     else {
8020         PyObject *j = PyInt_FromSsize_t(i);
8021         return __Pyx_SetItemInt_Generic(o, j, v);
8022     }
8023 }
8024 """,
8025 impl = """
8026 """)
8027
8028 #------------------------------------------------------------------------------------
8029
8030 delitem_int_utility_code = UtilityCode(
8031 proto = """
8032 #define __Pyx_DelItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
8033                                                     __Pyx_DelItemInt_Fast(o, i) : \\
8034                                                     __Pyx_DelItem_Generic(o, to_py_func(i)))
8035
8036 static CYTHON_INLINE int __Pyx_DelItem_Generic(PyObject *o, PyObject *j) {
8037     int r;
8038     if (!j) return -1;
8039     r = PyObject_DelItem(o, j);
8040     Py_DECREF(j);
8041     return r;
8042 }
8043
8044 static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i) {
8045     if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && likely(i >= 0))
8046         return PySequence_DelItem(o, i);
8047     else {
8048         PyObject *j = PyInt_FromSsize_t(i);
8049         return __Pyx_DelItem_Generic(o, j);
8050     }
8051 }
8052 """,
8053 impl = """
8054 """)
8055
8056 #------------------------------------------------------------------------------------
8057
8058 raise_too_many_values_to_unpack = UtilityCode(
8059 proto = """
8060 static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected);
8061 """,
8062 impl = '''
8063 static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) {
8064     PyErr_Format(PyExc_ValueError,
8065         #if PY_VERSION_HEX < 0x02050000
8066             "too many values to unpack (expected %d)", (int)expected);
8067         #else
8068             "too many values to unpack (expected %zd)", expected);
8069         #endif
8070 }
8071 ''')
8072
8073 raise_need_more_values_to_unpack = UtilityCode(
8074 proto = """
8075 static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index);
8076 """,
8077 impl = '''
8078 static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) {
8079     PyErr_Format(PyExc_ValueError,
8080         #if PY_VERSION_HEX < 0x02050000
8081                  "need more than %d value%s to unpack", (int)index,
8082         #else
8083                  "need more than %zd value%s to unpack", index,
8084         #endif
8085                  (index == 1) ? "" : "s");
8086 }
8087 ''')
8088
8089 #------------------------------------------------------------------------------------
8090
8091 tuple_unpacking_error_code = UtilityCode(
8092 proto = """
8093 static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/
8094 """,
8095 impl = """
8096 static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) {
8097     if (t == Py_None) {
8098       __Pyx_RaiseNoneNotIterableError();
8099     } else if (PyTuple_GET_SIZE(t) < index) {
8100       __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t));
8101     } else {
8102       __Pyx_RaiseTooManyValuesError(index);
8103     }
8104 }
8105 """,
8106 requires = [raise_none_iter_error_utility_code,
8107             raise_need_more_values_to_unpack,
8108             raise_too_many_values_to_unpack]
8109 )
8110
8111 unpacking_utility_code = UtilityCode(
8112 proto = """
8113 static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/
8114 static int __Pyx_EndUnpack(PyObject *, Py_ssize_t expected); /*proto*/
8115 """,
8116 impl = """
8117 static PyObject *__Pyx_UnpackItem(PyObject *iter, Py_ssize_t index) {
8118     PyObject *item;
8119     if (!(item = PyIter_Next(iter))) {
8120         if (!PyErr_Occurred()) {
8121             __Pyx_RaiseNeedMoreValuesError(index);
8122         }
8123     }
8124     return item;
8125 }
8126
8127 static int __Pyx_EndUnpack(PyObject *iter, Py_ssize_t expected) {
8128     PyObject *item;
8129     if ((item = PyIter_Next(iter))) {
8130         Py_DECREF(item);
8131         __Pyx_RaiseTooManyValuesError(expected);
8132         return -1;
8133     }
8134     else if (!PyErr_Occurred())
8135         return 0;
8136     else
8137         return -1;
8138 }
8139 """,
8140 requires = [raise_need_more_values_to_unpack,
8141             raise_too_many_values_to_unpack]
8142 )
8143
8144 #------------------------------------------------------------------------------------
8145
8146 # CPython supports calling functions with non-dict kwargs by
8147 # converting them to a dict first
8148
8149 kwargs_call_utility_code = UtilityCode(
8150 proto = """
8151 static PyObject* __Pyx_PyEval_CallObjectWithKeywords(PyObject*, PyObject*, PyObject*); /*proto*/
8152 """,
8153 impl = """
8154 static PyObject* __Pyx_PyEval_CallObjectWithKeywords(PyObject *callable, PyObject *args, PyObject *kwargs) {
8155     PyObject* result;
8156     if (likely(PyDict_Check(kwargs))) {
8157         return PyEval_CallObjectWithKeywords(callable, args, kwargs);
8158     } else {
8159         PyObject* real_dict;
8160         real_dict = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, kwargs, NULL);
8161         if (unlikely(!real_dict))
8162             return NULL;
8163         result = PyEval_CallObjectWithKeywords(callable, args, real_dict);
8164         Py_DECREF(real_dict);
8165         return result; /* may be NULL */
8166     }
8167 }
8168 """,
8169 )
8170
8171
8172 #------------------------------------------------------------------------------------
8173
8174 int_pow_utility_code = UtilityCode(
8175 proto="""
8176 static CYTHON_INLINE %(type)s %(func_name)s(%(type)s, %(type)s); /* proto */
8177 """,
8178 impl="""
8179 static CYTHON_INLINE %(type)s %(func_name)s(%(type)s b, %(type)s e) {
8180     %(type)s t = b;
8181     switch (e) {
8182         case 3:
8183             t *= b;
8184         case 2:
8185             t *= b;
8186         case 1:
8187             return t;
8188         case 0:
8189             return 1;
8190     }
8191     if (unlikely(e<0)) return 0;
8192     t = 1;
8193     while (likely(e)) {
8194         t *= (b * (e&1)) | ((~e)&1);    /* 1 or b */
8195         b *= b;
8196         e >>= 1;
8197     }
8198     return t;
8199 }
8200 """)
8201
8202 # ------------------------------ Division ------------------------------------
8203
8204 div_int_utility_code = UtilityCode(
8205 proto="""
8206 static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s, %(type)s); /* proto */
8207 """,
8208 impl="""
8209 static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s a, %(type)s b) {
8210     %(type)s q = a / b;
8211     %(type)s r = a - q*b;
8212     q -= ((r != 0) & ((r ^ b) < 0));
8213     return q;
8214 }
8215 """)
8216
8217 mod_int_utility_code = UtilityCode(
8218 proto="""
8219 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
8220 """,
8221 impl="""
8222 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
8223     %(type)s r = a %% b;
8224     r += ((r != 0) & ((r ^ b) < 0)) * b;
8225     return r;
8226 }
8227 """)
8228
8229 mod_float_utility_code = UtilityCode(
8230 proto="""
8231 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
8232 """,
8233 impl="""
8234 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
8235     %(type)s r = fmod%(math_h_modifier)s(a, b);
8236     r += ((r != 0) & ((r < 0) ^ (b < 0))) * b;
8237     return r;
8238 }
8239 """)
8240
8241 cdivision_warning_utility_code = UtilityCode(
8242 proto="""
8243 static int __Pyx_cdivision_warning(void); /* proto */
8244 """,
8245 impl="""
8246 static int __Pyx_cdivision_warning(void) {
8247     return PyErr_WarnExplicit(PyExc_RuntimeWarning,
8248                               "division with oppositely signed operands, C and Python semantics differ",
8249                               %(FILENAME)s,
8250                               %(LINENO)s,
8251                               __Pyx_MODULE_NAME,
8252                               NULL);
8253 }
8254 """ % {
8255     'FILENAME': Naming.filename_cname,
8256     'LINENO':  Naming.lineno_cname,
8257 })
8258
8259 # from intobject.c
8260 division_overflow_test_code = UtilityCode(
8261 proto="""
8262 #define UNARY_NEG_WOULD_OVERFLOW(x)     \
8263         (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x)))
8264 """)
8265
8266
8267 binding_cfunc_utility_code = UtilityCode(
8268 proto="""
8269 #define %(binding_cfunc)s_USED 1
8270
8271 typedef struct {
8272     PyCFunctionObject func;
8273 } %(binding_cfunc)s_object;
8274
8275 static PyTypeObject %(binding_cfunc)s_type;
8276 static PyTypeObject *%(binding_cfunc)s = NULL;
8277
8278 static PyObject *%(binding_cfunc)s_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module); /* proto */
8279 #define %(binding_cfunc)s_New(ml, self) %(binding_cfunc)s_NewEx(ml, self, NULL)
8280
8281 static int %(binding_cfunc)s_init(void); /* proto */
8282 """ % Naming.__dict__,
8283 impl="""
8284
8285 static PyObject *%(binding_cfunc)s_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) {
8286         %(binding_cfunc)s_object *op = PyObject_GC_New(%(binding_cfunc)s_object, %(binding_cfunc)s);
8287     if (op == NULL)
8288         return NULL;
8289         op->func.m_ml = ml;
8290         Py_XINCREF(self);
8291         op->func.m_self = self;
8292         Py_XINCREF(module);
8293         op->func.m_module = module;
8294         PyObject_GC_Track(op);
8295         return (PyObject *)op;
8296 }
8297
8298 static void %(binding_cfunc)s_dealloc(%(binding_cfunc)s_object *m) {
8299         PyObject_GC_UnTrack(m);
8300         Py_XDECREF(m->func.m_self);
8301         Py_XDECREF(m->func.m_module);
8302     PyObject_GC_Del(m);
8303 }
8304
8305 static PyObject *%(binding_cfunc)s_descr_get(PyObject *func, PyObject *obj, PyObject *type) {
8306         if (obj == Py_None)
8307                 obj = NULL;
8308         return PyMethod_New(func, obj, type);
8309 }
8310
8311 static int %(binding_cfunc)s_init(void) {
8312     %(binding_cfunc)s_type = PyCFunction_Type;
8313     %(binding_cfunc)s_type.tp_name = __Pyx_NAMESTR("cython_binding_builtin_function_or_method");
8314     %(binding_cfunc)s_type.tp_dealloc = (destructor)%(binding_cfunc)s_dealloc;
8315     %(binding_cfunc)s_type.tp_descr_get = %(binding_cfunc)s_descr_get;
8316     if (PyType_Ready(&%(binding_cfunc)s_type) < 0) {
8317         return -1;
8318     }
8319     %(binding_cfunc)s = &%(binding_cfunc)s_type;
8320     return 0;
8321
8322 }
8323 """ % Naming.__dict__)