Merge branch 'pyregr' of github.com:vitek/cython
[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 analyse_target_declaration(self, env):
2018         pass
2019
2020     def analyse_as_type(self, env):
2021         base_type = self.base.analyse_as_type(env)
2022         if base_type and not base_type.is_pyobject:
2023             if base_type.is_cpp_class:
2024                 if isinstance(self.index, TupleNode):
2025                     template_values = self.index.args
2026                 else:
2027                     template_values = [self.index]
2028                 import Nodes
2029                 type_node = Nodes.TemplatedTypeNode(
2030                     pos = self.pos,
2031                     positional_args = template_values,
2032                     keyword_args = None)
2033                 return type_node.analyse(env, base_type = base_type)
2034             else:
2035                 return PyrexTypes.CArrayType(base_type, int(self.index.compile_time_value(env)))
2036         return None
2037
2038     def type_dependencies(self, env):
2039         return self.base.type_dependencies(env) + self.index.type_dependencies(env)
2040
2041     def infer_type(self, env):
2042         base_type = self.base.infer_type(env)
2043         if isinstance(self.index, SliceNode):
2044             # slicing!
2045             if base_type.is_string:
2046                 # sliced C strings must coerce to Python
2047                 return bytes_type
2048             elif base_type in (unicode_type, bytes_type, str_type, list_type, tuple_type):
2049                 # slicing these returns the same type
2050                 return base_type
2051             else:
2052                 # TODO: Handle buffers (hopefully without too much redundancy).
2053                 return py_object_type
2054
2055         index_type = self.index.infer_type(env)
2056         if index_type and index_type.is_int or isinstance(self.index, (IntNode, LongNode)):
2057             # indexing!
2058             if base_type is unicode_type:
2059                 # Py_UNICODE will automatically coerce to a unicode string
2060                 # if required, so this is safe. We only infer Py_UNICODE
2061                 # when the index is a C integer type. Otherwise, we may
2062                 # need to use normal Python item access, in which case
2063                 # it's faster to return the one-char unicode string than
2064                 # to receive it, throw it away, and potentially rebuild it
2065                 # on a subsequent PyObject coercion.
2066                 return PyrexTypes.c_py_unicode_type
2067             elif isinstance(self.base, BytesNode):
2068                 #if env.global_scope().context.language_level >= 3:
2069                 #    # infering 'char' can be made to work in Python 3 mode
2070                 #    return PyrexTypes.c_char_type
2071                 # Py2/3 return different types on indexing bytes objects
2072                 return py_object_type
2073             elif base_type.is_ptr or base_type.is_array:
2074                 return base_type.base_type
2075
2076         # may be slicing or indexing, we don't know
2077         if base_type is unicode_type:
2078             # this type always returns its own type on Python indexing/slicing
2079             return base_type
2080         else:
2081             # TODO: Handle buffers (hopefully without too much redundancy).
2082             return py_object_type
2083
2084     def analyse_types(self, env):
2085         self.analyse_base_and_index_types(env, getting = 1)
2086
2087     def analyse_target_types(self, env):
2088         self.analyse_base_and_index_types(env, setting = 1)
2089
2090     def analyse_base_and_index_types(self, env, getting = 0, setting = 0):
2091         # Note: This might be cleaned up by having IndexNode
2092         # parsed in a saner way and only construct the tuple if
2093         # needed.
2094
2095         # Note that this function must leave IndexNode in a cloneable state.
2096         # For buffers, self.index is packed out on the initial analysis, and
2097         # when cloning self.indices is copied.
2098         self.is_buffer_access = False
2099
2100         self.base.analyse_types(env)
2101         if self.base.type.is_error:
2102             # Do not visit child tree if base is undeclared to avoid confusing
2103             # error messages
2104             self.type = PyrexTypes.error_type
2105             return
2106
2107         is_slice = isinstance(self.index, SliceNode)
2108         # Potentially overflowing index value.
2109         if not is_slice and isinstance(self.index, IntNode) and Utils.long_literal(self.index.value):
2110             self.index = self.index.coerce_to_pyobject(env)
2111
2112         # Handle the case where base is a literal char* (and we expect a string, not an int)
2113         if isinstance(self.base, BytesNode) or is_slice:
2114             if self.base.type.is_string or not (self.base.type.is_ptr or self.base.type.is_array):
2115                 self.base = self.base.coerce_to_pyobject(env)
2116
2117         skip_child_analysis = False
2118         buffer_access = False
2119         if self.base.type.is_buffer:
2120             if self.indices:
2121                 indices = self.indices
2122             else:
2123                 if isinstance(self.index, TupleNode):
2124                     indices = self.index.args
2125                 else:
2126                     indices = [self.index]
2127             if len(indices) == self.base.type.ndim:
2128                 buffer_access = True
2129                 skip_child_analysis = True
2130                 for x in indices:
2131                     x.analyse_types(env)
2132                     if not x.type.is_int:
2133                         buffer_access = False
2134             if buffer_access:
2135                 assert hasattr(self.base, "entry") # Must be a NameNode-like node
2136
2137         # On cloning, indices is cloned. Otherwise, unpack index into indices
2138         assert not (buffer_access and isinstance(self.index, CloneNode))
2139
2140         if buffer_access:
2141             self.indices = indices
2142             self.index = None
2143             self.type = self.base.type.dtype
2144             self.is_buffer_access = True
2145             self.buffer_type = self.base.entry.type
2146
2147             if getting and self.type.is_pyobject:
2148                 self.is_temp = True
2149             if setting:
2150                 if not self.base.entry.type.writable:
2151                     error(self.pos, "Writing to readonly buffer")
2152                 else:
2153                     self.base.entry.buffer_aux.writable_needed = True
2154         else:
2155             base_type = self.base.type
2156             if isinstance(self.index, TupleNode):
2157                 self.index.analyse_types(env, skip_children=skip_child_analysis)
2158             elif not skip_child_analysis:
2159                 self.index.analyse_types(env)
2160             self.original_index_type = self.index.type
2161             if base_type is PyrexTypes.c_py_unicode_type:
2162                 # we infer Py_UNICODE for unicode strings in some
2163                 # cases, but indexing must still work for them
2164                 if self.index.constant_result in (0, -1):
2165                     # FIXME: we know that this node is redundant -
2166                     # currently, this needs to get handled in Optimize.py
2167                     pass
2168                 self.base = self.base.coerce_to_pyobject(env)
2169                 base_type = self.base.type
2170             if base_type.is_pyobject:
2171                 if self.index.type.is_int:
2172                     if (not setting
2173                         and (base_type in (list_type, tuple_type, unicode_type))
2174                         and (not self.index.type.signed or isinstance(self.index, IntNode) and int(self.index.value) >= 0)
2175                         and not env.directives['boundscheck']):
2176                         self.is_temp = 0
2177                     else:
2178                         self.is_temp = 1
2179                     self.index = self.index.coerce_to(PyrexTypes.c_py_ssize_t_type, env).coerce_to_simple(env)
2180                 else:
2181                     self.index = self.index.coerce_to_pyobject(env)
2182                     self.is_temp = 1
2183                 if self.index.type.is_int and base_type is unicode_type:
2184                     # Py_UNICODE will automatically coerce to a unicode string
2185                     # if required, so this is fast and safe
2186                     self.type = PyrexTypes.c_py_unicode_type
2187                 elif is_slice and base_type in (bytes_type, str_type, unicode_type, list_type, tuple_type):
2188                     self.type = base_type
2189                 else:
2190                     self.type = py_object_type
2191             else:
2192                 if base_type.is_ptr or base_type.is_array:
2193                     self.type = base_type.base_type
2194                     if is_slice:
2195                         self.type = base_type
2196                     elif self.index.type.is_pyobject:
2197                         self.index = self.index.coerce_to(
2198                             PyrexTypes.c_py_ssize_t_type, env)
2199                     elif not self.index.type.is_int:
2200                         error(self.pos,
2201                             "Invalid index type '%s'" %
2202                                 self.index.type)
2203                 elif base_type.is_cpp_class:
2204                     function = env.lookup_operator("[]", [self.base, self.index])
2205                     if function is None:
2206                         error(self.pos, "Indexing '%s' not supported for index type '%s'" % (base_type, self.index.type))
2207                         self.type = PyrexTypes.error_type
2208                         self.result_code = "<error>"
2209                         return
2210                     func_type = function.type
2211                     if func_type.is_ptr:
2212                         func_type = func_type.base_type
2213                     self.index = self.index.coerce_to(func_type.args[0].type, env)
2214                     self.type = func_type.return_type
2215                     if setting and not func_type.return_type.is_reference:
2216                         error(self.pos, "Can't set non-reference result '%s'" % self.type)
2217                 else:
2218                     error(self.pos,
2219                         "Attempting to index non-array type '%s'" %
2220                             base_type)
2221                     self.type = PyrexTypes.error_type
2222
2223     gil_message = "Indexing Python object"
2224
2225     def nogil_check(self, env):
2226         if self.is_buffer_access:
2227             if env.directives['boundscheck']:
2228                 error(self.pos, "Cannot check buffer index bounds without gil; use boundscheck(False) directive")
2229                 return
2230             elif self.type.is_pyobject:
2231                 error(self.pos, "Cannot access buffer with object dtype without gil")
2232                 return
2233         super(IndexNode, self).nogil_check(env)
2234
2235
2236     def check_const_addr(self):
2237         return self.base.check_const_addr() and self.index.check_const()
2238
2239     def is_lvalue(self):
2240         return 1
2241
2242     def calculate_result_code(self):
2243         if self.is_buffer_access:
2244             return "(*%s)" % self.buffer_ptr_code
2245         elif self.base.type is list_type:
2246             return "PyList_GET_ITEM(%s, %s)" % (self.base.result(), self.index.result())
2247         elif self.base.type is tuple_type:
2248             return "PyTuple_GET_ITEM(%s, %s)" % (self.base.result(), self.index.result())
2249         elif self.base.type is unicode_type and self.type is PyrexTypes.c_py_unicode_type:
2250             return "PyUnicode_AS_UNICODE(%s)[%s]" % (self.base.result(), self.index.result())
2251         elif (self.type.is_ptr or self.type.is_array) and self.type == self.base.type:
2252             error(self.pos, "Invalid use of pointer slice")
2253         else:
2254             return "(%s[%s])" % (
2255                 self.base.result(), self.index.result())
2256
2257     def extra_index_params(self):
2258         if self.index.type.is_int:
2259             if self.original_index_type.signed:
2260                 size_adjustment = ""
2261             else:
2262                 size_adjustment = "+1"
2263             return ", sizeof(%s)%s, %s" % (self.original_index_type.declaration_code(""), size_adjustment, self.original_index_type.to_py_function)
2264         else:
2265             return ""
2266
2267     def generate_subexpr_evaluation_code(self, code):
2268         self.base.generate_evaluation_code(code)
2269         if not self.indices:
2270             self.index.generate_evaluation_code(code)
2271         else:
2272             for i in self.indices:
2273                 i.generate_evaluation_code(code)
2274
2275     def generate_subexpr_disposal_code(self, code):
2276         self.base.generate_disposal_code(code)
2277         if not self.indices:
2278             self.index.generate_disposal_code(code)
2279         else:
2280             for i in self.indices:
2281                 i.generate_disposal_code(code)
2282
2283     def free_subexpr_temps(self, code):
2284         self.base.free_temps(code)
2285         if not self.indices:
2286             self.index.free_temps(code)
2287         else:
2288             for i in self.indices:
2289                 i.free_temps(code)
2290
2291     def generate_result_code(self, code):
2292         if self.is_buffer_access:
2293             if code.globalstate.directives['nonecheck']:
2294                 self.put_nonecheck(code)
2295             self.buffer_ptr_code = self.buffer_lookup_code(code)
2296             if self.type.is_pyobject:
2297                 # is_temp is True, so must pull out value and incref it.
2298                 code.putln("%s = *%s;" % (self.result(), self.buffer_ptr_code))
2299                 code.putln("__Pyx_INCREF((PyObject*)%s);" % self.result())
2300         elif self.is_temp:
2301             if self.type.is_pyobject:
2302                 if self.index.type.is_int:
2303                     index_code = self.index.result()
2304                     if self.base.type is list_type:
2305                         function = "__Pyx_GetItemInt_List"
2306                     elif self.base.type is tuple_type:
2307                         function = "__Pyx_GetItemInt_Tuple"
2308                     else:
2309                         function = "__Pyx_GetItemInt"
2310                     code.globalstate.use_utility_code(getitem_int_utility_code)
2311                 else:
2312                     index_code = self.index.py_result()
2313                     if self.base.type is dict_type:
2314                         function = "__Pyx_PyDict_GetItem"
2315                         code.globalstate.use_utility_code(getitem_dict_utility_code)
2316                     else:
2317                         function = "PyObject_GetItem"
2318                 code.putln(
2319                     "%s = %s(%s, %s%s); if (!%s) %s" % (
2320                         self.result(),
2321                         function,
2322                         self.base.py_result(),
2323                         index_code,
2324                         self.extra_index_params(),
2325                         self.result(),
2326                         code.error_goto(self.pos)))
2327                 code.put_gotref(self.py_result())
2328             elif self.type is PyrexTypes.c_py_unicode_type and self.base.type is unicode_type:
2329                 assert self.index.type.is_int
2330                 index_code = self.index.result()
2331                 function = "__Pyx_GetItemInt_Unicode"
2332                 code.globalstate.use_utility_code(getitem_int_pyunicode_utility_code)
2333                 code.putln(
2334                     "%s = %s(%s, %s%s); if (unlikely(%s == (Py_UNICODE)-1)) %s;" % (
2335                         self.result(),
2336                         function,
2337                         self.base.py_result(),
2338                         index_code,
2339                         self.extra_index_params(),
2340                         self.result(),
2341                         code.error_goto(self.pos)))
2342
2343     def generate_setitem_code(self, value_code, code):
2344         if self.index.type.is_int:
2345             function = "__Pyx_SetItemInt"
2346             index_code = self.index.result()
2347             code.globalstate.use_utility_code(setitem_int_utility_code)
2348         else:
2349             index_code = self.index.py_result()
2350             if self.base.type is dict_type:
2351                 function = "PyDict_SetItem"
2352             # It would seem that we could specialized lists/tuples, but that
2353             # shouldn't happen here.
2354             # Both PyList_SetItem PyTuple_SetItem and a Py_ssize_t as input,
2355             # not a PyObject*, and bad conversion here would give the wrong
2356             # exception. Also, tuples are supposed to be immutable, and raise
2357             # TypeErrors when trying to set their entries (PyTuple_SetItem
2358             # is for creating new tuples from).
2359             else:
2360                 function = "PyObject_SetItem"
2361         code.putln(
2362             "if (%s(%s, %s, %s%s) < 0) %s" % (
2363                 function,
2364                 self.base.py_result(),
2365                 index_code,
2366                 value_code,
2367                 self.extra_index_params(),
2368                 code.error_goto(self.pos)))
2369
2370     def generate_buffer_setitem_code(self, rhs, code, op=""):
2371         # Used from generate_assignment_code and InPlaceAssignmentNode
2372         if code.globalstate.directives['nonecheck']:
2373             self.put_nonecheck(code)
2374         ptrexpr = self.buffer_lookup_code(code)
2375         if self.buffer_type.dtype.is_pyobject:
2376             # Must manage refcounts. Decref what is already there
2377             # and incref what we put in.
2378             ptr = code.funcstate.allocate_temp(self.buffer_type.buffer_ptr_type, manage_ref=False)
2379             rhs_code = rhs.result()
2380             code.putln("%s = %s;" % (ptr, ptrexpr))
2381             code.put_gotref("*%s" % ptr)
2382             code.putln("__Pyx_DECREF(*%s); __Pyx_INCREF(%s);" % (
2383                 ptr, rhs_code
2384                 ))
2385             code.putln("*%s %s= %s;" % (ptr, op, rhs_code))
2386             code.put_giveref("*%s" % ptr)
2387             code.funcstate.release_temp(ptr)
2388         else:
2389             # Simple case
2390             code.putln("*%s %s= %s;" % (ptrexpr, op, rhs.result()))
2391
2392     def generate_assignment_code(self, rhs, code):
2393         self.generate_subexpr_evaluation_code(code)
2394         if self.is_buffer_access:
2395             self.generate_buffer_setitem_code(rhs, code)
2396         elif self.type.is_pyobject:
2397             self.generate_setitem_code(rhs.py_result(), code)
2398         else:
2399             code.putln(
2400                 "%s = %s;" % (
2401                     self.result(), rhs.result()))
2402         self.generate_subexpr_disposal_code(code)
2403         self.free_subexpr_temps(code)
2404         rhs.generate_disposal_code(code)
2405         rhs.free_temps(code)
2406
2407     def generate_deletion_code(self, code):
2408         self.generate_subexpr_evaluation_code(code)
2409         #if self.type.is_pyobject:
2410         if self.index.type.is_int:
2411             function = "__Pyx_DelItemInt"
2412             index_code = self.index.result()
2413             code.globalstate.use_utility_code(delitem_int_utility_code)
2414         else:
2415             index_code = self.index.py_result()
2416             if self.base.type is dict_type:
2417                 function = "PyDict_DelItem"
2418             else:
2419                 function = "PyObject_DelItem"
2420         code.putln(
2421             "if (%s(%s, %s%s) < 0) %s" % (
2422                 function,
2423                 self.base.py_result(),
2424                 index_code,
2425                 self.extra_index_params(),
2426                 code.error_goto(self.pos)))
2427         self.generate_subexpr_disposal_code(code)
2428         self.free_subexpr_temps(code)
2429
2430     def buffer_lookup_code(self, code):
2431         # Assign indices to temps
2432         index_temps = [code.funcstate.allocate_temp(i.type, manage_ref=False) for i in self.indices]
2433         for temp, index in zip(index_temps, self.indices):
2434             code.putln("%s = %s;" % (temp, index.result()))
2435         # Generate buffer access code using these temps
2436         import Buffer
2437         # The above could happen because child_attrs is wrong somewhere so that
2438         # options are not propagated.
2439         return Buffer.put_buffer_lookup_code(entry=self.base.entry,
2440                                              index_signeds=[i.type.signed for i in self.indices],
2441                                              index_cnames=index_temps,
2442                                              directives=code.globalstate.directives,
2443                                              pos=self.pos, code=code)
2444
2445     def put_nonecheck(self, code):
2446         code.globalstate.use_utility_code(raise_noneindex_error_utility_code)
2447         code.putln("if (%s) {" % code.unlikely("%s == Py_None") % self.base.result_as(PyrexTypes.py_object_type))
2448         code.putln("__Pyx_RaiseNoneIndexingError();")
2449         code.putln(code.error_goto(self.pos))
2450         code.putln("}")
2451
2452 class SliceIndexNode(ExprNode):
2453     #  2-element slice indexing
2454     #
2455     #  base      ExprNode
2456     #  start     ExprNode or None
2457     #  stop      ExprNode or None
2458
2459     subexprs = ['base', 'start', 'stop']
2460
2461     def infer_type(self, env):
2462         base_type = self.base.infer_type(env)
2463         if base_type.is_string:
2464             return bytes_type
2465         elif base_type in (bytes_type, str_type, unicode_type,
2466                            list_type, tuple_type):
2467             return base_type
2468         return py_object_type
2469
2470     def calculate_constant_result(self):
2471         self.constant_result = self.base.constant_result[
2472             self.start.constant_result : self.stop.constant_result]
2473
2474     def compile_time_value(self, denv):
2475         base = self.base.compile_time_value(denv)
2476         if self.start is None:
2477             start = 0
2478         else:
2479             start = self.start.compile_time_value(denv)
2480         if self.stop is None:
2481             stop = None
2482         else:
2483             stop = self.stop.compile_time_value(denv)
2484         try:
2485             return base[start:stop]
2486         except Exception, e:
2487             self.compile_time_value_error(e)
2488
2489     def analyse_target_declaration(self, env):
2490         pass
2491
2492     def analyse_target_types(self, env):
2493         self.analyse_types(env)
2494         # when assigning, we must accept any Python type
2495         if self.type.is_pyobject:
2496             self.type = py_object_type
2497
2498     def analyse_types(self, env):
2499         self.base.analyse_types(env)
2500         if self.start:
2501             self.start.analyse_types(env)
2502         if self.stop:
2503             self.stop.analyse_types(env)
2504         base_type = self.base.type
2505         if base_type.is_string:
2506             self.type = bytes_type
2507         elif base_type.is_ptr:
2508             self.type = base_type
2509         elif base_type.is_array:
2510             # we need a ptr type here instead of an array type, as
2511             # array types can result in invalid type casts in the C
2512             # code
2513             self.type = PyrexTypes.CPtrType(base_type.base_type)
2514         else:
2515             self.base = self.base.coerce_to_pyobject(env)
2516             self.type = py_object_type
2517         if base_type.is_builtin_type:
2518             # slicing builtin types returns something of the same type
2519             self.type = base_type
2520         c_int = PyrexTypes.c_py_ssize_t_type
2521         if self.start:
2522             self.start = self.start.coerce_to(c_int, env)
2523         if self.stop:
2524             self.stop = self.stop.coerce_to(c_int, env)
2525         self.is_temp = 1
2526
2527     nogil_check = Node.gil_error
2528     gil_message = "Slicing Python object"
2529
2530     def generate_result_code(self, code):
2531         if not self.type.is_pyobject:
2532             error(self.pos,
2533                   "Slicing is not currently supported for '%s'." % self.type)
2534             return
2535         if self.base.type.is_string:
2536             if self.stop is None:
2537                 code.putln(
2538                     "%s = PyBytes_FromString(%s + %s); %s" % (
2539                         self.result(),
2540                         self.base.result(),
2541                         self.start_code(),
2542                         code.error_goto_if_null(self.result(), self.pos)))
2543             else:
2544                 code.putln(
2545                     "%s = PyBytes_FromStringAndSize(%s + %s, %s - %s); %s" % (
2546                         self.result(),
2547                         self.base.result(),
2548                         self.start_code(),
2549                         self.stop_code(),
2550                         self.start_code(),
2551                         code.error_goto_if_null(self.result(), self.pos)))
2552         else:
2553             code.putln(
2554                 "%s = __Pyx_PySequence_GetSlice(%s, %s, %s); %s" % (
2555                     self.result(),
2556                     self.base.py_result(),
2557                     self.start_code(),
2558                     self.stop_code(),
2559                     code.error_goto_if_null(self.result(), self.pos)))
2560         code.put_gotref(self.py_result())
2561
2562     def generate_assignment_code(self, rhs, code):
2563         self.generate_subexpr_evaluation_code(code)
2564         if self.type.is_pyobject:
2565             code.put_error_if_neg(self.pos,
2566                 "__Pyx_PySequence_SetSlice(%s, %s, %s, %s)" % (
2567                     self.base.py_result(),
2568                     self.start_code(),
2569                     self.stop_code(),
2570                     rhs.py_result()))
2571         else:
2572             start_offset = ''
2573             if self.start:
2574                 start_offset = self.start_code()
2575                 if start_offset == '0':
2576                     start_offset = ''
2577                 else:
2578                     start_offset += '+'
2579             if rhs.type.is_array:
2580                 array_length = rhs.type.size
2581                 self.generate_slice_guard_code(code, array_length)
2582             else:
2583                 error(self.pos,
2584                       "Slice assignments from pointers are not yet supported.")
2585                 # FIXME: fix the array size according to start/stop
2586                 array_length = self.base.type.size
2587             for i in range(array_length):
2588                 code.putln("%s[%s%s] = %s[%d];" % (
2589                         self.base.result(), start_offset, i,
2590                         rhs.result(), i))
2591         self.generate_subexpr_disposal_code(code)
2592         self.free_subexpr_temps(code)
2593         rhs.generate_disposal_code(code)
2594         rhs.free_temps(code)
2595
2596     def generate_deletion_code(self, code):
2597         if not self.base.type.is_pyobject:
2598             error(self.pos,
2599                   "Deleting slices is only supported for Python types, not '%s'." % self.type)
2600             return
2601         self.generate_subexpr_evaluation_code(code)
2602         code.put_error_if_neg(self.pos,
2603             "__Pyx_PySequence_DelSlice(%s, %s, %s)" % (
2604                 self.base.py_result(),
2605                 self.start_code(),
2606                 self.stop_code()))
2607         self.generate_subexpr_disposal_code(code)
2608         self.free_subexpr_temps(code)
2609
2610     def generate_slice_guard_code(self, code, target_size):
2611         if not self.base.type.is_array:
2612             return
2613         slice_size = self.base.type.size
2614         start = stop = None
2615         if self.stop:
2616             stop = self.stop.result()
2617             try:
2618                 stop = int(stop)
2619                 if stop < 0:
2620                     slice_size = self.base.type.size + stop
2621                 else:
2622                     slice_size = stop
2623                 stop = None
2624             except ValueError:
2625                 pass
2626         if self.start:
2627             start = self.start.result()
2628             try:
2629                 start = int(start)
2630                 if start < 0:
2631                     start = self.base.type.size + start
2632                 slice_size -= start
2633                 start = None
2634             except ValueError:
2635                 pass
2636         check = None
2637         if slice_size < 0:
2638             if target_size > 0:
2639                 error(self.pos, "Assignment to empty slice.")
2640         elif start is None and stop is None:
2641             # we know the exact slice length
2642             if target_size != slice_size:
2643                 error(self.pos, "Assignment to slice of wrong length, expected %d, got %d" % (
2644                         slice_size, target_size))
2645         elif start is not None:
2646             if stop is None:
2647                 stop = slice_size
2648             check = "(%s)-(%s)" % (stop, start)
2649         else: # stop is not None:
2650             check = stop
2651         if check:
2652             code.putln("if (unlikely((%s) != %d)) {" % (check, target_size))
2653             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));' % (
2654                         target_size, check))
2655             code.putln(code.error_goto(self.pos))
2656             code.putln("}")
2657
2658     def start_code(self):
2659         if self.start:
2660             return self.start.result()
2661         else:
2662             return "0"
2663
2664     def stop_code(self):
2665         if self.stop:
2666             return self.stop.result()
2667         elif self.base.type.is_array:
2668             return self.base.type.size
2669         else:
2670             return "PY_SSIZE_T_MAX"
2671
2672     def calculate_result_code(self):
2673         # self.result() is not used, but this method must exist
2674         return "<unused>"
2675
2676
2677 class SliceNode(ExprNode):
2678     #  start:stop:step in subscript list
2679     #
2680     #  start     ExprNode
2681     #  stop      ExprNode
2682     #  step      ExprNode
2683
2684     type = py_object_type
2685     is_temp = 1
2686
2687     def calculate_constant_result(self):
2688         self.constant_result = self.base.constant_result[
2689             self.start.constant_result : \
2690                 self.stop.constant_result : \
2691                 self.step.constant_result]
2692
2693     def compile_time_value(self, denv):
2694         start = self.start.compile_time_value(denv)
2695         if self.stop is None:
2696             stop = None
2697         else:
2698             stop = self.stop.compile_time_value(denv)
2699         if self.step is None:
2700             step = None
2701         else:
2702             step = self.step.compile_time_value(denv)
2703         try:
2704             return slice(start, stop, step)
2705         except Exception, e:
2706             self.compile_time_value_error(e)
2707
2708     subexprs = ['start', 'stop', 'step']
2709
2710     def analyse_types(self, env):
2711         self.start.analyse_types(env)
2712         self.stop.analyse_types(env)
2713         self.step.analyse_types(env)
2714         self.start = self.start.coerce_to_pyobject(env)
2715         self.stop = self.stop.coerce_to_pyobject(env)
2716         self.step = self.step.coerce_to_pyobject(env)
2717
2718     gil_message = "Constructing Python slice object"
2719
2720     def generate_result_code(self, code):
2721         code.putln(
2722             "%s = PySlice_New(%s, %s, %s); %s" % (
2723                 self.result(),
2724                 self.start.py_result(),
2725                 self.stop.py_result(),
2726                 self.step.py_result(),
2727                 code.error_goto_if_null(self.result(), self.pos)))
2728         code.put_gotref(self.py_result())
2729
2730
2731 class CallNode(ExprNode):
2732
2733     # allow overriding the default 'may_be_none' behaviour
2734     may_return_none = None
2735
2736     def may_be_none(self):
2737         if self.may_return_none is not None:
2738             return self.may_return_none
2739         return ExprNode.may_be_none(self)
2740
2741     def analyse_as_type_constructor(self, env):
2742         type = self.function.analyse_as_type(env)
2743         if type and type.is_struct_or_union:
2744             args, kwds = self.explicit_args_kwds()
2745             items = []
2746             for arg, member in zip(args, type.scope.var_entries):
2747                 items.append(DictItemNode(pos=arg.pos, key=StringNode(pos=arg.pos, value=member.name), value=arg))
2748             if kwds:
2749                 items += kwds.key_value_pairs
2750             self.key_value_pairs = items
2751             self.__class__ = DictNode
2752             self.analyse_types(env)
2753             self.coerce_to(type, env)
2754             return True
2755         elif type and type.is_cpp_class:
2756             for arg in self.args:
2757                 arg.analyse_types(env)
2758             constructor = type.scope.lookup("<init>")
2759             self.function = RawCNameExprNode(self.function.pos, constructor.type)
2760             self.function.entry = constructor
2761             self.function.set_cname(type.declaration_code(""))
2762             self.analyse_c_function_call(env)
2763             return True
2764
2765     def is_lvalue(self):
2766         return self.type.is_reference
2767
2768     def nogil_check(self, env):
2769         func_type = self.function_type()
2770         if func_type.is_pyobject:
2771             self.gil_error()
2772         elif not getattr(func_type, 'nogil', False):
2773             self.gil_error()
2774
2775     gil_message = "Calling gil-requiring function"
2776
2777
2778 class SimpleCallNode(CallNode):
2779     #  Function call without keyword, * or ** args.
2780     #
2781     #  function       ExprNode
2782     #  args           [ExprNode]
2783     #  arg_tuple      ExprNode or None     used internally
2784     #  self           ExprNode or None     used internally
2785     #  coerced_self   ExprNode or None     used internally
2786     #  wrapper_call   bool                 used internally
2787     #  has_optional_args   bool            used internally
2788     #  nogil          bool                 used internally
2789
2790     subexprs = ['self', 'coerced_self', 'function', 'args', 'arg_tuple']
2791
2792     self = None
2793     coerced_self = None
2794     arg_tuple = None
2795     wrapper_call = False
2796     has_optional_args = False
2797     nogil = False
2798     analysed = False
2799
2800     def compile_time_value(self, denv):
2801         function = self.function.compile_time_value(denv)
2802         args = [arg.compile_time_value(denv) for arg in self.args]
2803         try:
2804             return function(*args)
2805         except Exception, e:
2806             self.compile_time_value_error(e)
2807
2808     def type_dependencies(self, env):
2809         # TODO: Update when Danilo's C++ code merged in to handle the
2810         # the case of function overloading.
2811         return self.function.type_dependencies(env)
2812
2813     def infer_type(self, env):
2814         function = self.function
2815         func_type = function.infer_type(env)
2816         if isinstance(self.function, NewExprNode):
2817             return PyrexTypes.CPtrType(self.function.class_type)
2818         if func_type.is_ptr:
2819             func_type = func_type.base_type
2820         if func_type.is_cfunction:
2821             return func_type.return_type
2822         elif func_type is type_type:
2823             if function.is_name and function.entry and function.entry.type:
2824                 result_type = function.entry.type
2825                 if result_type.is_extension_type:
2826                     return result_type
2827                 elif result_type.is_builtin_type:
2828                     if function.entry.name == 'float':
2829                         return PyrexTypes.c_double_type
2830                     elif function.entry.name in Builtin.types_that_construct_their_instance:
2831                         return result_type
2832         return py_object_type
2833
2834     def analyse_as_type(self, env):
2835         attr = self.function.as_cython_attribute()
2836         if attr == 'pointer':
2837             if len(self.args) != 1:
2838                 error(self.args.pos, "only one type allowed.")
2839             else:
2840                 type = self.args[0].analyse_as_type(env)
2841                 if not type:
2842                     error(self.args[0].pos, "Unknown type")
2843                 else:
2844                     return PyrexTypes.CPtrType(type)
2845
2846     def explicit_args_kwds(self):
2847         return self.args, None
2848
2849     def analyse_types(self, env):
2850         if self.analyse_as_type_constructor(env):
2851             return
2852         if self.analysed:
2853             return
2854         self.analysed = True
2855         function = self.function
2856         function.is_called = 1
2857         self.function.analyse_types(env)
2858         if function.is_attribute and function.entry and function.entry.is_cmethod:
2859             # Take ownership of the object from which the attribute
2860             # was obtained, because we need to pass it as 'self'.
2861             self.self = function.obj
2862             function.obj = CloneNode(self.self)
2863         func_type = self.function_type()
2864         if func_type.is_pyobject:
2865             self.arg_tuple = TupleNode(self.pos, args = self.args)
2866             self.arg_tuple.analyse_types(env)
2867             self.args = None
2868             if func_type is Builtin.type_type and function.is_name and \
2869                    function.entry and \
2870                    function.entry.is_builtin and \
2871                    function.entry.name in Builtin.types_that_construct_their_instance:
2872                 # calling a builtin type that returns a specific object type
2873                 if function.entry.name == 'float':
2874                     # the following will come true later on in a transform
2875                     self.type = PyrexTypes.c_double_type
2876                     self.result_ctype = PyrexTypes.c_double_type
2877                 else:
2878                     self.type = Builtin.builtin_types[function.entry.name]
2879                     self.result_ctype = py_object_type
2880                 self.may_return_none = False
2881             elif function.is_name and function.type_entry:
2882                 # We are calling an extension type constructor.  As
2883                 # long as we do not support __new__(), the result type
2884                 # is clear
2885                 self.type = function.type_entry.type
2886                 self.result_ctype = py_object_type
2887                 self.may_return_none = False
2888             else:
2889                 self.type = py_object_type
2890             self.is_temp = 1
2891         else:
2892             for arg in self.args:
2893                 arg.analyse_types(env)
2894             if self.self and func_type.args:
2895                 # Coerce 'self' to the type expected by the method.
2896                 self_arg = func_type.args[0]
2897                 if self_arg.not_none: # C methods must do the None test for self at *call* time
2898                     self.self = self.self.as_none_safe_node(
2899                         "'NoneType' object has no attribute '%s'" % self.function.entry.name,
2900                         'PyExc_AttributeError')
2901                 expected_type = self_arg.type
2902                 self.coerced_self = CloneNode(self.self).coerce_to(
2903                     expected_type, env)
2904                 # Insert coerced 'self' argument into argument list.
2905                 self.args.insert(0, self.coerced_self)
2906             self.analyse_c_function_call(env)
2907
2908     def function_type(self):
2909         # Return the type of the function being called, coercing a function
2910         # pointer to a function if necessary.
2911         func_type = self.function.type
2912         if func_type.is_ptr:
2913             func_type = func_type.base_type
2914         return func_type
2915
2916     def analyse_c_function_call(self, env):
2917         if self.function.type is error_type:
2918             self.type = error_type
2919             return
2920         if self.function.type.is_cpp_class:
2921             overloaded_entry = self.function.type.scope.lookup("operator()")
2922             if overloaded_entry is None:
2923                 self.type = PyrexTypes.error_type
2924                 self.result_code = "<error>"
2925                 return
2926         elif hasattr(self.function, 'entry'):
2927             overloaded_entry = self.function.entry
2928         else:
2929             overloaded_entry = None
2930         if overloaded_entry:
2931             entry = PyrexTypes.best_match(self.args, overloaded_entry.all_alternatives(), self.pos)
2932             if not entry:
2933                 self.type = PyrexTypes.error_type
2934                 self.result_code = "<error>"
2935                 return
2936             self.function.entry = entry
2937             self.function.type = entry.type
2938             func_type = self.function_type()
2939         else:
2940             func_type = self.function_type()
2941             if not func_type.is_cfunction:
2942                 error(self.pos, "Calling non-function type '%s'" % func_type)
2943                 self.type = PyrexTypes.error_type
2944                 self.result_code = "<error>"
2945                 return
2946         # Check no. of args
2947         max_nargs = len(func_type.args)
2948         expected_nargs = max_nargs - func_type.optional_arg_count
2949         actual_nargs = len(self.args)
2950         if func_type.optional_arg_count and expected_nargs != actual_nargs:
2951             self.has_optional_args = 1
2952             self.is_temp = 1
2953         # Coerce arguments
2954         for i in range(min(max_nargs, actual_nargs)):
2955             formal_type = func_type.args[i].type
2956             arg = self.args[i].coerce_to(formal_type, env)
2957             if arg.type.is_pyobject and not env.nogil and (arg.is_attribute or not arg.is_simple):
2958                 # we do not own the argument's reference, but we must
2959                 # make sure it cannot be collected before we return
2960                 # from the function, so we create an owned temp
2961                 # reference to it
2962                 arg = arg.coerce_to_temp(env)
2963             self.args[i] = arg
2964         for i in range(max_nargs, actual_nargs):
2965             arg = self.args[i]
2966             if arg.type.is_pyobject:
2967                 arg_ctype = arg.type.default_coerced_ctype()
2968                 if arg_ctype is None:
2969                     error(self.args[i].pos,
2970                           "Python object cannot be passed as a varargs parameter")
2971                 else:
2972                     self.args[i] = arg.coerce_to(arg_ctype, env)
2973         # Calc result type and code fragment
2974         if isinstance(self.function, NewExprNode):
2975             self.type = PyrexTypes.CPtrType(self.function.class_type)
2976         else:
2977             self.type = func_type.return_type
2978         if self.type.is_pyobject:
2979             self.result_ctype = py_object_type
2980             self.is_temp = 1
2981         elif func_type.exception_value is not None \
2982                  or func_type.exception_check:
2983             self.is_temp = 1
2984         # Called in 'nogil' context?
2985         self.nogil = env.nogil
2986         if (self.nogil and
2987             func_type.exception_check and
2988             func_type.exception_check != '+'):
2989             env.use_utility_code(pyerr_occurred_withgil_utility_code)
2990         # C++ exception handler
2991         if func_type.exception_check == '+':
2992             if func_type.exception_value is None:
2993                 env.use_utility_code(cpp_exception_utility_code)
2994
2995     def calculate_result_code(self):
2996         return self.c_call_code()
2997
2998     def c_call_code(self):
2999         func_type = self.function_type()
3000         if self.type is PyrexTypes.error_type or not func_type.is_cfunction:
3001             return "<error>"
3002         formal_args = func_type.args
3003         arg_list_code = []
3004         args = list(zip(formal_args, self.args))
3005         max_nargs = len(func_type.args)
3006         expected_nargs = max_nargs - func_type.optional_arg_count
3007         actual_nargs = len(self.args)
3008         for formal_arg, actual_arg in args[:expected_nargs]:
3009                 arg_code = actual_arg.result_as(formal_arg.type)
3010                 arg_list_code.append(arg_code)
3011
3012         if func_type.is_overridable:
3013             arg_list_code.append(str(int(self.wrapper_call or self.function.entry.is_unbound_cmethod)))
3014
3015         if func_type.optional_arg_count:
3016             if expected_nargs == actual_nargs:
3017                 optional_args = 'NULL'
3018             else:
3019                 optional_args = "&%s" % self.opt_arg_struct
3020             arg_list_code.append(optional_args)
3021
3022         for actual_arg in self.args[len(formal_args):]:
3023             arg_list_code.append(actual_arg.result())
3024         result = "%s(%s)" % (self.function.result(),
3025             ', '.join(arg_list_code))
3026         return result
3027
3028     def generate_result_code(self, code):
3029         func_type = self.function_type()
3030         if func_type.is_pyobject:
3031             arg_code = self.arg_tuple.py_result()
3032             code.putln(
3033                 "%s = PyObject_Call(%s, %s, NULL); %s" % (
3034                     self.result(),
3035                     self.function.py_result(),
3036                     arg_code,
3037                     code.error_goto_if_null(self.result(), self.pos)))
3038             code.put_gotref(self.py_result())
3039         elif func_type.is_cfunction:
3040             if self.has_optional_args:
3041                 actual_nargs = len(self.args)
3042                 expected_nargs = len(func_type.args) - func_type.optional_arg_count
3043                 self.opt_arg_struct = code.funcstate.allocate_temp(
3044                     func_type.op_arg_struct.base_type, manage_ref=True)
3045                 code.putln("%s.%s = %s;" % (
3046                         self.opt_arg_struct,
3047                         Naming.pyrex_prefix + "n",
3048                         len(self.args) - expected_nargs))
3049                 args = list(zip(func_type.args, self.args))
3050                 for formal_arg, actual_arg in args[expected_nargs:actual_nargs]:
3051                     code.putln("%s.%s = %s;" % (
3052                             self.opt_arg_struct,
3053                             func_type.opt_arg_cname(formal_arg.name),
3054                             actual_arg.result_as(formal_arg.type)))
3055             exc_checks = []
3056             if self.type.is_pyobject and self.is_temp:
3057                 exc_checks.append("!%s" % self.result())
3058             else:
3059                 exc_val = func_type.exception_value
3060                 exc_check = func_type.exception_check
3061                 if exc_val is not None:
3062                     exc_checks.append("%s == %s" % (self.result(), exc_val))
3063                 if exc_check:
3064                     if self.nogil:
3065                         exc_checks.append("__Pyx_ErrOccurredWithGIL()")
3066                     else:
3067                         exc_checks.append("PyErr_Occurred()")
3068             if self.is_temp or exc_checks:
3069                 rhs = self.c_call_code()
3070                 if self.result():
3071                     lhs = "%s = " % self.result()
3072                     if self.is_temp and self.type.is_pyobject:
3073                         #return_type = self.type # func_type.return_type
3074                         #print "SimpleCallNode.generate_result_code: casting", rhs, \
3075                         #    "from", return_type, "to pyobject" ###
3076                         rhs = typecast(py_object_type, self.type, rhs)
3077                 else:
3078                     lhs = ""
3079                 if func_type.exception_check == '+':
3080                     if func_type.exception_value is None:
3081                         raise_py_exception = "__Pyx_CppExn2PyErr()"
3082                     elif func_type.exception_value.type.is_pyobject:
3083                         raise_py_exception = ' try { throw; } catch(const std::exception& exn) { PyErr_SetString(%s, exn.what()); } catch(...) { PyErr_SetNone(%s); }' % (
3084                             func_type.exception_value.entry.cname,
3085                             func_type.exception_value.entry.cname)
3086                     else:
3087                         raise_py_exception = '%s(); if (!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError , "Error converting c++ exception.")' % func_type.exception_value.entry.cname
3088                     if self.nogil:
3089                         raise_py_exception = 'Py_BLOCK_THREADS; %s; Py_UNBLOCK_THREADS' % raise_py_exception
3090                     code.putln(
3091                     "try {%s%s;} catch(...) {%s; %s}" % (
3092                         lhs,
3093                         rhs,
3094                         raise_py_exception,
3095                         code.error_goto(self.pos)))
3096                 else:
3097                     if exc_checks:
3098                         goto_error = code.error_goto_if(" && ".join(exc_checks), self.pos)
3099                     else:
3100                         goto_error = ""
3101                     code.putln("%s%s; %s" % (lhs, rhs, goto_error))
3102                 if self.type.is_pyobject and self.result():
3103                     code.put_gotref(self.py_result())
3104             if self.has_optional_args:
3105                 code.funcstate.release_temp(self.opt_arg_struct)
3106
3107
3108 class PythonCapiFunctionNode(ExprNode):
3109     subexprs = []
3110     def __init__(self, pos, py_name, cname, func_type, utility_code = None):
3111         self.pos = pos
3112         self.name = py_name
3113         self.cname = cname
3114         self.type = func_type
3115         self.utility_code = utility_code
3116
3117     def analyse_types(self, env):
3118         pass
3119
3120     def generate_result_code(self, code):
3121         if self.utility_code:
3122             code.globalstate.use_utility_code(self.utility_code)
3123
3124     def calculate_result_code(self):
3125         return self.cname
3126
3127 class PythonCapiCallNode(SimpleCallNode):
3128     # Python C-API Function call (only created in transforms)
3129
3130     # By default, we assume that the call never returns None, as this
3131     # is true for most C-API functions in CPython.  If this does not
3132     # apply to a call, set the following to True (or None to inherit
3133     # the default behaviour).
3134     may_return_none = False
3135
3136     def __init__(self, pos, function_name, func_type,
3137                  utility_code = None, py_name=None, **kwargs):
3138         self.type = func_type.return_type
3139         self.result_ctype = self.type
3140         self.function = PythonCapiFunctionNode(
3141             pos, py_name, function_name, func_type,
3142             utility_code = utility_code)
3143         # call this last so that we can override the constructed
3144         # attributes above with explicit keyword arguments if required
3145         SimpleCallNode.__init__(self, pos, **kwargs)
3146
3147
3148 class GeneralCallNode(CallNode):
3149     #  General Python function call, including keyword,
3150     #  * and ** arguments.
3151     #
3152     #  function         ExprNode
3153     #  positional_args  ExprNode          Tuple of positional arguments
3154     #  keyword_args     ExprNode or None  Dict of keyword arguments
3155     #  starstar_arg     ExprNode or None  Dict of extra keyword args
3156
3157     type = py_object_type
3158
3159     subexprs = ['function', 'positional_args', 'keyword_args', 'starstar_arg']
3160
3161     nogil_check = Node.gil_error
3162
3163     def compile_time_value(self, denv):
3164         function = self.function.compile_time_value(denv)
3165         positional_args = self.positional_args.compile_time_value(denv)
3166         keyword_args = self.keyword_args.compile_time_value(denv)
3167         starstar_arg = self.starstar_arg.compile_time_value(denv)
3168         try:
3169             keyword_args.update(starstar_arg)
3170             return function(*positional_args, **keyword_args)
3171         except Exception, e:
3172             self.compile_time_value_error(e)
3173
3174     def explicit_args_kwds(self):
3175         if self.starstar_arg or not isinstance(self.positional_args, TupleNode):
3176             raise CompileError(self.pos,
3177                 'Compile-time keyword arguments must be explicit.')
3178         return self.positional_args.args, self.keyword_args
3179
3180     def analyse_types(self, env):
3181         if self.analyse_as_type_constructor(env):
3182             return
3183         self.function.analyse_types(env)
3184         self.positional_args.analyse_types(env)
3185         if self.keyword_args:
3186             self.keyword_args.analyse_types(env)
3187         if self.starstar_arg:
3188             self.starstar_arg.analyse_types(env)
3189         if not self.function.type.is_pyobject:
3190             if self.function.type.is_error:
3191                 self.type = error_type
3192                 return
3193             if hasattr(self.function, 'entry') and not self.function.entry.as_variable:
3194                 error(self.pos, "Keyword and starred arguments not allowed in cdef functions.")
3195             else:
3196                 self.function = self.function.coerce_to_pyobject(env)
3197         self.positional_args = \
3198             self.positional_args.coerce_to_pyobject(env)
3199         if self.starstar_arg:
3200             self.starstar_arg = \
3201                 self.starstar_arg.coerce_to_pyobject(env)
3202         function = self.function
3203         if function.is_name and function.type_entry:
3204             # We are calling an extension type constructor.  As long
3205             # as we do not support __new__(), the result type is clear
3206             self.type = function.type_entry.type
3207             self.result_ctype = py_object_type
3208             self.may_return_none = False
3209         else:
3210             self.type = py_object_type
3211         self.is_temp = 1
3212
3213     def generate_result_code(self, code):
3214         if self.type.is_error: return
3215         kwargs_call_function = "PyEval_CallObjectWithKeywords"
3216         if self.keyword_args and self.starstar_arg:
3217             code.put_error_if_neg(self.pos,
3218                 "PyDict_Update(%s, %s)" % (
3219                     self.keyword_args.py_result(),
3220                     self.starstar_arg.py_result()))
3221             keyword_code = self.keyword_args.py_result()
3222         elif self.keyword_args:
3223             keyword_code = self.keyword_args.py_result()
3224         elif self.starstar_arg:
3225             keyword_code = self.starstar_arg.py_result()
3226             if self.starstar_arg.type is not Builtin.dict_type:
3227                 # CPython supports calling functions with non-dicts, so do we
3228                 code.globalstate.use_utility_code(kwargs_call_utility_code)
3229                 kwargs_call_function = "__Pyx_PyEval_CallObjectWithKeywords"
3230         else:
3231             keyword_code = None
3232         if not keyword_code:
3233             call_code = "PyObject_Call(%s, %s, NULL)" % (
3234                 self.function.py_result(),
3235                 self.positional_args.py_result())
3236         else:
3237             call_code = "%s(%s, %s, %s)" % (
3238                 kwargs_call_function,
3239                 self.function.py_result(),
3240                 self.positional_args.py_result(),
3241                 keyword_code)
3242         code.putln(
3243             "%s = %s; %s" % (
3244                 self.result(),
3245                 call_code,
3246                 code.error_goto_if_null(self.result(), self.pos)))
3247         code.put_gotref(self.py_result())
3248
3249
3250 class AsTupleNode(ExprNode):
3251     #  Convert argument to tuple. Used for normalising
3252     #  the * argument of a function call.
3253     #
3254     #  arg    ExprNode
3255
3256     subexprs = ['arg']
3257
3258     def calculate_constant_result(self):
3259         self.constant_result = tuple(self.base.constant_result)
3260
3261     def compile_time_value(self, denv):
3262         arg = self.arg.compile_time_value(denv)
3263         try:
3264             return tuple(arg)
3265         except Exception, e:
3266             self.compile_time_value_error(e)
3267
3268     def analyse_types(self, env):
3269         self.arg.analyse_types(env)
3270         self.arg = self.arg.coerce_to_pyobject(env)
3271         self.type = tuple_type
3272         self.is_temp = 1
3273
3274     def may_be_none(self):
3275         return False
3276
3277     nogil_check = Node.gil_error
3278     gil_message = "Constructing Python tuple"
3279
3280     def generate_result_code(self, code):
3281         code.putln(
3282             "%s = PySequence_Tuple(%s); %s" % (
3283                 self.result(),
3284                 self.arg.py_result(),
3285                 code.error_goto_if_null(self.result(), self.pos)))
3286         code.put_gotref(self.py_result())
3287
3288
3289 class AttributeNode(ExprNode):
3290     #  obj.attribute
3291     #
3292     #  obj          ExprNode
3293     #  attribute    string
3294     #  needs_none_check boolean        Used if obj is an extension type.
3295     #                                  If set to True, it is known that the type is not None.
3296     #
3297     #  Used internally:
3298     #
3299     #  is_py_attr           boolean   Is a Python getattr operation
3300     #  member               string    C name of struct member
3301     #  is_called            boolean   Function call is being done on result
3302     #  entry                Entry     Symbol table entry of attribute
3303
3304     is_attribute = 1
3305     subexprs = ['obj']
3306
3307     type = PyrexTypes.error_type
3308     entry = None
3309     is_called = 0
3310     needs_none_check = True
3311
3312     def as_cython_attribute(self):
3313         if isinstance(self.obj, NameNode) and self.obj.is_cython_module:
3314             return self.attribute
3315         cy = self.obj.as_cython_attribute()
3316         if cy:
3317             return "%s.%s" % (cy, self.attribute)
3318
3319     def coerce_to(self, dst_type, env):
3320         #  If coercing to a generic pyobject and this is a cpdef function
3321         #  we can create the corresponding attribute
3322         if dst_type is py_object_type:
3323             entry = self.entry
3324             if entry and entry.is_cfunction and entry.as_variable:
3325                 # must be a cpdef function
3326                 self.is_temp = 1
3327                 self.entry = entry.as_variable
3328                 self.analyse_as_python_attribute(env)
3329                 return self
3330         return ExprNode.coerce_to(self, dst_type, env)
3331
3332     def calculate_constant_result(self):
3333         attr = self.attribute
3334         if attr.startswith("__") and attr.endswith("__"):
3335             return
3336         self.constant_result = getattr(self.obj.constant_result, attr)
3337
3338     def compile_time_value(self, denv):
3339         attr = self.attribute
3340         if attr.startswith("__") and attr.endswith("__"):
3341             error(self.pos,
3342                   "Invalid attribute name '%s' in compile-time expression" % attr)
3343             return None
3344         obj = self.obj.compile_time_value(denv)
3345         try:
3346             return getattr(obj, attr)
3347         except Exception, e:
3348             self.compile_time_value_error(e)
3349
3350     def type_dependencies(self, env):
3351         return self.obj.type_dependencies(env)
3352
3353     def infer_type(self, env):
3354         if self.analyse_as_cimported_attribute(env, 0):
3355             return self.entry.type
3356         elif self.analyse_as_unbound_cmethod(env):
3357             return self.entry.type
3358         else:
3359             obj_type = self.obj.infer_type(env)
3360             self.analyse_attribute(env, obj_type = obj_type)
3361             if obj_type.is_builtin_type and self.type.is_cfunction:
3362                 # special case: C-API replacements for C methods of
3363                 # builtin types cannot be inferred as C functions as
3364                 # that would prevent their use as bound methods
3365                 self.type = py_object_type
3366                 return py_object_type
3367             return self.type
3368
3369     def analyse_target_declaration(self, env):
3370         pass
3371
3372     def analyse_target_types(self, env):
3373         self.analyse_types(env, target = 1)
3374
3375     def analyse_types(self, env, target = 0):
3376         if self.analyse_as_cimported_attribute(env, target):
3377             return
3378         if not target and self.analyse_as_unbound_cmethod(env):
3379             return
3380         self.analyse_as_ordinary_attribute(env, target)
3381
3382     def analyse_as_cimported_attribute(self, env, target):
3383         # Try to interpret this as a reference to an imported
3384         # C const, type, var or function. If successful, mutates
3385         # this node into a NameNode and returns 1, otherwise
3386         # returns 0.
3387         module_scope = self.obj.analyse_as_module(env)
3388         if module_scope:
3389             entry = module_scope.lookup_here(self.attribute)
3390             if entry and (
3391                 entry.is_cglobal or entry.is_cfunction
3392                 or entry.is_type or entry.is_const):
3393                     self.mutate_into_name_node(env, entry, target)
3394                     return 1
3395         return 0
3396
3397     def analyse_as_unbound_cmethod(self, env):
3398         # Try to interpret this as a reference to an unbound
3399         # C method of an extension type. If successful, mutates
3400         # this node into a NameNode and returns 1, otherwise
3401         # returns 0.
3402         type = self.obj.analyse_as_extension_type(env)
3403         if type:
3404             entry = type.scope.lookup_here(self.attribute)
3405             if entry and entry.is_cmethod:
3406                 # Create a temporary entry describing the C method
3407                 # as an ordinary function.
3408                 ubcm_entry = Symtab.Entry(entry.name,
3409                     "%s->%s" % (type.vtabptr_cname, entry.cname),
3410                     entry.type)
3411                 ubcm_entry.is_cfunction = 1
3412                 ubcm_entry.func_cname = entry.func_cname
3413                 ubcm_entry.is_unbound_cmethod = 1
3414                 self.mutate_into_name_node(env, ubcm_entry, None)
3415                 return 1
3416         return 0
3417
3418     def analyse_as_type(self, env):
3419         module_scope = self.obj.analyse_as_module(env)
3420         if module_scope:
3421             return module_scope.lookup_type(self.attribute)
3422         if not isinstance(self.obj, (UnicodeNode, StringNode, BytesNode)):
3423             base_type = self.obj.analyse_as_type(env)
3424             if base_type and hasattr(base_type, 'scope') and base_type.scope is not None:
3425                 return base_type.scope.lookup_type(self.attribute)
3426         return None
3427
3428     def analyse_as_extension_type(self, env):
3429         # Try to interpret this as a reference to an extension type
3430         # in a cimported module. Returns the extension type, or None.
3431         module_scope = self.obj.analyse_as_module(env)
3432         if module_scope:
3433             entry = module_scope.lookup_here(self.attribute)
3434             if entry and entry.is_type and entry.type.is_extension_type:
3435                 return entry.type
3436         return None
3437
3438     def analyse_as_module(self, env):
3439         # Try to interpret this as a reference to a cimported module
3440         # in another cimported module. Returns the module scope, or None.
3441         module_scope = self.obj.analyse_as_module(env)
3442         if module_scope:
3443             entry = module_scope.lookup_here(self.attribute)
3444             if entry and entry.as_module:
3445                 return entry.as_module
3446         return None
3447
3448     def mutate_into_name_node(self, env, entry, target):
3449         # Mutate this node into a NameNode and complete the
3450         # analyse_types phase.
3451         self.__class__ = NameNode
3452         self.name = self.attribute
3453         self.entry = entry
3454         del self.obj
3455         del self.attribute
3456         if target:
3457             NameNode.analyse_target_types(self, env)
3458         else:
3459             NameNode.analyse_rvalue_entry(self, env)
3460
3461     def analyse_as_ordinary_attribute(self, env, target):
3462         self.obj.analyse_types(env)
3463         self.analyse_attribute(env)
3464         if self.entry and self.entry.is_cmethod and not self.is_called:
3465 #            error(self.pos, "C method can only be called")
3466             pass
3467         ## Reference to C array turns into pointer to first element.
3468         #while self.type.is_array:
3469         #    self.type = self.type.element_ptr_type()
3470         if self.is_py_attr:
3471             if not target:
3472                 self.is_temp = 1
3473                 self.result_ctype = py_object_type
3474         elif target and self.obj.type.is_builtin_type:
3475             error(self.pos, "Assignment to an immutable object field")
3476
3477     def analyse_attribute(self, env, obj_type = None):
3478         # Look up attribute and set self.type and self.member.
3479         self.is_py_attr = 0
3480         self.member = self.attribute
3481         if obj_type is None:
3482             if self.obj.type.is_string:
3483                 self.obj = self.obj.coerce_to_pyobject(env)
3484             obj_type = self.obj.type
3485         else:
3486             if obj_type.is_string:
3487                 obj_type = py_object_type
3488         if obj_type.is_ptr or obj_type.is_array:
3489             obj_type = obj_type.base_type
3490             self.op = "->"
3491         elif obj_type.is_extension_type or obj_type.is_builtin_type:
3492             self.op = "->"
3493         else:
3494             self.op = "."
3495         if obj_type.has_attributes:
3496             entry = None
3497             if obj_type.attributes_known():
3498                 entry = obj_type.scope.lookup_here(self.attribute)
3499                 if entry and entry.is_member:
3500                     entry = None
3501             else:
3502                 error(self.pos,
3503                     "Cannot select attribute of incomplete type '%s'"
3504                     % obj_type)
3505                 self.type = PyrexTypes.error_type
3506                 return
3507             self.entry = entry
3508             if entry:
3509                 if obj_type.is_extension_type and entry.name == "__weakref__":
3510                     error(self.pos, "Illegal use of special attribute __weakref__")
3511                 # methods need the normal attribute lookup
3512                 # because they do not have struct entries
3513                 if entry.is_variable or entry.is_cmethod:
3514                     self.type = entry.type
3515                     self.member = entry.cname
3516                     return
3517                 else:
3518                     # If it's not a variable or C method, it must be a Python
3519                     # method of an extension type, so we treat it like a Python
3520                     # attribute.
3521                     pass
3522         # If we get here, the base object is not a struct/union/extension
3523         # type, or it is an extension type and the attribute is either not
3524         # declared or is declared as a Python method. Treat it as a Python
3525         # attribute reference.
3526         self.analyse_as_python_attribute(env, obj_type)
3527
3528     def analyse_as_python_attribute(self, env, obj_type = None):
3529         if obj_type is None:
3530             obj_type = self.obj.type
3531         self.member = self.attribute
3532         self.type = py_object_type
3533         self.is_py_attr = 1
3534         if not obj_type.is_pyobject and not obj_type.is_error:
3535             if obj_type.can_coerce_to_pyobject(env):
3536                 self.obj = self.obj.coerce_to_pyobject(env)
3537             else:
3538                 error(self.pos,
3539                       "Object of type '%s' has no attribute '%s'" %
3540                       (obj_type, self.attribute))
3541
3542     def nogil_check(self, env):
3543         if self.is_py_attr:
3544             self.gil_error()
3545
3546     gil_message = "Accessing Python attribute"
3547
3548     def is_simple(self):
3549         if self.obj:
3550             return self.result_in_temp() or self.obj.is_simple()
3551         else:
3552             return NameNode.is_simple(self)
3553
3554     def is_lvalue(self):
3555         if self.obj:
3556             return 1
3557         else:
3558             return NameNode.is_lvalue(self)
3559
3560     def is_ephemeral(self):
3561         if self.obj:
3562             return self.obj.is_ephemeral()
3563         else:
3564             return NameNode.is_ephemeral(self)
3565
3566     def calculate_result_code(self):
3567         #print "AttributeNode.calculate_result_code:", self.member ###
3568         #print "...obj node =", self.obj, "code", self.obj.result() ###
3569         #print "...obj type", self.obj.type, "ctype", self.obj.ctype() ###
3570         obj = self.obj
3571         obj_code = obj.result_as(obj.type)
3572         #print "...obj_code =", obj_code ###
3573         if self.entry and self.entry.is_cmethod:
3574             if obj.type.is_extension_type:
3575                 return "((struct %s *)%s%s%s)->%s" % (
3576                     obj.type.vtabstruct_cname, obj_code, self.op,
3577                     obj.type.vtabslot_cname, self.member)
3578             else:
3579                 return self.member
3580         elif obj.type.is_complex:
3581             return "__Pyx_C%s(%s)" % (self.member.upper(), obj_code)
3582         else:
3583             if obj.type.is_builtin_type and self.entry and self.entry.is_variable:
3584                 # accessing a field of a builtin type, need to cast better than result_as() does
3585                 obj_code = obj.type.cast_code(obj.result(), to_object_struct = True)
3586             return "%s%s%s" % (obj_code, self.op, self.member)
3587
3588     def generate_result_code(self, code):
3589         interned_attr_cname = code.intern_identifier(self.attribute)
3590         if self.is_py_attr:
3591             code.putln(
3592                 '%s = PyObject_GetAttr(%s, %s); %s' % (
3593                     self.result(),
3594                     self.obj.py_result(),
3595                     interned_attr_cname,
3596                     code.error_goto_if_null(self.result(), self.pos)))
3597             code.put_gotref(self.py_result())
3598         else:
3599             # result_code contains what is needed, but we may need to insert
3600             # a check and raise an exception
3601             if (self.obj.type.is_extension_type
3602                   and self.needs_none_check
3603                   and code.globalstate.directives['nonecheck']):
3604                 self.put_nonecheck(code)
3605
3606     def generate_assignment_code(self, rhs, code):
3607         interned_attr_cname = code.intern_identifier(self.attribute)
3608         self.obj.generate_evaluation_code(code)
3609         if self.is_py_attr:
3610             code.put_error_if_neg(self.pos,
3611                 'PyObject_SetAttr(%s, %s, %s)' % (
3612                     self.obj.py_result(),
3613                     interned_attr_cname,
3614                     rhs.py_result()))
3615             rhs.generate_disposal_code(code)
3616             rhs.free_temps(code)
3617         elif self.obj.type.is_complex:
3618             code.putln("__Pyx_SET_C%s(%s, %s);" % (
3619                 self.member.upper(),
3620                 self.obj.result_as(self.obj.type),
3621                 rhs.result_as(self.ctype())))
3622         else:
3623             if (self.obj.type.is_extension_type
3624                   and self.needs_none_check
3625                   and code.globalstate.directives['nonecheck']):
3626                 self.put_nonecheck(code)
3627
3628             select_code = self.result()
3629             if self.type.is_pyobject and self.use_managed_ref:
3630                 rhs.make_owned_reference(code)
3631                 code.put_giveref(rhs.py_result())
3632                 code.put_gotref(select_code)
3633                 code.put_decref(select_code, self.ctype())
3634             code.putln(
3635                 "%s = %s;" % (
3636                     select_code,
3637                     rhs.result_as(self.ctype())))
3638                     #rhs.result()))
3639             rhs.generate_post_assignment_code(code)
3640             rhs.free_temps(code)
3641         self.obj.generate_disposal_code(code)
3642         self.obj.free_temps(code)
3643
3644     def generate_deletion_code(self, code):
3645         interned_attr_cname = code.intern_identifier(self.attribute)
3646         self.obj.generate_evaluation_code(code)
3647         if self.is_py_attr or (isinstance(self.entry.scope, Symtab.PropertyScope)
3648                                and u'__del__' in self.entry.scope.entries):
3649             code.put_error_if_neg(self.pos,
3650                 'PyObject_DelAttr(%s, %s)' % (
3651                     self.obj.py_result(),
3652                     interned_attr_cname))
3653         else:
3654             error(self.pos, "Cannot delete C attribute of extension type")
3655         self.obj.generate_disposal_code(code)
3656         self.obj.free_temps(code)
3657
3658     def annotate(self, code):
3659         if self.is_py_attr:
3660             code.annotate(self.pos, AnnotationItem('py_attr', 'python attribute', size=len(self.attribute)))
3661         else:
3662             code.annotate(self.pos, AnnotationItem('c_attr', 'c attribute', size=len(self.attribute)))
3663
3664     def put_nonecheck(self, code):
3665         code.globalstate.use_utility_code(raise_noneattr_error_utility_code)
3666         code.putln("if (%s) {" % code.unlikely("%s == Py_None") % self.obj.result_as(PyrexTypes.py_object_type))
3667         code.putln("__Pyx_RaiseNoneAttributeError(\"%s\");" % self.attribute)
3668         code.putln(code.error_goto(self.pos))
3669         code.putln("}")
3670
3671
3672 #-------------------------------------------------------------------
3673 #
3674 #  Constructor nodes
3675 #
3676 #-------------------------------------------------------------------
3677
3678 class StarredTargetNode(ExprNode):
3679     #  A starred expression like "*a"
3680     #
3681     #  This is only allowed in sequence assignment targets such as
3682     #
3683     #      a, *b = (1,2,3,4)    =>     a = 1 ; b = [2,3,4]
3684     #
3685     #  and will be removed during type analysis (or generate an error
3686     #  if it's found at unexpected places).
3687     #
3688     #  target          ExprNode
3689
3690     subexprs = ['target']
3691     is_starred = 1
3692     type = py_object_type
3693     is_temp = 1
3694
3695     def __init__(self, pos, target):
3696         self.pos = pos
3697         self.target = target
3698
3699     def analyse_declarations(self, env):
3700         error(self.pos, "can use starred expression only as assignment target")
3701         self.target.analyse_declarations(env)
3702
3703     def analyse_types(self, env):
3704         error(self.pos, "can use starred expression only as assignment target")
3705         self.target.analyse_types(env)
3706         self.type = self.target.type
3707
3708     def analyse_target_declaration(self, env):
3709         self.target.analyse_target_declaration(env)
3710
3711     def analyse_target_types(self, env):
3712         self.target.analyse_target_types(env)
3713         self.type = self.target.type
3714
3715     def calculate_result_code(self):
3716         return ""
3717
3718     def generate_result_code(self, code):
3719         pass
3720
3721
3722 class SequenceNode(ExprNode):
3723     #  Base class for list and tuple constructor nodes.
3724     #  Contains common code for performing sequence unpacking.
3725     #
3726     #  args                    [ExprNode]
3727     #  iterator                ExprNode
3728     #  unpacked_items          [ExprNode] or None
3729     #  coerced_unpacked_items  [ExprNode] or None
3730
3731     subexprs = ['args']
3732
3733     is_sequence_constructor = 1
3734     unpacked_items = None
3735
3736     def compile_time_value_list(self, denv):
3737         return [arg.compile_time_value(denv) for arg in self.args]
3738
3739     def replace_starred_target_node(self):
3740         # replace a starred node in the targets by the contained expression
3741         self.starred_assignment = False
3742         args = []
3743         for arg in self.args:
3744             if arg.is_starred:
3745                 if self.starred_assignment:
3746                     error(arg.pos, "more than 1 starred expression in assignment")
3747                 self.starred_assignment = True
3748                 arg = arg.target
3749                 arg.is_starred = True
3750             args.append(arg)
3751         self.args = args
3752
3753     def analyse_target_declaration(self, env):
3754         self.replace_starred_target_node()
3755         for arg in self.args:
3756             arg.analyse_target_declaration(env)
3757
3758     def analyse_types(self, env, skip_children=False):
3759         for i in range(len(self.args)):
3760             arg = self.args[i]
3761             if not skip_children: arg.analyse_types(env)
3762             self.args[i] = arg.coerce_to_pyobject(env)
3763         self.is_temp = 1
3764         # not setting self.type here, subtypes do this
3765
3766     def may_be_none(self):
3767         return False
3768
3769     def analyse_target_types(self, env):
3770         self.iterator = PyTempNode(self.pos, env)
3771         self.unpacked_items = []
3772         self.coerced_unpacked_items = []
3773         for arg in self.args:
3774             arg.analyse_target_types(env)
3775             if arg.is_starred:
3776                 if not arg.type.assignable_from(Builtin.list_type):
3777                     error(arg.pos,
3778                           "starred target must have Python object (list) type")
3779                 if arg.type is py_object_type:
3780                     arg.type = Builtin.list_type
3781             unpacked_item = PyTempNode(self.pos, env)
3782             coerced_unpacked_item = unpacked_item.coerce_to(arg.type, env)
3783             self.unpacked_items.append(unpacked_item)
3784             self.coerced_unpacked_items.append(coerced_unpacked_item)
3785         self.type = py_object_type
3786
3787     def generate_result_code(self, code):
3788         self.generate_operation_code(code)
3789
3790     def generate_assignment_code(self, rhs, code):
3791         if self.starred_assignment:
3792             self.generate_starred_assignment_code(rhs, code)
3793         else:
3794             self.generate_parallel_assignment_code(rhs, code)
3795
3796         for item in self.unpacked_items:
3797             item.release(code)
3798         rhs.free_temps(code)
3799
3800     def generate_parallel_assignment_code(self, rhs, code):
3801         # Need to work around the fact that generate_evaluation_code
3802         # allocates the temps in a rather hacky way -- the assignment
3803         # is evaluated twice, within each if-block.
3804
3805         if rhs.type is tuple_type:
3806             tuple_check = "likely(%s != Py_None)"
3807         else:
3808             tuple_check = "PyTuple_CheckExact(%s)"
3809         code.putln(
3810             "if (%s && likely(PyTuple_GET_SIZE(%s) == %s)) {" % (
3811                 tuple_check % rhs.py_result(),
3812                 rhs.py_result(),
3813                 len(self.args)))
3814         code.putln("PyObject* tuple = %s;" % rhs.py_result())
3815         for item in self.unpacked_items:
3816             item.allocate(code)
3817         for i in range(len(self.args)):
3818             item = self.unpacked_items[i]
3819             code.put(
3820                 "%s = PyTuple_GET_ITEM(tuple, %s); " % (
3821                     item.result(),
3822                     i))
3823             code.put_incref(item.result(), item.ctype())
3824             value_node = self.coerced_unpacked_items[i]
3825             value_node.generate_evaluation_code(code)
3826         rhs.generate_disposal_code(code)
3827
3828         for i in range(len(self.args)):
3829             self.args[i].generate_assignment_code(
3830                 self.coerced_unpacked_items[i], code)
3831
3832         code.putln("} else {")
3833
3834         if rhs.type is tuple_type:
3835             code.globalstate.use_utility_code(tuple_unpacking_error_code)
3836             code.putln("__Pyx_UnpackTupleError(%s, %s);" % (
3837                         rhs.py_result(), len(self.args)))
3838             code.putln(code.error_goto(self.pos))
3839         else:
3840             code.globalstate.use_utility_code(unpacking_utility_code)
3841
3842             self.iterator.allocate(code)
3843             code.putln(
3844                 "%s = PyObject_GetIter(%s); %s" % (
3845                     self.iterator.result(),
3846                     rhs.py_result(),
3847                     code.error_goto_if_null(self.iterator.result(), self.pos)))
3848             code.put_gotref(self.iterator.py_result())
3849             rhs.generate_disposal_code(code)
3850             for i in range(len(self.args)):
3851                 item = self.unpacked_items[i]
3852                 unpack_code = "__Pyx_UnpackItem(%s, %d)" % (
3853                     self.iterator.py_result(), i)
3854                 code.putln(
3855                     "%s = %s; %s" % (
3856                         item.result(),
3857                         typecast(item.ctype(), py_object_type, unpack_code),
3858                         code.error_goto_if_null(item.result(), self.pos)))
3859                 code.put_gotref(item.py_result())
3860                 value_node = self.coerced_unpacked_items[i]
3861                 value_node.generate_evaluation_code(code)
3862             code.put_error_if_neg(self.pos, "__Pyx_EndUnpack(%s, %d)" % (
3863                 self.iterator.py_result(),
3864                 len(self.args)))
3865             if debug_disposal_code:
3866                 print("UnpackNode.generate_assignment_code:")
3867                 print("...generating disposal code for %s" % self.iterator)
3868             self.iterator.generate_disposal_code(code)
3869             self.iterator.free_temps(code)
3870             self.iterator.release(code)
3871
3872             for i in range(len(self.args)):
3873                 self.args[i].generate_assignment_code(
3874                     self.coerced_unpacked_items[i], code)
3875
3876         code.putln("}")
3877
3878     def generate_starred_assignment_code(self, rhs, code):
3879         code.globalstate.use_utility_code(unpacking_utility_code)
3880
3881         for i, arg in enumerate(self.args):
3882             if arg.is_starred:
3883                 starred_target = self.unpacked_items[i]
3884                 fixed_args_left  = self.args[:i]
3885                 fixed_args_right = self.args[i+1:]
3886                 break
3887
3888         self.iterator.allocate(code)
3889         code.putln(
3890             "%s = PyObject_GetIter(%s); %s" % (
3891                 self.iterator.result(),
3892                 rhs.py_result(),
3893                 code.error_goto_if_null(self.iterator.result(), self.pos)))
3894         code.put_gotref(self.iterator.py_result())
3895         rhs.generate_disposal_code(code)
3896
3897         for item in self.unpacked_items:
3898             item.allocate(code)
3899         for i in range(len(fixed_args_left)):
3900             item = self.unpacked_items[i]
3901             unpack_code = "__Pyx_UnpackItem(%s, %d)" % (
3902                 self.iterator.py_result(), i)
3903             code.putln(
3904                 "%s = %s; %s" % (
3905                     item.result(),
3906                     typecast(item.ctype(), py_object_type, unpack_code),
3907                     code.error_goto_if_null(item.result(), self.pos)))
3908             code.put_gotref(item.py_result())
3909             value_node = self.coerced_unpacked_items[i]
3910             value_node.generate_evaluation_code(code)
3911
3912         target_list = starred_target.result()
3913         code.putln("%s = PySequence_List(%s); %s" % (
3914             target_list, self.iterator.py_result(),
3915             code.error_goto_if_null(target_list, self.pos)))
3916         code.put_gotref(target_list)
3917         if fixed_args_right:
3918             code.globalstate.use_utility_code(raise_need_more_values_to_unpack)
3919             unpacked_right_args = self.unpacked_items[-len(fixed_args_right):]
3920             code.putln("if (unlikely(PyList_GET_SIZE(%s) < %d)) {" % (
3921                 (target_list, len(unpacked_right_args))))
3922             code.put("__Pyx_RaiseNeedMoreValuesError(%d+PyList_GET_SIZE(%s)); %s" % (
3923                      len(fixed_args_left), target_list,
3924                      code.error_goto(self.pos)))
3925             code.putln('}')
3926             for i, (arg, coerced_arg) in enumerate(zip(unpacked_right_args[::-1],
3927                                                        self.coerced_unpacked_items[::-1])):
3928                 code.putln(
3929                     "%s = PyList_GET_ITEM(%s, PyList_GET_SIZE(%s)-1); " % (
3930                         arg.py_result(),
3931                         target_list, target_list))
3932                 # resize the list the hard way
3933                 code.putln("((PyVarObject*)%s)->ob_size--;" % target_list)
3934                 code.put_gotref(arg.py_result())
3935                 coerced_arg.generate_evaluation_code(code)
3936
3937         self.iterator.generate_disposal_code(code)
3938         self.iterator.free_temps(code)
3939         self.iterator.release(code)
3940
3941         for i in range(len(self.args)):
3942             self.args[i].generate_assignment_code(
3943                 self.coerced_unpacked_items[i], code)
3944
3945     def annotate(self, code):
3946         for arg in self.args:
3947             arg.annotate(code)
3948         if self.unpacked_items:
3949             for arg in self.unpacked_items:
3950                 arg.annotate(code)
3951             for arg in self.coerced_unpacked_items:
3952                 arg.annotate(code)
3953
3954
3955 class TupleNode(SequenceNode):
3956     #  Tuple constructor.
3957
3958     type = tuple_type
3959
3960     gil_message = "Constructing Python tuple"
3961
3962     def analyse_types(self, env, skip_children=False):
3963         if len(self.args) == 0:
3964             self.is_temp = 0
3965             self.is_literal = 1
3966         else:
3967             SequenceNode.analyse_types(self, env, skip_children)
3968             for child in self.args:
3969                 if not child.is_literal:
3970                     break
3971             else:
3972                 self.is_temp = 0
3973                 self.is_literal = 1
3974
3975     def calculate_result_code(self):
3976         if len(self.args) > 0:
3977             return self.result_code
3978         else:
3979             return Naming.empty_tuple
3980
3981     def calculate_constant_result(self):
3982         self.constant_result = tuple([
3983                 arg.constant_result for arg in self.args])
3984
3985     def compile_time_value(self, denv):
3986         values = self.compile_time_value_list(denv)
3987         try:
3988             return tuple(values)
3989         except Exception, e:
3990             self.compile_time_value_error(e)
3991
3992     def generate_operation_code(self, code):
3993         if len(self.args) == 0:
3994             # result_code is Naming.empty_tuple
3995             return
3996         if self.is_literal:
3997             # non-empty cached tuple => result is global constant,
3998             # creation code goes into separate code writer
3999             self.result_code = code.get_py_const(py_object_type, 'tuple_', cleanup_level=2)
4000             code = code.get_cached_constants_writer()
4001             code.mark_pos(self.pos)
4002
4003         code.putln(
4004             "%s = PyTuple_New(%s); %s" % (
4005                 self.result(),
4006                 len(self.args),
4007                 code.error_goto_if_null(self.result(), self.pos)))
4008         code.put_gotref(self.py_result())
4009         for i in range(len(self.args)):
4010             arg = self.args[i]
4011             if not arg.result_in_temp():
4012                 code.put_incref(arg.result(), arg.ctype())
4013             code.putln(
4014                 "PyTuple_SET_ITEM(%s, %s, %s);" % (
4015                     self.result(),
4016                     i,
4017                     arg.py_result()))
4018             code.put_giveref(arg.py_result())
4019         if self.is_literal:
4020             code.put_giveref(self.py_result())
4021
4022     def generate_subexpr_disposal_code(self, code):
4023         # We call generate_post_assignment_code here instead
4024         # of generate_disposal_code, because values were stored
4025         # in the tuple using a reference-stealing operation.
4026         for arg in self.args:
4027             arg.generate_post_assignment_code(code)
4028             # Should NOT call free_temps -- this is invoked by the default
4029             # generate_evaluation_code which will do that.
4030
4031
4032 class ListNode(SequenceNode):
4033     #  List constructor.
4034
4035     # obj_conversion_errors    [PyrexError]   used internally
4036     # orignial_args            [ExprNode]     used internally
4037
4038     obj_conversion_errors = []
4039     type = list_type
4040
4041     gil_message = "Constructing Python list"
4042
4043     def type_dependencies(self, env):
4044         return ()
4045
4046     def infer_type(self, env):
4047         # TOOD: Infer non-object list arrays.
4048         return list_type
4049
4050     def analyse_expressions(self, env):
4051         SequenceNode.analyse_expressions(self, env)
4052         self.coerce_to_pyobject(env)
4053
4054     def analyse_types(self, env):
4055         hold_errors()
4056         self.original_args = list(self.args)
4057         SequenceNode.analyse_types(self, env)
4058         self.obj_conversion_errors = held_errors()
4059         release_errors(ignore=True)
4060
4061     def coerce_to(self, dst_type, env):
4062         if dst_type.is_pyobject:
4063             for err in self.obj_conversion_errors:
4064                 report_error(err)
4065             self.obj_conversion_errors = []
4066             if not self.type.subtype_of(dst_type):
4067                 error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
4068         elif dst_type.is_ptr and dst_type.base_type is not PyrexTypes.c_void_type:
4069             base_type = dst_type.base_type
4070             self.type = PyrexTypes.CArrayType(base_type, len(self.args))
4071             for i in range(len(self.original_args)):
4072                 arg = self.args[i]
4073                 if isinstance(arg, CoerceToPyTypeNode):
4074                     arg = arg.arg
4075                 self.args[i] = arg.coerce_to(base_type, env)
4076         elif dst_type.is_struct:
4077             if len(self.args) > len(dst_type.scope.var_entries):
4078                 error(self.pos, "Too may members for '%s'" % dst_type)
4079             else:
4080                 if len(self.args) < len(dst_type.scope.var_entries):
4081                     warning(self.pos, "Too few members for '%s'" % dst_type, 1)
4082                 for i, (arg, member) in enumerate(zip(self.original_args, dst_type.scope.var_entries)):
4083                     if isinstance(arg, CoerceToPyTypeNode):
4084                         arg = arg.arg
4085                     self.args[i] = arg.coerce_to(member.type, env)
4086             self.type = dst_type
4087         else:
4088             self.type = error_type
4089             error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
4090         return self
4091
4092     def release_temp(self, env):
4093         if self.type.is_array:
4094             # To be valid C++, we must allocate the memory on the stack
4095             # manually and be sure not to reuse it for something else.
4096             pass
4097         else:
4098             SequenceNode.release_temp(self, env)
4099
4100     def calculate_constant_result(self):
4101         self.constant_result = [
4102             arg.constant_result for arg in self.args]
4103
4104     def compile_time_value(self, denv):
4105         return self.compile_time_value_list(denv)
4106
4107     def generate_operation_code(self, code):
4108         if self.type.is_pyobject:
4109             for err in self.obj_conversion_errors:
4110                 report_error(err)
4111             code.putln("%s = PyList_New(%s); %s" %
4112                 (self.result(),
4113                 len(self.args),
4114                 code.error_goto_if_null(self.result(), self.pos)))
4115             code.put_gotref(self.py_result())
4116             for i in range(len(self.args)):
4117                 arg = self.args[i]
4118                 #if not arg.is_temp:
4119                 if not arg.result_in_temp():
4120                     code.put_incref(arg.result(), arg.ctype())
4121                 code.putln("PyList_SET_ITEM(%s, %s, %s);" %
4122                     (self.result(),
4123                     i,
4124                     arg.py_result()))
4125                 code.put_giveref(arg.py_result())
4126         elif self.type.is_array:
4127             for i, arg in enumerate(self.args):
4128                 code.putln("%s[%s] = %s;" % (
4129                                 self.result(),
4130                                 i,
4131                                 arg.result()))
4132         elif self.type.is_struct:
4133             for arg, member in zip(self.args, self.type.scope.var_entries):
4134                 code.putln("%s.%s = %s;" % (
4135                         self.result(),
4136                         member.cname,
4137                         arg.result()))
4138         else:
4139             raise InternalError("List type never specified")
4140
4141     def generate_subexpr_disposal_code(self, code):
4142         # We call generate_post_assignment_code here instead
4143         # of generate_disposal_code, because values were stored
4144         # in the list using a reference-stealing operation.
4145         for arg in self.args:
4146             arg.generate_post_assignment_code(code)
4147             # Should NOT call free_temps -- this is invoked by the default
4148             # generate_evaluation_code which will do that.
4149
4150
4151 class ScopedExprNode(ExprNode):
4152     # Abstract base class for ExprNodes that have their own local
4153     # scope, such as generator expressions.
4154     #
4155     # expr_scope    Scope  the inner scope of the expression
4156
4157     subexprs = []
4158     expr_scope = None
4159
4160     # does this node really have a local scope, e.g. does it leak loop
4161     # variables or not?  non-leaking Py3 behaviour is default, except
4162     # for list comprehensions where the behaviour differs in Py2 and
4163     # Py3 (set in Parsing.py based on parser context)
4164     has_local_scope = True
4165
4166     def init_scope(self, outer_scope, expr_scope=None):
4167         if expr_scope is not None:
4168             self.expr_scope = expr_scope
4169         elif self.has_local_scope:
4170             self.expr_scope = Symtab.GeneratorExpressionScope(outer_scope)
4171         else:
4172             self.expr_scope = None
4173
4174     def analyse_declarations(self, env):
4175         self.init_scope(env)
4176
4177     def analyse_scoped_declarations(self, env):
4178         # this is called with the expr_scope as env
4179         pass
4180
4181     def analyse_types(self, env):
4182         # no recursion here, the children will be analysed separately below
4183         pass
4184
4185     def analyse_scoped_expressions(self, env):
4186         # this is called with the expr_scope as env
4187         pass
4188
4189     def generate_evaluation_code(self, code):
4190         # set up local variables and free their references on exit
4191         generate_inner_evaluation_code = super(ScopedExprNode, self).generate_evaluation_code
4192         if not self.has_local_scope or not self.expr_scope.var_entries:
4193             # no local variables => delegate, done
4194             generate_inner_evaluation_code(code)
4195             return
4196
4197         code.putln('{ /* enter inner scope */')
4198         py_entries = []
4199         for entry in self.expr_scope.var_entries:
4200             if not entry.in_closure:
4201                 code.put_var_declaration(entry)
4202                 if entry.type.is_pyobject and entry.used:
4203                     py_entries.append(entry)
4204         if not py_entries:
4205             # no local Python references => no cleanup required
4206             generate_inner_evaluation_code(code)
4207             code.putln('} /* exit inner scope */')
4208             return
4209         for entry in py_entries:
4210             code.put_init_var_to_py_none(entry)
4211
4212         # must free all local Python references at each exit point
4213         old_loop_labels = tuple(code.new_loop_labels())
4214         old_error_label = code.new_error_label()
4215
4216         generate_inner_evaluation_code(code)
4217
4218         # normal (non-error) exit
4219         for entry in py_entries:
4220             code.put_var_decref(entry)
4221
4222         # error/loop body exit points
4223         exit_scope = code.new_label('exit_scope')
4224         code.put_goto(exit_scope)
4225         for label, old_label in ([(code.error_label, old_error_label)] +
4226                                  list(zip(code.get_loop_labels(), old_loop_labels))):
4227             if code.label_used(label):
4228                 code.put_label(label)
4229                 for entry in py_entries:
4230                     code.put_var_decref(entry)
4231                 code.put_goto(old_label)
4232         code.put_label(exit_scope)
4233         code.putln('} /* exit inner scope */')
4234
4235         code.set_loop_labels(old_loop_labels)
4236         code.error_label = old_error_label
4237
4238
4239 class ComprehensionNode(ScopedExprNode):
4240     subexprs = ["target"]
4241     child_attrs = ["loop", "append"]
4242
4243     def infer_type(self, env):
4244         return self.target.infer_type(env)
4245
4246     def analyse_declarations(self, env):
4247         self.append.target = self # this is used in the PyList_Append of the inner loop
4248         self.init_scope(env)
4249
4250     def analyse_scoped_declarations(self, env):
4251         self.loop.analyse_declarations(env)
4252
4253     def analyse_types(self, env):
4254         self.target.analyse_expressions(env)
4255         self.type = self.target.type
4256         if not self.has_local_scope:
4257             self.loop.analyse_expressions(env)
4258
4259     def analyse_scoped_expressions(self, env):
4260         if self.has_local_scope:
4261             self.loop.analyse_expressions(env)
4262
4263     def may_be_none(self):
4264         return False
4265
4266     def calculate_result_code(self):
4267         return self.target.result()
4268
4269     def generate_result_code(self, code):
4270         self.generate_operation_code(code)
4271
4272     def generate_operation_code(self, code):
4273         self.loop.generate_execution_code(code)
4274
4275     def annotate(self, code):
4276         self.loop.annotate(code)
4277
4278
4279 class ComprehensionAppendNode(Node):
4280     # Need to be careful to avoid infinite recursion:
4281     # target must not be in child_attrs/subexprs
4282
4283     child_attrs = ['expr']
4284
4285     type = PyrexTypes.c_int_type
4286
4287     def analyse_expressions(self, env):
4288         self.expr.analyse_expressions(env)
4289         if not self.expr.type.is_pyobject:
4290             self.expr = self.expr.coerce_to_pyobject(env)
4291
4292     def generate_execution_code(self, code):
4293         if self.target.type is list_type:
4294             function = "PyList_Append"
4295         elif self.target.type is set_type:
4296             function = "PySet_Add"
4297         else:
4298             raise InternalError(
4299                 "Invalid type for comprehension node: %s" % self.target.type)
4300
4301         self.expr.generate_evaluation_code(code)
4302         code.putln(code.error_goto_if("%s(%s, (PyObject*)%s)" % (
4303             function,
4304             self.target.result(),
4305             self.expr.result()
4306             ), self.pos))
4307         self.expr.generate_disposal_code(code)
4308         self.expr.free_temps(code)
4309
4310     def generate_function_definitions(self, env, code):
4311         self.expr.generate_function_definitions(env, code)
4312
4313     def annotate(self, code):
4314         self.expr.annotate(code)
4315
4316 class DictComprehensionAppendNode(ComprehensionAppendNode):
4317     child_attrs = ['key_expr', 'value_expr']
4318
4319     def analyse_expressions(self, env):
4320         self.key_expr.analyse_expressions(env)
4321         if not self.key_expr.type.is_pyobject:
4322             self.key_expr = self.key_expr.coerce_to_pyobject(env)
4323         self.value_expr.analyse_expressions(env)
4324         if not self.value_expr.type.is_pyobject:
4325             self.value_expr = self.value_expr.coerce_to_pyobject(env)
4326
4327     def generate_execution_code(self, code):
4328         self.key_expr.generate_evaluation_code(code)
4329         self.value_expr.generate_evaluation_code(code)
4330         code.putln(code.error_goto_if("PyDict_SetItem(%s, (PyObject*)%s, (PyObject*)%s)" % (
4331             self.target.result(),
4332             self.key_expr.result(),
4333             self.value_expr.result()
4334             ), self.pos))
4335         self.key_expr.generate_disposal_code(code)
4336         self.key_expr.free_temps(code)
4337         self.value_expr.generate_disposal_code(code)
4338         self.value_expr.free_temps(code)
4339
4340     def generate_function_definitions(self, env, code):
4341         self.key_expr.generate_function_definitions(env, code)
4342         self.value_expr.generate_function_definitions(env, code)
4343
4344     def annotate(self, code):
4345         self.key_expr.annotate(code)
4346         self.value_expr.annotate(code)
4347
4348
4349 class GeneratorExpressionNode(ScopedExprNode):
4350     # A generator expression, e.g.  (i for i in range(10))
4351     #
4352     # Result is a generator.
4353     #
4354     # loop      ForStatNode   the for-loop, containing a YieldExprNode
4355
4356     child_attrs = ["loop"]
4357
4358     type = py_object_type
4359
4360     def analyse_scoped_declarations(self, env):
4361         self.loop.analyse_declarations(env)
4362
4363     def analyse_types(self, env):
4364         if not self.has_local_scope:
4365             self.loop.analyse_expressions(env)
4366         self.is_temp = True
4367
4368     def analyse_scoped_expressions(self, env):
4369         if self.has_local_scope:
4370             self.loop.analyse_expressions(env)
4371
4372     def may_be_none(self):
4373         return False
4374
4375     def annotate(self, code):
4376         self.loop.annotate(code)
4377
4378
4379 class InlinedGeneratorExpressionNode(GeneratorExpressionNode):
4380     # An inlined generator expression for which the result is
4381     # calculated inside of the loop.  This will only be created by
4382     # transforms when replacing builtin calls on generator
4383     # expressions.
4384     #
4385     # loop           ForStatNode      the for-loop, not containing any YieldExprNodes
4386     # result_node    ResultRefNode    the reference to the result value temp
4387     # orig_func      String           the name of the builtin function this node replaces
4388
4389     child_attrs = ["loop"]
4390     loop_analysed = False
4391
4392     def infer_type(self, env):
4393         return self.result_node.infer_type(env)
4394
4395     def analyse_types(self, env):
4396         if not self.has_local_scope:
4397             self.loop_analysed = True
4398             self.loop.analyse_expressions(env)
4399         self.type = self.result_node.type
4400         self.is_temp = True
4401
4402     def analyse_scoped_expressions(self, env):
4403         self.loop_analysed = True
4404         GeneratorExpressionNode.analyse_scoped_expressions(self, env)
4405
4406     def coerce_to(self, dst_type, env):
4407         if self.orig_func == 'sum' and dst_type.is_numeric and not self.loop_analysed:
4408             # We can optimise by dropping the aggregation variable and
4409             # the add operations into C.  This can only be done safely
4410             # before analysing the loop body, after that, the result
4411             # reference type will have infected expressions and
4412             # assignments.
4413             self.result_node.type = self.type = dst_type
4414             return self
4415         return GeneratorExpressionNode.coerce_to(self, dst_type, env)
4416
4417     def generate_result_code(self, code):
4418         self.result_node.result_code = self.result()
4419         self.loop.generate_execution_code(code)
4420
4421
4422 class SetNode(ExprNode):
4423     #  Set constructor.
4424
4425     type = set_type
4426
4427     subexprs = ['args']
4428
4429     gil_message = "Constructing Python set"
4430
4431     def analyse_types(self, env):
4432         for i in range(len(self.args)):
4433             arg = self.args[i]
4434             arg.analyse_types(env)
4435             self.args[i] = arg.coerce_to_pyobject(env)
4436         self.type = set_type
4437         self.is_temp = 1
4438
4439     def may_be_none(self):
4440         return False
4441
4442     def calculate_constant_result(self):
4443         self.constant_result = set([
4444                 arg.constant_result for arg in self.args])
4445
4446     def compile_time_value(self, denv):
4447         values = [arg.compile_time_value(denv) for arg in self.args]
4448         try:
4449             return set(values)
4450         except Exception, e:
4451             self.compile_time_value_error(e)
4452
4453     def generate_evaluation_code(self, code):
4454         code.globalstate.use_utility_code(Builtin.py23_set_utility_code)
4455         self.allocate_temp_result(code)
4456         code.putln(
4457             "%s = PySet_New(0); %s" % (
4458                 self.result(),
4459                 code.error_goto_if_null(self.result(), self.pos)))
4460         code.put_gotref(self.py_result())
4461         for arg in self.args:
4462             arg.generate_evaluation_code(code)
4463             code.putln(
4464                 code.error_goto_if_neg(
4465                     "PySet_Add(%s, %s)" % (self.result(), arg.py_result()),
4466                     self.pos))
4467             arg.generate_disposal_code(code)
4468             arg.free_temps(code)
4469
4470
4471 class DictNode(ExprNode):
4472     #  Dictionary constructor.
4473     #
4474     #  key_value_pairs  [DictItemNode]
4475     #
4476     # obj_conversion_errors    [PyrexError]   used internally
4477
4478     subexprs = ['key_value_pairs']
4479     is_temp = 1
4480     type = dict_type
4481
4482     obj_conversion_errors = []
4483
4484     def calculate_constant_result(self):
4485         self.constant_result = dict([
4486                 item.constant_result for item in self.key_value_pairs])
4487
4488     def compile_time_value(self, denv):
4489         pairs = [(item.key.compile_time_value(denv), item.value.compile_time_value(denv))
4490             for item in self.key_value_pairs]
4491         try:
4492             return dict(pairs)
4493         except Exception, e:
4494             self.compile_time_value_error(e)
4495
4496     def type_dependencies(self, env):
4497         return ()
4498
4499     def infer_type(self, env):
4500         # TOOD: Infer struct constructors.
4501         return dict_type
4502
4503     def analyse_types(self, env):
4504         hold_errors()
4505         for item in self.key_value_pairs:
4506             item.analyse_types(env)
4507         self.obj_conversion_errors = held_errors()
4508         release_errors(ignore=True)
4509
4510     def may_be_none(self):
4511         return False
4512
4513     def coerce_to(self, dst_type, env):
4514         if dst_type.is_pyobject:
4515             self.release_errors()
4516             if not self.type.subtype_of(dst_type):
4517                 error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
4518         elif dst_type.is_struct_or_union:
4519             self.type = dst_type
4520             if not dst_type.is_struct and len(self.key_value_pairs) != 1:
4521                 error(self.pos, "Exactly one field must be specified to convert to union '%s'" % dst_type)
4522             elif dst_type.is_struct and len(self.key_value_pairs) < len(dst_type.scope.var_entries):
4523                 warning(self.pos, "Not all members given for struct '%s'" % dst_type, 1)
4524             for item in self.key_value_pairs:
4525                 if isinstance(item.key, CoerceToPyTypeNode):
4526                     item.key = item.key.arg
4527                 if not isinstance(item.key, (UnicodeNode, StringNode, BytesNode)):
4528                     error(item.key.pos, "Invalid struct field identifier")
4529                     item.key = StringNode(item.key.pos, value="<error>")
4530                 else:
4531                     key = str(item.key.value) # converts string literals to unicode in Py3
4532                     member = dst_type.scope.lookup_here(key)
4533                     if not member:
4534                         error(item.key.pos, "struct '%s' has no field '%s'" % (dst_type, key))
4535                     else:
4536                         value = item.value
4537                         if isinstance(value, CoerceToPyTypeNode):
4538                             value = value.arg
4539                         item.value = value.coerce_to(member.type, env)
4540         else:
4541             self.type = error_type
4542             error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
4543         return self
4544
4545     def release_errors(self):
4546         for err in self.obj_conversion_errors:
4547             report_error(err)
4548         self.obj_conversion_errors = []
4549
4550     gil_message = "Constructing Python dict"
4551
4552     def generate_evaluation_code(self, code):
4553         #  Custom method used here because key-value
4554         #  pairs are evaluated and used one at a time.
4555         code.mark_pos(self.pos)
4556         self.allocate_temp_result(code)
4557         if self.type.is_pyobject:
4558             self.release_errors()
4559             code.putln(
4560                 "%s = PyDict_New(); %s" % (
4561                     self.result(),
4562                     code.error_goto_if_null(self.result(), self.pos)))
4563             code.put_gotref(self.py_result())
4564         for item in self.key_value_pairs:
4565             item.generate_evaluation_code(code)
4566             if self.type.is_pyobject:
4567                 code.put_error_if_neg(self.pos,
4568                     "PyDict_SetItem(%s, %s, %s)" % (
4569                         self.result(),
4570                         item.key.py_result(),
4571                         item.value.py_result()))
4572             else:
4573                 code.putln("%s.%s = %s;" % (
4574                         self.result(),
4575                         item.key.value,
4576                         item.value.result()))
4577             item.generate_disposal_code(code)
4578             item.free_temps(code)
4579
4580     def annotate(self, code):
4581         for item in self.key_value_pairs:
4582             item.annotate(code)
4583
4584 class DictItemNode(ExprNode):
4585     # Represents a single item in a DictNode
4586     #
4587     # key          ExprNode
4588     # value        ExprNode
4589     subexprs = ['key', 'value']
4590
4591     nogil_check = None # Parent DictNode takes care of it
4592
4593     def calculate_constant_result(self):
4594         self.constant_result = (
4595             self.key.constant_result, self.value.constant_result)
4596
4597     def analyse_types(self, env):
4598         self.key.analyse_types(env)
4599         self.value.analyse_types(env)
4600         self.key = self.key.coerce_to_pyobject(env)
4601         self.value = self.value.coerce_to_pyobject(env)
4602
4603     def generate_evaluation_code(self, code):
4604         self.key.generate_evaluation_code(code)
4605         self.value.generate_evaluation_code(code)
4606
4607     def generate_disposal_code(self, code):
4608         self.key.generate_disposal_code(code)
4609         self.value.generate_disposal_code(code)
4610
4611     def free_temps(self, code):
4612         self.key.free_temps(code)
4613         self.value.free_temps(code)
4614
4615     def __iter__(self):
4616         return iter([self.key, self.value])
4617
4618 class ModuleNameMixin(object):
4619     def set_mod_name(self, env):
4620         self.module_name = env.global_scope().qualified_name
4621
4622     def get_py_mod_name(self, code):
4623         return code.get_py_string_const(
4624                  self.module_name, identifier=True)
4625
4626 class ClassNode(ExprNode, ModuleNameMixin):
4627     #  Helper class used in the implementation of Python
4628     #  class definitions. Constructs a class object given
4629     #  a name, tuple of bases and class dictionary.
4630     #
4631     #  name         EncodedString      Name of the class
4632     #  bases        ExprNode           Base class tuple
4633     #  dict         ExprNode           Class dict (not owned by this node)
4634     #  doc          ExprNode or None   Doc string
4635     #  module_name  EncodedString      Name of defining module
4636
4637     subexprs = ['bases', 'doc']
4638
4639     def analyse_types(self, env):
4640         self.bases.analyse_types(env)
4641         if self.doc:
4642             self.doc.analyse_types(env)
4643             self.doc = self.doc.coerce_to_pyobject(env)
4644         self.type = py_object_type
4645         self.is_temp = 1
4646         env.use_utility_code(create_class_utility_code);
4647         #TODO(craig,haoyu) This should be moved to a better place
4648         self.set_mod_name(env)
4649
4650     def may_be_none(self):
4651         return True
4652
4653     gil_message = "Constructing Python class"
4654
4655     def generate_result_code(self, code):
4656         cname = code.intern_identifier(self.name)
4657
4658         if self.doc:
4659             code.put_error_if_neg(self.pos,
4660                 'PyDict_SetItemString(%s, "__doc__", %s)' % (
4661                     self.dict.py_result(),
4662                     self.doc.py_result()))
4663         py_mod_name = self.get_py_mod_name(code)
4664         code.putln(
4665             '%s = __Pyx_CreateClass(%s, %s, %s, %s); %s' % (
4666                 self.result(),
4667                 self.bases.py_result(),
4668                 self.dict.py_result(),
4669                 cname,
4670                 py_mod_name,
4671                 code.error_goto_if_null(self.result(), self.pos)))
4672         code.put_gotref(self.py_result())
4673
4674
4675 class Py3ClassNode(ExprNode):
4676     #  Helper class used in the implementation of Python3+
4677     #  class definitions. Constructs a class object given
4678     #  a name, tuple of bases and class dictionary.
4679     #
4680     #  name         EncodedString      Name of the class
4681     #  dict         ExprNode           Class dict (not owned by this node)
4682     #  module_name  EncodedString      Name of defining module
4683
4684     subexprs = []
4685
4686     def analyse_types(self, env):
4687         self.type = py_object_type
4688         self.is_temp = 1
4689
4690     def may_be_none(self):
4691         return True
4692
4693     gil_message = "Constructing Python class"
4694
4695     def generate_result_code(self, code):
4696         code.globalstate.use_utility_code(create_py3class_utility_code)
4697         cname = code.intern_identifier(self.name)
4698         code.putln(
4699             '%s = __Pyx_Py3ClassCreate(%s, %s, %s, %s, %s); %s' % (
4700                 self.result(),
4701                 self.metaclass.result(),
4702                 cname,
4703                 self.bases.py_result(),
4704                 self.dict.py_result(),
4705                 self.mkw.py_result(),
4706                 code.error_goto_if_null(self.result(), self.pos)))
4707         code.put_gotref(self.py_result())
4708
4709 class KeywordArgsNode(ExprNode):
4710     # Helper class for keyword arguments
4711     #
4712     # keyword_args ExprNode or None     Keyword arguments
4713     # starstar_arg ExprNode or None     Extra arguments
4714
4715     subexprs = ['keyword_args', 'starstar_arg']
4716
4717     def analyse_types(self, env):
4718         if self.keyword_args:
4719             self.keyword_args.analyse_types(env)
4720         if self.starstar_arg:
4721             self.starstar_arg.analyse_types(env)
4722             # make sure we have a Python object as **kwargs mapping
4723             self.starstar_arg = \
4724                 self.starstar_arg.coerce_to_pyobject(env)
4725         self.type = py_object_type
4726         self.is_temp = 1
4727
4728     gil_message = "Constructing Keyword Args"
4729
4730     def generate_result_code(self, code):
4731         if self.keyword_args and self.starstar_arg:
4732             code.put_error_if_neg(self.pos,
4733                 "PyDict_Update(%s, %s)" % (
4734                     self.keyword_args.py_result(),
4735                     self.starstar_arg.py_result()))
4736         if self.keyword_args:
4737             code.putln("%s = %s;" % (self.result(), self.keyword_args.result()))
4738             code.put_incref(self.keyword_args.result(), self.keyword_args.ctype())
4739         elif self.starstar_arg:
4740             code.putln(
4741                 "%s = PyDict_Copy(%s); %s" % (
4742                     self.result(),
4743                     self.starstar_arg.py_result(),
4744                     code.error_goto_if_null(self.result(), self.pos)))
4745             code.put_gotref(self.py_result())
4746         else:
4747             code.putln(
4748                 "%s = PyDict_New(); %s" % (
4749                     self.result(),
4750                     code.error_goto_if_null(self.result(), self.pos)))
4751             code.put_gotref(self.py_result())
4752
4753 class PyClassMetaclassNode(ExprNode):
4754     # Helper class holds Python3 metaclass object
4755     #
4756     #  bases        ExprNode           Base class tuple (not owned by this node)
4757     #  mkw          ExprNode           Class keyword arguments (not owned by this node)
4758
4759     subexprs = []
4760
4761     def analyse_types(self, env):
4762         self.type = py_object_type
4763         self.is_temp = True
4764
4765     def may_be_none(self):
4766         return True
4767
4768     def generate_result_code(self, code):
4769         code.putln(
4770             "%s = __Pyx_Py3MetaclassGet(%s, %s); %s" % (
4771                 self.result(),
4772                 self.bases.result(),
4773                 self.mkw.result(),
4774                 code.error_goto_if_null(self.result(), self.pos)))
4775         code.put_gotref(self.py_result())
4776
4777 class PyClassNamespaceNode(ExprNode, ModuleNameMixin):
4778     # Helper class holds Python3 namespace object
4779     #
4780     # All this are not owned by this node
4781     #  metaclass    ExprNode           Metaclass object
4782     #  bases        ExprNode           Base class tuple
4783     #  mkw          ExprNode           Class keyword arguments
4784     #  doc          ExprNode or None   Doc string (owned)
4785
4786     subexprs = ['doc']
4787
4788     def analyse_types(self, env):
4789         self.bases.analyse_types(env)
4790         if self.doc:
4791             self.doc.analyse_types(env)
4792             self.doc = self.doc.coerce_to_pyobject(env)
4793         self.type = py_object_type
4794         self.is_temp = 1
4795         #TODO(craig,haoyu) This should be moved to a better place
4796         self.set_mod_name(env)
4797
4798     def may_be_none(self):
4799         return True
4800
4801     def generate_result_code(self, code):
4802         cname = code.intern_identifier(self.name)
4803         py_mod_name = self.get_py_mod_name(code)
4804         if self.doc:
4805             doc_code = self.doc.result()
4806         else:
4807             doc_code = '(PyObject *) NULL'
4808         code.putln(
4809             "%s = __Pyx_Py3MetaclassPrepare(%s, %s, %s, %s, %s, %s); %s" % (
4810                 self.result(),
4811                 self.metaclass.result(),
4812                 self.bases.result(),
4813                 cname,
4814                 self.mkw.result(),
4815                 py_mod_name,
4816                 doc_code,
4817                 code.error_goto_if_null(self.result(), self.pos)))
4818         code.put_gotref(self.py_result())
4819
4820 class BoundMethodNode(ExprNode):
4821     #  Helper class used in the implementation of Python
4822     #  class definitions. Constructs an bound method
4823     #  object from a class and a function.
4824     #
4825     #  function      ExprNode   Function object
4826     #  self_object   ExprNode   self object
4827
4828     subexprs = ['function']
4829
4830     def analyse_types(self, env):
4831         self.function.analyse_types(env)
4832         self.type = py_object_type
4833         self.is_temp = 1
4834
4835     gil_message = "Constructing an bound method"
4836
4837     def generate_result_code(self, code):
4838         code.putln(
4839             "%s = PyMethod_New(%s, %s, (PyObject*)%s->ob_type); %s" % (
4840                 self.result(),
4841                 self.function.py_result(),
4842                 self.self_object.py_result(),
4843                 self.self_object.py_result(),
4844                 code.error_goto_if_null(self.result(), self.pos)))
4845         code.put_gotref(self.py_result())
4846
4847 class UnboundMethodNode(ExprNode):
4848     #  Helper class used in the implementation of Python
4849     #  class definitions. Constructs an unbound method
4850     #  object from a class and a function.
4851     #
4852     #  function      ExprNode   Function object
4853
4854     type = py_object_type
4855     is_temp = 1
4856
4857     subexprs = ['function']
4858
4859     def analyse_types(self, env):
4860         self.function.analyse_types(env)
4861
4862     def may_be_none(self):
4863         return False
4864
4865     gil_message = "Constructing an unbound method"
4866
4867     def generate_result_code(self, code):
4868         class_cname = code.pyclass_stack[-1].classobj.result()
4869         code.putln(
4870             "%s = PyMethod_New(%s, 0, %s); %s" % (
4871                 self.result(),
4872                 self.function.py_result(),
4873                 class_cname,
4874                 code.error_goto_if_null(self.result(), self.pos)))
4875         code.put_gotref(self.py_result())
4876
4877
4878 class PyCFunctionNode(ExprNode, ModuleNameMixin):
4879     #  Helper class used in the implementation of Python
4880     #  class definitions. Constructs a PyCFunction object
4881     #  from a PyMethodDef struct.
4882     #
4883     #  pymethdef_cname   string             PyMethodDef structure
4884     #  self_object       ExprNode or None
4885     #  binding           bool
4886     #  module_name       EncodedString      Name of defining module
4887
4888     subexprs = []
4889     self_object = None
4890     binding = False
4891
4892     type = py_object_type
4893     is_temp = 1
4894
4895     def analyse_types(self, env):
4896         if self.binding:
4897             env.use_utility_code(binding_cfunc_utility_code)
4898
4899         #TODO(craig,haoyu) This should be moved to a better place
4900         self.set_mod_name(env)
4901
4902     def may_be_none(self):
4903         return False
4904
4905     gil_message = "Constructing Python function"
4906
4907     def self_result_code(self):
4908         if self.self_object is None:
4909             self_result = "NULL"
4910         else:
4911             self_result = self.self_object.py_result()
4912         return self_result
4913
4914     def generate_result_code(self, code):
4915         if self.binding:
4916             constructor = "%s_NewEx" % Naming.binding_cfunc
4917         else:
4918             constructor = "PyCFunction_NewEx"
4919         py_mod_name = self.get_py_mod_name(code)
4920         code.putln(
4921             '%s = %s(&%s, %s, %s); %s' % (
4922                 self.result(),
4923                 constructor,
4924                 self.pymethdef_cname,
4925                 self.self_result_code(),
4926                 py_mod_name,
4927                 code.error_goto_if_null(self.result(), self.pos)))
4928         code.put_gotref(self.py_result())
4929
4930 class InnerFunctionNode(PyCFunctionNode):
4931     # Special PyCFunctionNode that depends on a closure class
4932     #
4933
4934     binding = True
4935     needs_self_code = True
4936
4937     def self_result_code(self):
4938         if self.needs_self_code:
4939             return "((PyObject*)%s)" % (Naming.cur_scope_cname)
4940         return "NULL"
4941
4942 class LambdaNode(InnerFunctionNode):
4943     # Lambda expression node (only used as a function reference)
4944     #
4945     # args          [CArgDeclNode]         formal arguments
4946     # star_arg      PyArgDeclNode or None  * argument
4947     # starstar_arg  PyArgDeclNode or None  ** argument
4948     # lambda_name   string                 a module-globally unique lambda name
4949     # result_expr   ExprNode
4950     # def_node      DefNode                the underlying function 'def' node
4951
4952     child_attrs = ['def_node']
4953
4954     def_node = None
4955     name = StringEncoding.EncodedString('<lambda>')
4956
4957     def analyse_declarations(self, env):
4958         self.def_node.analyse_declarations(env)
4959         self.pymethdef_cname = self.def_node.entry.pymethdef_cname
4960         env.add_lambda_def(self.def_node)
4961
4962 class YieldExprNode(ExprNode):
4963     # Yield expression node
4964     #
4965     # arg         ExprNode   the value to return from the generator
4966     # label_name  string     name of the C label used for this yield
4967
4968     subexprs = ['arg']
4969     type = py_object_type
4970
4971     def analyse_types(self, env):
4972         self.is_temp = 1
4973         if self.arg is not None:
4974             self.arg.analyse_types(env)
4975             if not self.arg.type.is_pyobject:
4976                 self.arg = self.arg.coerce_to_pyobject(env)
4977         error(self.pos, "Generators are not supported")
4978
4979     def generate_result_code(self, code):
4980         self.label_name = code.new_label('resume_from_yield')
4981         code.use_label(self.label_name)
4982         code.putln("/* FIXME: save temporary variables */")
4983         code.putln("/* FIXME: return from function, yielding value */")
4984         code.put_label(self.label_name)
4985         code.putln("/* FIXME: restore temporary variables and  */")
4986         code.putln("/* FIXME: extract sent value from closure */")
4987
4988
4989 #-------------------------------------------------------------------
4990 #
4991 #  Unary operator nodes
4992 #
4993 #-------------------------------------------------------------------
4994
4995 compile_time_unary_operators = {
4996     'not': operator.not_,
4997     '~': operator.inv,
4998     '-': operator.neg,
4999     '+': operator.pos,
5000 }
5001
5002 class UnopNode(ExprNode):
5003     #  operator     string
5004     #  operand      ExprNode
5005     #
5006     #  Processing during analyse_expressions phase:
5007     #
5008     #    analyse_c_operation
5009     #      Called when the operand is not a pyobject.
5010     #      - Check operand type and coerce if needed.
5011     #      - Determine result type and result code fragment.
5012     #      - Allocate temporary for result if needed.
5013
5014     subexprs = ['operand']
5015     infix = True
5016
5017     def calculate_constant_result(self):
5018         func = compile_time_unary_operators[self.operator]
5019         self.constant_result = func(self.operand.constant_result)
5020
5021     def compile_time_value(self, denv):
5022         func = compile_time_unary_operators.get(self.operator)
5023         if not func:
5024             error(self.pos,
5025                 "Unary '%s' not supported in compile-time expression"
5026                     % self.operator)
5027         operand = self.operand.compile_time_value(denv)
5028         try:
5029             return func(operand)
5030         except Exception, e:
5031             self.compile_time_value_error(e)
5032
5033     def infer_type(self, env):
5034         operand_type = self.operand.infer_type(env)
5035         if operand_type.is_pyobject:
5036             return py_object_type
5037         else:
5038             return operand_type
5039
5040     def analyse_types(self, env):
5041         self.operand.analyse_types(env)
5042         if self.is_py_operation():
5043             self.coerce_operand_to_pyobject(env)
5044             self.type = py_object_type
5045             self.is_temp = 1
5046         elif self.is_cpp_operation():
5047             self.analyse_cpp_operation(env)
5048         else:
5049             self.analyse_c_operation(env)
5050
5051     def check_const(self):
5052         return self.operand.check_const()
5053
5054     def is_py_operation(self):
5055         return self.operand.type.is_pyobject
5056
5057     def nogil_check(self, env):
5058         if self.is_py_operation():
5059             self.gil_error()
5060
5061     def is_cpp_operation(self):
5062         type = self.operand.type
5063         return type.is_cpp_class
5064
5065     def coerce_operand_to_pyobject(self, env):
5066         self.operand = self.operand.coerce_to_pyobject(env)
5067
5068     def generate_result_code(self, code):
5069         if self.operand.type.is_pyobject:
5070             self.generate_py_operation_code(code)
5071
5072     def generate_py_operation_code(self, code):
5073         function = self.py_operation_function()
5074         code.putln(
5075             "%s = %s(%s); %s" % (
5076                 self.result(),
5077                 function,
5078                 self.operand.py_result(),
5079                 code.error_goto_if_null(self.result(), self.pos)))
5080         code.put_gotref(self.py_result())
5081
5082     def type_error(self):
5083         if not self.operand.type.is_error:
5084             error(self.pos, "Invalid operand type for '%s' (%s)" %
5085                 (self.operator, self.operand.type))
5086         self.type = PyrexTypes.error_type
5087
5088     def analyse_cpp_operation(self, env):
5089         type = self.operand.type
5090         if type.is_ptr:
5091             type = type.base_type
5092         function = type.scope.lookup("operator%s" % self.operator)
5093         if not function:
5094             error(self.pos, "'%s' operator not defined for %s"
5095                 % (self.operator, type))
5096             self.type_error()
5097             return
5098         func_type = function.type
5099         if func_type.is_ptr:
5100             func_type = func_type.base_type
5101         self.type = func_type.return_type
5102
5103
5104 class NotNode(ExprNode):
5105     #  'not' operator
5106     #
5107     #  operand   ExprNode
5108
5109     type = PyrexTypes.c_bint_type
5110
5111     subexprs = ['operand']
5112
5113     def calculate_constant_result(self):
5114         self.constant_result = not self.operand.constant_result
5115
5116     def compile_time_value(self, denv):
5117         operand = self.operand.compile_time_value(denv)
5118         try:
5119             return not operand
5120         except Exception, e:
5121             self.compile_time_value_error(e)
5122
5123     def infer_type(self, env):
5124         return PyrexTypes.c_bint_type
5125
5126     def analyse_types(self, env):
5127         self.operand.analyse_types(env)
5128         self.operand = self.operand.coerce_to_boolean(env)
5129
5130     def calculate_result_code(self):
5131         return "(!%s)" % self.operand.result()
5132
5133     def generate_result_code(self, code):
5134         pass
5135
5136
5137 class UnaryPlusNode(UnopNode):
5138     #  unary '+' operator
5139
5140     operator = '+'
5141
5142     def analyse_c_operation(self, env):
5143         self.type = self.operand.type
5144
5145     def py_operation_function(self):
5146         return "PyNumber_Positive"
5147
5148     def calculate_result_code(self):
5149         if self.is_cpp_operation():
5150             return "(+%s)" % self.operand.result()
5151         else:
5152             return self.operand.result()
5153
5154
5155 class UnaryMinusNode(UnopNode):
5156     #  unary '-' operator
5157
5158     operator = '-'
5159
5160     def analyse_c_operation(self, env):
5161         if self.operand.type.is_numeric:
5162             self.type = self.operand.type
5163         else:
5164             self.type_error()
5165         if self.type.is_complex:
5166             self.infix = False
5167
5168     def py_operation_function(self):
5169         return "PyNumber_Negative"
5170
5171     def calculate_result_code(self):
5172         if self.infix:
5173             return "(-%s)" % self.operand.result()
5174         else:
5175             return "%s(%s)" % (self.operand.type.unary_op('-'), self.operand.result())
5176
5177     def get_constant_c_result_code(self):
5178         value = self.operand.get_constant_c_result_code()
5179         if value:
5180             return "(-%s)" % (value)
5181
5182 class TildeNode(UnopNode):
5183     #  unary '~' operator
5184
5185     def analyse_c_operation(self, env):
5186         if self.operand.type.is_int:
5187             self.type = self.operand.type
5188         else:
5189             self.type_error()
5190
5191     def py_operation_function(self):
5192         return "PyNumber_Invert"
5193
5194     def calculate_result_code(self):
5195         return "(~%s)" % self.operand.result()
5196
5197
5198 class CUnopNode(UnopNode):
5199
5200     def is_py_operation(self):
5201         return False
5202
5203 class DereferenceNode(CUnopNode):
5204     #  unary * operator
5205
5206     operator = '*'
5207
5208     def analyse_c_operation(self, env):
5209         if self.operand.type.is_ptr:
5210             self.type = self.operand.type.base_type
5211         else:
5212             self.type_error()
5213
5214     def calculate_result_code(self):
5215         return "(*%s)" % self.operand.result()
5216
5217
5218 class DecrementIncrementNode(CUnopNode):
5219     #  unary ++/-- operator
5220
5221     def analyse_c_operation(self, env):
5222         if self.operand.type.is_ptr or self.operand.type.is_numeric:
5223             self.type = self.operand.type
5224         else:
5225             self.type_error()
5226
5227     def calculate_result_code(self):
5228         if self.is_prefix:
5229             return "(%s%s)" % (self.operator, self.operand.result())
5230         else:
5231             return "(%s%s)" % (self.operand.result(), self.operator)
5232
5233 def inc_dec_constructor(is_prefix, operator):
5234     return lambda pos, **kwds: DecrementIncrementNode(pos, is_prefix=is_prefix, operator=operator, **kwds)
5235
5236
5237 class AmpersandNode(ExprNode):
5238     #  The C address-of operator.
5239     #
5240     #  operand  ExprNode
5241
5242     subexprs = ['operand']
5243
5244     def infer_type(self, env):
5245         return PyrexTypes.c_ptr_type(self.operand.infer_type(env))
5246
5247     def analyse_types(self, env):
5248         self.operand.analyse_types(env)
5249         argtype = self.operand.type
5250         if not (argtype.is_cfunction or self.operand.is_lvalue()):
5251             self.error("Taking address of non-lvalue")
5252             return
5253         if argtype.is_pyobject:
5254             self.error("Cannot take address of Python variable")
5255             return
5256         self.type = PyrexTypes.c_ptr_type(argtype)
5257
5258     def check_const(self):
5259         return self.operand.check_const_addr()
5260
5261     def error(self, mess):
5262         error(self.pos, mess)
5263         self.type = PyrexTypes.error_type
5264         self.result_code = "<error>"
5265
5266     def calculate_result_code(self):
5267         return "(&%s)" % self.operand.result()
5268
5269     def generate_result_code(self, code):
5270         pass
5271
5272
5273 unop_node_classes = {
5274     "+":  UnaryPlusNode,
5275     "-":  UnaryMinusNode,
5276     "~":  TildeNode,
5277 }
5278
5279 def unop_node(pos, operator, operand):
5280     # Construct unnop node of appropriate class for
5281     # given operator.
5282     if isinstance(operand, IntNode) and operator == '-':
5283         return IntNode(pos = operand.pos, value = str(-Utils.str_to_number(operand.value)))
5284     elif isinstance(operand, UnopNode) and operand.operator == operator:
5285         warning(pos, "Python has no increment/decrement operator: %s%sx = %s(%sx) = x" % ((operator,)*4), 5)
5286     return unop_node_classes[operator](pos,
5287         operator = operator,
5288         operand = operand)
5289
5290
5291 class TypecastNode(ExprNode):
5292     #  C type cast
5293     #
5294     #  operand      ExprNode
5295     #  base_type    CBaseTypeNode
5296     #  declarator   CDeclaratorNode
5297     #
5298     #  If used from a transform, one can if wanted specify the attribute
5299     #  "type" directly and leave base_type and declarator to None
5300
5301     subexprs = ['operand']
5302     base_type = declarator = type = None
5303
5304     def type_dependencies(self, env):
5305         return ()
5306
5307     def infer_type(self, env):
5308         if self.type is None:
5309             base_type = self.base_type.analyse(env)
5310             _, self.type = self.declarator.analyse(base_type, env)
5311         return self.type
5312
5313     def analyse_types(self, env):
5314         if self.type is None:
5315             base_type = self.base_type.analyse(env)
5316             _, self.type = self.declarator.analyse(base_type, env)
5317         if self.type.is_cfunction:
5318             error(self.pos,
5319                 "Cannot cast to a function type")
5320             self.type = PyrexTypes.error_type
5321         self.operand.analyse_types(env)
5322         to_py = self.type.is_pyobject
5323         from_py = self.operand.type.is_pyobject
5324         if from_py and not to_py and self.operand.is_ephemeral() and not self.type.is_numeric:
5325             error(self.pos, "Casting temporary Python object to non-numeric non-Python type")
5326         if to_py and not from_py:
5327             if self.type is bytes_type and self.operand.type.is_int:
5328                 # FIXME: the type cast node isn't needed in this case
5329                 # and can be dropped once analyse_types() can return a
5330                 # different node
5331                 self.operand = CoerceIntToBytesNode(self.operand, env)
5332             elif self.operand.type.can_coerce_to_pyobject(env):
5333                 self.result_ctype = py_object_type
5334                 self.operand = self.operand.coerce_to_pyobject(env)
5335             else:
5336                 if self.operand.type.is_ptr:
5337                     if not (self.operand.type.base_type.is_void or self.operand.type.base_type.is_struct):
5338                         error(self.pos, "Python objects cannot be cast from pointers of primitive types")
5339                 else:
5340                     # Should this be an error?
5341                     warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.operand.type, self.type))
5342                 self.operand = self.operand.coerce_to_simple(env)
5343         elif from_py and not to_py:
5344             if self.type.create_from_py_utility_code(env):
5345                 self.operand = self.operand.coerce_to(self.type, env)
5346             elif self.type.is_ptr:
5347                 if not (self.type.base_type.is_void or self.type.base_type.is_struct):
5348                     error(self.pos, "Python objects cannot be cast to pointers of primitive types")
5349             else:
5350                 warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.type, self.operand.type))
5351         elif from_py and to_py:
5352             if self.typecheck and self.type.is_extension_type:
5353                 self.operand = PyTypeTestNode(self.operand, self.type, env, notnone=True)
5354         elif self.type.is_complex and self.operand.type.is_complex:
5355             self.operand = self.operand.coerce_to_simple(env)
5356
5357     def nogil_check(self, env):
5358         if self.type and self.type.is_pyobject and self.is_temp:
5359             self.gil_error()
5360
5361     def check_const(self):
5362         return self.operand.check_const()
5363
5364     def calculate_constant_result(self):
5365         # we usually do not know the result of a type cast at code
5366         # generation time
5367         pass
5368
5369     def calculate_result_code(self):
5370         if self.type.is_complex:
5371             operand_result = self.operand.result()
5372             if self.operand.type.is_complex:
5373                 real_part = self.type.real_type.cast_code("__Pyx_CREAL(%s)" % operand_result)
5374                 imag_part = self.type.real_type.cast_code("__Pyx_CIMAG(%s)" % operand_result)
5375             else:
5376                 real_part = self.type.real_type.cast_code(operand_result)
5377                 imag_part = "0"
5378             return "%s(%s, %s)" % (
5379                     self.type.from_parts,
5380                     real_part,
5381                     imag_part)
5382         else:
5383             return self.type.cast_code(self.operand.result())
5384
5385     def get_constant_c_result_code(self):
5386         operand_result = self.operand.get_constant_c_result_code()
5387         if operand_result:
5388             return self.type.cast_code(operand_result)
5389
5390     def result_as(self, type):
5391         if self.type.is_pyobject and not self.is_temp:
5392             #  Optimise away some unnecessary casting
5393             return self.operand.result_as(type)
5394         else:
5395             return ExprNode.result_as(self, type)
5396
5397     def generate_result_code(self, code):
5398         if self.is_temp:
5399             code.putln(
5400                 "%s = (PyObject *)%s;" % (
5401                     self.result(),
5402                     self.operand.result()))
5403             code.put_incref(self.result(), self.ctype())
5404
5405
5406 class SizeofNode(ExprNode):
5407     #  Abstract base class for sizeof(x) expression nodes.
5408
5409     type = PyrexTypes.c_size_t_type
5410
5411     def check_const(self):
5412         return True
5413
5414     def generate_result_code(self, code):
5415         pass
5416
5417
5418 class SizeofTypeNode(SizeofNode):
5419     #  C sizeof function applied to a type
5420     #
5421     #  base_type   CBaseTypeNode
5422     #  declarator  CDeclaratorNode
5423
5424     subexprs = []
5425     arg_type = None
5426
5427     def analyse_types(self, env):
5428         # we may have incorrectly interpreted a dotted name as a type rather than an attribute
5429         # this could be better handled by more uniformly treating types as runtime-available objects
5430         if 0 and self.base_type.module_path:
5431             path = self.base_type.module_path
5432             obj = env.lookup(path[0])
5433             if obj.as_module is None:
5434                 operand = NameNode(pos=self.pos, name=path[0])
5435                 for attr in path[1:]:
5436                     operand = AttributeNode(pos=self.pos, obj=operand, attribute=attr)
5437                 operand = AttributeNode(pos=self.pos, obj=operand, attribute=self.base_type.name)
5438                 self.operand = operand
5439                 self.__class__ = SizeofVarNode
5440                 self.analyse_types(env)
5441                 return
5442         if self.arg_type is None:
5443             base_type = self.base_type.analyse(env)
5444             _, arg_type = self.declarator.analyse(base_type, env)
5445             self.arg_type = arg_type
5446         self.check_type()
5447
5448     def check_type(self):
5449         arg_type = self.arg_type
5450         if arg_type.is_pyobject and not arg_type.is_extension_type:
5451             error(self.pos, "Cannot take sizeof Python object")
5452         elif arg_type.is_void:
5453             error(self.pos, "Cannot take sizeof void")
5454         elif not arg_type.is_complete():
5455             error(self.pos, "Cannot take sizeof incomplete type '%s'" % arg_type)
5456
5457     def calculate_result_code(self):
5458         if self.arg_type.is_extension_type:
5459             # the size of the pointer is boring
5460             # we want the size of the actual struct
5461             arg_code = self.arg_type.declaration_code("", deref=1)
5462         else:
5463             arg_code = self.arg_type.declaration_code("")
5464         return "(sizeof(%s))" % arg_code
5465
5466
5467 class SizeofVarNode(SizeofNode):
5468     #  C sizeof function applied to a variable
5469     #
5470     #  operand   ExprNode
5471
5472     subexprs = ['operand']
5473
5474     def analyse_types(self, env):
5475         # We may actually be looking at a type rather than a variable...
5476         # If we are, traditional analysis would fail...
5477         operand_as_type = self.operand.analyse_as_type(env)
5478         if operand_as_type:
5479             self.arg_type = operand_as_type
5480             self.__class__ = SizeofTypeNode
5481             self.check_type()
5482         else:
5483             self.operand.analyse_types(env)
5484
5485     def calculate_result_code(self):
5486         return "(sizeof(%s))" % self.operand.result()
5487
5488     def generate_result_code(self, code):
5489         pass
5490
5491 class TypeofNode(ExprNode):
5492     #  Compile-time type of an expression, as a string.
5493     #
5494     #  operand   ExprNode
5495     #  literal   StringNode # internal
5496
5497     literal = None
5498     type = py_object_type
5499
5500     subexprs = ['literal'] # 'operand' will be ignored after type analysis!
5501
5502     def analyse_types(self, env):
5503         self.operand.analyse_types(env)
5504         self.literal = StringNode(
5505             self.pos, value=StringEncoding.EncodedString(str(self.operand.type)))
5506         self.literal.analyse_types(env)
5507         self.literal = self.literal.coerce_to_pyobject(env)
5508
5509     def may_be_none(self):
5510         return False
5511
5512     def generate_evaluation_code(self, code):
5513         self.literal.generate_evaluation_code(code)
5514
5515     def calculate_result_code(self):
5516         return self.literal.calculate_result_code()
5517
5518 #-------------------------------------------------------------------
5519 #
5520 #  Binary operator nodes
5521 #
5522 #-------------------------------------------------------------------
5523
5524 def _not_in(x, seq):
5525     return x not in seq
5526
5527 compile_time_binary_operators = {
5528     '<': operator.lt,
5529     '<=': operator.le,
5530     '==': operator.eq,
5531     '!=': operator.ne,
5532     '>=': operator.ge,
5533     '>': operator.gt,
5534     'is': operator.is_,
5535     'is_not': operator.is_not,
5536     '+': operator.add,
5537     '&': operator.and_,
5538     '/': operator.truediv,
5539     '//': operator.floordiv,
5540     '<<': operator.lshift,
5541     '%': operator.mod,
5542     '*': operator.mul,
5543     '|': operator.or_,
5544     '**': operator.pow,
5545     '>>': operator.rshift,
5546     '-': operator.sub,
5547     '^': operator.xor,
5548     'in': operator.contains,
5549     'not_in': _not_in,
5550 }
5551
5552 def get_compile_time_binop(node):
5553     func = compile_time_binary_operators.get(node.operator)
5554     if not func:
5555         error(node.pos,
5556             "Binary '%s' not supported in compile-time expression"
5557                 % node.operator)
5558     return func
5559
5560 class BinopNode(ExprNode):
5561     #  operator     string
5562     #  operand1     ExprNode
5563     #  operand2     ExprNode
5564     #
5565     #  Processing during analyse_expressions phase:
5566     #
5567     #    analyse_c_operation
5568     #      Called when neither operand is a pyobject.
5569     #      - Check operand types and coerce if needed.
5570     #      - Determine result type and result code fragment.
5571     #      - Allocate temporary for result if needed.
5572
5573     subexprs = ['operand1', 'operand2']
5574     inplace = False
5575
5576     def calculate_constant_result(self):
5577         func = compile_time_binary_operators[self.operator]
5578         self.constant_result = func(
5579             self.operand1.constant_result,
5580             self.operand2.constant_result)
5581
5582     def compile_time_value(self, denv):
5583         func = get_compile_time_binop(self)
5584         operand1 = self.operand1.compile_time_value(denv)
5585         operand2 = self.operand2.compile_time_value(denv)
5586         try:
5587             return func(operand1, operand2)
5588         except Exception, e:
5589             self.compile_time_value_error(e)
5590
5591     def infer_type(self, env):
5592         return self.result_type(self.operand1.infer_type(env),
5593                                 self.operand2.infer_type(env))
5594
5595     def analyse_types(self, env):
5596         self.operand1.analyse_types(env)
5597         self.operand2.analyse_types(env)
5598         self.analyse_operation(env)
5599
5600     def analyse_operation(self, env):
5601         if self.is_py_operation():
5602             self.coerce_operands_to_pyobjects(env)
5603             self.type = self.result_type(self.operand1.type,
5604                                          self.operand2.type)
5605             assert self.type.is_pyobject
5606             self.is_temp = 1
5607         elif self.is_cpp_operation():
5608             self.analyse_cpp_operation(env)
5609         else:
5610             self.analyse_c_operation(env)
5611
5612     def is_py_operation(self):
5613         return self.is_py_operation_types(self.operand1.type, self.operand2.type)
5614
5615     def is_py_operation_types(self, type1, type2):
5616         return type1.is_pyobject or type2.is_pyobject
5617
5618     def is_cpp_operation(self):
5619         return (self.operand1.type.is_cpp_class
5620             or self.operand2.type.is_cpp_class)
5621
5622     def analyse_cpp_operation(self, env):
5623         type1 = self.operand1.type
5624         type2 = self.operand2.type
5625         entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
5626         if not entry:
5627             self.type_error()
5628             return
5629         func_type = entry.type
5630         if func_type.is_ptr:
5631             func_type = func_type.base_type
5632         if len(func_type.args) == 1:
5633             self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
5634         else:
5635             self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
5636             self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
5637         self.type = func_type.return_type
5638
5639     def result_type(self, type1, type2):
5640         if self.is_py_operation_types(type1, type2):
5641             if type2.is_string:
5642                 type2 = Builtin.bytes_type
5643             if type1.is_string:
5644                 type1 = Builtin.bytes_type
5645             elif self.operator == '%' \
5646                      and type1 in (Builtin.str_type, Builtin.unicode_type):
5647                 # note that  b'%s' % b'abc'  doesn't work in Py3
5648                 return type1
5649             if type1.is_builtin_type:
5650                 if type1 is type2:
5651                     if self.operator in '**%+|&^':
5652                         # FIXME: at least these operators should be safe - others?
5653                         return type1
5654                 elif self.operator == '*':
5655                     if type1 in (Builtin.bytes_type, Builtin.str_type, Builtin.unicode_type):
5656                         return type1
5657                     # multiplication of containers/numbers with an
5658                     # integer value always (?) returns the same type
5659                     if type2.is_int:
5660                         return type1
5661             elif type2.is_builtin_type and type1.is_int and self.operator == '*':
5662                 # multiplication of containers/numbers with an
5663                 # integer value always (?) returns the same type
5664                 return type2
5665             return py_object_type
5666         else:
5667             return self.compute_c_result_type(type1, type2)
5668
5669     def nogil_check(self, env):
5670         if self.is_py_operation():
5671             self.gil_error()
5672
5673     def coerce_operands_to_pyobjects(self, env):
5674         self.operand1 = self.operand1.coerce_to_pyobject(env)
5675         self.operand2 = self.operand2.coerce_to_pyobject(env)
5676
5677     def check_const(self):
5678         return self.operand1.check_const() and self.operand2.check_const()
5679
5680     def generate_result_code(self, code):
5681         #print "BinopNode.generate_result_code:", self.operand1, self.operand2 ###
5682         if self.operand1.type.is_pyobject:
5683             function = self.py_operation_function()
5684             if self.operator == '**':
5685                 extra_args = ", Py_None"
5686             else:
5687                 extra_args = ""
5688             code.putln(
5689                 "%s = %s(%s, %s%s); %s" % (
5690                     self.result(),
5691                     function,
5692                     self.operand1.py_result(),
5693                     self.operand2.py_result(),
5694                     extra_args,
5695                     code.error_goto_if_null(self.result(), self.pos)))
5696             code.put_gotref(self.py_result())
5697
5698     def type_error(self):
5699         if not (self.operand1.type.is_error
5700                 or self.operand2.type.is_error):
5701             error(self.pos, "Invalid operand types for '%s' (%s; %s)" %
5702                 (self.operator, self.operand1.type,
5703                     self.operand2.type))
5704         self.type = PyrexTypes.error_type
5705
5706
5707 class CBinopNode(BinopNode):
5708
5709     def analyse_types(self, env):
5710         BinopNode.analyse_types(self, env)
5711         if self.is_py_operation():
5712             self.type = PyrexTypes.error_type
5713
5714     def py_operation_function():
5715         return ""
5716
5717     def calculate_result_code(self):
5718         return "(%s %s %s)" % (
5719             self.operand1.result(),
5720             self.operator,
5721             self.operand2.result())
5722
5723
5724 def c_binop_constructor(operator):
5725     def make_binop_node(pos, **operands):
5726         return CBinopNode(pos, operator=operator, **operands)
5727     return make_binop_node
5728
5729 class NumBinopNode(BinopNode):
5730     #  Binary operation taking numeric arguments.
5731
5732     infix = True
5733
5734     def analyse_c_operation(self, env):
5735         type1 = self.operand1.type
5736         type2 = self.operand2.type
5737         self.type = self.compute_c_result_type(type1, type2)
5738         if not self.type:
5739             self.type_error()
5740             return
5741         if self.type.is_complex:
5742             self.infix = False
5743         if not self.infix or (type1.is_numeric and type2.is_numeric):
5744             self.operand1 = self.operand1.coerce_to(self.type, env)
5745             self.operand2 = self.operand2.coerce_to(self.type, env)
5746
5747     def compute_c_result_type(self, type1, type2):
5748         if self.c_types_okay(type1, type2):
5749             widest_type = PyrexTypes.widest_numeric_type(type1, type2)
5750             if widest_type is PyrexTypes.c_bint_type:
5751                 if self.operator not in '|^&':
5752                     # False + False == 0 # not False!
5753                     widest_type = PyrexTypes.c_int_type
5754             return widest_type
5755         else:
5756             return None
5757
5758     def get_constant_c_result_code(self):
5759         value1 = self.operand1.get_constant_c_result_code()
5760         value2 = self.operand2.get_constant_c_result_code()
5761         if value1 and value2:
5762             return "(%s %s %s)" % (value1, self.operator, value2)
5763         else:
5764             return None
5765
5766     def c_types_okay(self, type1, type2):
5767         #print "NumBinopNode.c_types_okay:", type1, type2 ###
5768         return (type1.is_numeric  or type1.is_enum) \
5769             and (type2.is_numeric  or type2.is_enum)
5770
5771     def calculate_result_code(self):
5772         if self.infix:
5773             return "(%s %s %s)" % (
5774                 self.operand1.result(),
5775                 self.operator,
5776                 self.operand2.result())
5777         else:
5778             func = self.type.binary_op(self.operator)
5779             if func is None:
5780                 error(self.pos, "binary operator %s not supported for %s" % (self.operator, self.type))
5781             return "%s(%s, %s)" % (
5782                 func,
5783                 self.operand1.result(),
5784                 self.operand2.result())
5785
5786     def is_py_operation_types(self, type1, type2):
5787         return (type1 is PyrexTypes.c_py_unicode_type or
5788                 type2 is PyrexTypes.c_py_unicode_type or
5789                 BinopNode.is_py_operation_types(self, type1, type2))
5790
5791     def py_operation_function(self):
5792         fuction = self.py_functions[self.operator]
5793         if self.inplace:
5794             fuction = fuction.replace('PyNumber_', 'PyNumber_InPlace')
5795         return fuction
5796
5797     py_functions = {
5798         "|":        "PyNumber_Or",
5799         "^":        "PyNumber_Xor",
5800         "&":        "PyNumber_And",
5801         "<<":       "PyNumber_Lshift",
5802         ">>":       "PyNumber_Rshift",
5803         "+":        "PyNumber_Add",
5804         "-":        "PyNumber_Subtract",
5805         "*":        "PyNumber_Multiply",
5806         "/":        "__Pyx_PyNumber_Divide",
5807         "//":       "PyNumber_FloorDivide",
5808         "%":        "PyNumber_Remainder",
5809         "**":       "PyNumber_Power"
5810     }
5811
5812 class IntBinopNode(NumBinopNode):
5813     #  Binary operation taking integer arguments.
5814
5815     def c_types_okay(self, type1, type2):
5816         #print "IntBinopNode.c_types_okay:", type1, type2 ###
5817         return (type1.is_int or type1.is_enum) \
5818             and (type2.is_int or type2.is_enum)
5819
5820
5821 class AddNode(NumBinopNode):
5822     #  '+' operator.
5823
5824     def is_py_operation_types(self, type1, type2):
5825         if type1.is_string and type2.is_string:
5826             return 1
5827         else:
5828             return NumBinopNode.is_py_operation_types(self, type1, type2)
5829
5830     def compute_c_result_type(self, type1, type2):
5831         #print "AddNode.compute_c_result_type:", type1, self.operator, type2 ###
5832         if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
5833             return type1
5834         elif (type2.is_ptr or type2.is_array) and (type1.is_int or type1.is_enum):
5835             return type2
5836         else:
5837             return NumBinopNode.compute_c_result_type(
5838                 self, type1, type2)
5839
5840
5841 class SubNode(NumBinopNode):
5842     #  '-' operator.
5843
5844     def compute_c_result_type(self, type1, type2):
5845         if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
5846             return type1
5847         elif (type1.is_ptr or type1.is_array) and (type2.is_ptr or type2.is_array):
5848             return PyrexTypes.c_int_type
5849         else:
5850             return NumBinopNode.compute_c_result_type(
5851                 self, type1, type2)
5852
5853
5854 class MulNode(NumBinopNode):
5855     #  '*' operator.
5856
5857     def is_py_operation_types(self, type1, type2):
5858         if (type1.is_string and type2.is_int) \
5859             or (type2.is_string and type1.is_int):
5860                 return 1
5861         else:
5862             return NumBinopNode.is_py_operation_types(self, type1, type2)
5863
5864
5865 class DivNode(NumBinopNode):
5866     #  '/' or '//' operator.
5867
5868     cdivision = None
5869     truedivision = None   # == "unknown" if operator == '/'
5870     ctruedivision = False
5871     cdivision_warnings = False
5872     zerodivision_check = None
5873
5874     def find_compile_time_binary_operator(self, op1, op2):
5875         func = compile_time_binary_operators[self.operator]
5876         if self.operator == '/' and self.truedivision is None:
5877             # => true div for floats, floor div for integers
5878             if isinstance(op1, (int,long)) and isinstance(op2, (int,long)):
5879                 func = compile_time_binary_operators['//']
5880         return func
5881
5882     def calculate_constant_result(self):
5883         op1 = self.operand1.constant_result
5884         op2 = self.operand2.constant_result
5885         func = self.find_compile_time_binary_operator(op1, op2)
5886         self.constant_result = func(
5887             self.operand1.constant_result,
5888             self.operand2.constant_result)
5889
5890     def compile_time_value(self, denv):
5891         operand1 = self.operand1.compile_time_value(denv)
5892         operand2 = self.operand2.compile_time_value(denv)
5893         try:
5894             func = self.find_compile_time_binary_operator(
5895                 self, operand1, operand2)
5896             return func(operand1, operand2)
5897         except Exception, e:
5898             self.compile_time_value_error(e)
5899
5900     def analyse_operation(self, env):
5901         if self.cdivision or env.directives['cdivision']:
5902             self.ctruedivision = False
5903         else:
5904             self.ctruedivision = self.truedivision
5905         NumBinopNode.analyse_operation(self, env)
5906         if self.is_cpp_operation():
5907             self.cdivision = True
5908         if not self.type.is_pyobject:
5909             self.zerodivision_check = (
5910                 self.cdivision is None and not env.directives['cdivision']
5911                 and (not self.operand2.has_constant_result() or
5912                      self.operand2.constant_result == 0))
5913             if self.zerodivision_check or env.directives['cdivision_warnings']:
5914                 # Need to check ahead of time to warn or raise zero division error
5915                 self.operand1 = self.operand1.coerce_to_simple(env)
5916                 self.operand2 = self.operand2.coerce_to_simple(env)
5917                 if env.nogil:
5918                     error(self.pos, "Pythonic division not allowed without gil, consider using cython.cdivision(True)")
5919
5920     def compute_c_result_type(self, type1, type2):
5921         if self.operator == '/' and self.ctruedivision:
5922             if not type1.is_float and not type2.is_float:
5923                 widest_type = PyrexTypes.widest_numeric_type(type1, PyrexTypes.c_double_type)
5924                 widest_type = PyrexTypes.widest_numeric_type(type2, widest_type)
5925                 return widest_type
5926         return NumBinopNode.compute_c_result_type(self, type1, type2)
5927
5928     def zero_division_message(self):
5929         if self.type.is_int:
5930             return "integer division or modulo by zero"
5931         else:
5932             return "float division"
5933
5934     def generate_evaluation_code(self, code):
5935         if not self.type.is_pyobject and not self.type.is_complex:
5936             if self.cdivision is None:
5937                 self.cdivision = (code.globalstate.directives['cdivision']
5938                                     or not self.type.signed
5939                                     or self.type.is_float)
5940             if not self.cdivision:
5941                 code.globalstate.use_utility_code(div_int_utility_code.specialize(self.type))
5942         NumBinopNode.generate_evaluation_code(self, code)
5943         self.generate_div_warning_code(code)
5944
5945     def generate_div_warning_code(self, code):
5946         if not self.type.is_pyobject:
5947             if self.zerodivision_check:
5948                 if not self.infix:
5949                     zero_test = "%s(%s)" % (self.type.unary_op('zero'), self.operand2.result())
5950                 else:
5951                     zero_test = "%s == 0" % self.operand2.result()
5952                 code.putln("if (unlikely(%s)) {" % zero_test)
5953                 code.putln('PyErr_Format(PyExc_ZeroDivisionError, "%s");' % self.zero_division_message())
5954                 code.putln(code.error_goto(self.pos))
5955                 code.putln("}")
5956                 if self.type.is_int and self.type.signed and self.operator != '%':
5957                     code.globalstate.use_utility_code(division_overflow_test_code)
5958                     code.putln("else if (sizeof(%s) == sizeof(long) && unlikely(%s == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(%s))) {" % (
5959                                     self.type.declaration_code(''),
5960                                     self.operand2.result(),
5961                                     self.operand1.result()))
5962                     code.putln('PyErr_Format(PyExc_OverflowError, "value too large to perform division");')
5963                     code.putln(code.error_goto(self.pos))
5964                     code.putln("}")
5965             if code.globalstate.directives['cdivision_warnings'] and self.operator != '/':
5966                 code.globalstate.use_utility_code(cdivision_warning_utility_code)
5967                 code.putln("if ((%s < 0) ^ (%s < 0)) {" % (
5968                                 self.operand1.result(),
5969                                 self.operand2.result()))
5970                 code.putln(code.set_error_info(self.pos));
5971                 code.put("if (__Pyx_cdivision_warning()) ")
5972                 code.put_goto(code.error_label)
5973                 code.putln("}")
5974
5975     def calculate_result_code(self):
5976         if self.type.is_complex:
5977             return NumBinopNode.calculate_result_code(self)
5978         elif self.type.is_float and self.operator == '//':
5979             return "floor(%s / %s)" % (
5980                 self.operand1.result(),
5981                 self.operand2.result())
5982         elif self.truedivision or self.cdivision:
5983             op1 = self.operand1.result()
5984             op2 = self.operand2.result()
5985             if self.truedivision:
5986                 if self.type != self.operand1.type:
5987                     op1 = self.type.cast_code(op1)
5988                 if self.type != self.operand2.type:
5989                     op2 = self.type.cast_code(op2)
5990             return "(%s / %s)" % (op1, op2)
5991         else:
5992             return "__Pyx_div_%s(%s, %s)" % (
5993                     self.type.specialization_name(),
5994                     self.operand1.result(),
5995                     self.operand2.result())
5996
5997
5998 class ModNode(DivNode):
5999     #  '%' operator.
6000
6001     def is_py_operation_types(self, type1, type2):
6002         return (type1.is_string
6003             or type2.is_string
6004             or NumBinopNode.is_py_operation_types(self, type1, type2))
6005
6006     def zero_division_message(self):
6007         if self.type.is_int:
6008             return "integer division or modulo by zero"
6009         else:
6010             return "float divmod()"
6011
6012     def generate_evaluation_code(self, code):
6013         if not self.type.is_pyobject:
6014             if self.cdivision is None:
6015                 self.cdivision = code.globalstate.directives['cdivision'] or not self.type.signed
6016             if not self.cdivision:
6017                 if self.type.is_int:
6018                     code.globalstate.use_utility_code(mod_int_utility_code.specialize(self.type))
6019                 else:
6020                     code.globalstate.use_utility_code(
6021                         mod_float_utility_code.specialize(self.type, math_h_modifier=self.type.math_h_modifier))
6022         NumBinopNode.generate_evaluation_code(self, code)
6023         self.generate_div_warning_code(code)
6024
6025     def calculate_result_code(self):
6026         if self.cdivision:
6027             if self.type.is_float:
6028                 return "fmod%s(%s, %s)" % (
6029                     self.type.math_h_modifier,
6030                     self.operand1.result(),
6031                     self.operand2.result())
6032             else:
6033                 return "(%s %% %s)" % (
6034                     self.operand1.result(),
6035                     self.operand2.result())
6036         else:
6037             return "__Pyx_mod_%s(%s, %s)" % (
6038                     self.type.specialization_name(),
6039                     self.operand1.result(),
6040                     self.operand2.result())
6041
6042 class PowNode(NumBinopNode):
6043     #  '**' operator.
6044
6045     def analyse_c_operation(self, env):
6046         NumBinopNode.analyse_c_operation(self, env)
6047         if self.type.is_complex:
6048             if self.type.real_type.is_float:
6049                 self.operand1 = self.operand1.coerce_to(self.type, env)
6050                 self.operand2 = self.operand2.coerce_to(self.type, env)
6051                 self.pow_func = "__Pyx_c_pow" + self.type.real_type.math_h_modifier
6052             else:
6053                 error(self.pos, "complex int powers not supported")
6054                 self.pow_func = "<error>"
6055         elif self.type.is_float:
6056             self.pow_func = "pow" + self.type.math_h_modifier
6057         else:
6058             self.pow_func = "__Pyx_pow_%s" % self.type.declaration_code('').replace(' ', '_')
6059             env.use_utility_code(
6060                     int_pow_utility_code.specialize(func_name=self.pow_func,
6061                                                 type=self.type.declaration_code('')))
6062
6063     def calculate_result_code(self):
6064         # Work around MSVC overloading ambiguity.
6065         def typecast(operand):
6066             if self.type == operand.type:
6067                 return operand.result()
6068             else:
6069                 return self.type.cast_code(operand.result())
6070         return "%s(%s, %s)" % (
6071             self.pow_func,
6072             typecast(self.operand1),
6073             typecast(self.operand2))
6074
6075
6076 # Note: This class is temporarily "shut down" into an ineffective temp
6077 # allocation mode.
6078 #
6079 # More sophisticated temp reuse was going on before, one could have a
6080 # look at adding this again after /all/ classes are converted to the
6081 # new temp scheme. (The temp juggling cannot work otherwise).
6082 class BoolBinopNode(ExprNode):
6083     #  Short-circuiting boolean operation.
6084     #
6085     #  operator     string
6086     #  operand1     ExprNode
6087     #  operand2     ExprNode
6088
6089     subexprs = ['operand1', 'operand2']
6090
6091     def infer_type(self, env):
6092         type1 = self.operand1.infer_type(env)
6093         type2 = self.operand2.infer_type(env)
6094         return PyrexTypes.independent_spanning_type(type1, type2)
6095
6096     def may_be_none(self):
6097         if self.operator == 'or':
6098             return self.operand2.may_be_none()
6099         else:
6100             return self.operand1.may_be_none() or self.operand2.may_be_none()
6101
6102     def calculate_constant_result(self):
6103         if self.operator == 'and':
6104             self.constant_result = \
6105                 self.operand1.constant_result and \
6106                 self.operand2.constant_result
6107         else:
6108             self.constant_result = \
6109                 self.operand1.constant_result or \
6110                 self.operand2.constant_result
6111
6112     def compile_time_value(self, denv):
6113         if self.operator == 'and':
6114             return self.operand1.compile_time_value(denv) \
6115                 and self.operand2.compile_time_value(denv)
6116         else:
6117             return self.operand1.compile_time_value(denv) \
6118                 or self.operand2.compile_time_value(denv)
6119
6120     def coerce_to_boolean(self, env):
6121         return BoolBinopNode(
6122             self.pos,
6123             operator = self.operator,
6124             operand1 = self.operand1.coerce_to_boolean(env),
6125             operand2 = self.operand2.coerce_to_boolean(env),
6126             type = PyrexTypes.c_bint_type,
6127             is_temp = self.is_temp)
6128
6129     def analyse_types(self, env):
6130         self.operand1.analyse_types(env)
6131         self.operand2.analyse_types(env)
6132         self.type = PyrexTypes.independent_spanning_type(self.operand1.type, self.operand2.type)
6133         self.operand1 = self.operand1.coerce_to(self.type, env)
6134         self.operand2 = self.operand2.coerce_to(self.type, env)
6135
6136         # For what we're about to do, it's vital that
6137         # both operands be temp nodes.
6138         self.operand1 = self.operand1.coerce_to_simple(env)
6139         self.operand2 = self.operand2.coerce_to_simple(env)
6140         self.is_temp = 1
6141
6142     gil_message = "Truth-testing Python object"
6143
6144     def check_const(self):
6145         return self.operand1.check_const() and self.operand2.check_const()
6146
6147     def generate_evaluation_code(self, code):
6148         code.mark_pos(self.pos)
6149         self.operand1.generate_evaluation_code(code)
6150         test_result, uses_temp = self.generate_operand1_test(code)
6151         if self.operator == 'and':
6152             sense = ""
6153         else:
6154             sense = "!"
6155         code.putln(
6156             "if (%s%s) {" % (
6157                 sense,
6158                 test_result))
6159         if uses_temp:
6160             code.funcstate.release_temp(test_result)
6161         self.operand1.generate_disposal_code(code)
6162         self.operand2.generate_evaluation_code(code)
6163         self.allocate_temp_result(code)
6164         self.operand2.make_owned_reference(code)
6165         code.putln("%s = %s;" % (self.result(), self.operand2.result()))
6166         self.operand2.generate_post_assignment_code(code)
6167         self.operand2.free_temps(code)
6168         code.putln("} else {")
6169         self.operand1.make_owned_reference(code)
6170         code.putln("%s = %s;" % (self.result(), self.operand1.result()))
6171         self.operand1.generate_post_assignment_code(code)
6172         self.operand1.free_temps(code)
6173         code.putln("}")
6174
6175     def generate_operand1_test(self, code):
6176         #  Generate code to test the truth of the first operand.
6177         if self.type.is_pyobject:
6178             test_result = code.funcstate.allocate_temp(PyrexTypes.c_bint_type,
6179                                                        manage_ref=False)
6180             code.putln(
6181                 "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
6182                     test_result,
6183                     self.operand1.py_result(),
6184                     code.error_goto_if_neg(test_result, self.pos)))
6185         else:
6186             test_result = self.operand1.result()
6187         return (test_result, self.type.is_pyobject)
6188
6189
6190 class CondExprNode(ExprNode):
6191     #  Short-circuiting conditional expression.
6192     #
6193     #  test        ExprNode
6194     #  true_val    ExprNode
6195     #  false_val   ExprNode
6196
6197     true_val = None
6198     false_val = None
6199
6200     subexprs = ['test', 'true_val', 'false_val']
6201
6202     def type_dependencies(self, env):
6203         return self.true_val.type_dependencies(env) + self.false_val.type_dependencies(env)
6204
6205     def infer_type(self, env):
6206         return PyrexTypes.independent_spanning_type(self.true_val.infer_type(env),
6207                                                     self.false_val.infer_type(env))
6208
6209     def calculate_constant_result(self):
6210         if self.test.constant_result:
6211             self.constant_result = self.true_val.constant_result
6212         else:
6213             self.constant_result = self.false_val.constant_result
6214
6215     def analyse_types(self, env):
6216         self.test.analyse_types(env)
6217         self.test = self.test.coerce_to_boolean(env)
6218         self.true_val.analyse_types(env)
6219         self.false_val.analyse_types(env)
6220         self.type = PyrexTypes.independent_spanning_type(self.true_val.type, self.false_val.type)
6221         if self.true_val.type.is_pyobject or self.false_val.type.is_pyobject:
6222             self.true_val = self.true_val.coerce_to(self.type, env)
6223             self.false_val = self.false_val.coerce_to(self.type, env)
6224         self.is_temp = 1
6225         if self.type == PyrexTypes.error_type:
6226             self.type_error()
6227
6228     def type_error(self):
6229         if not (self.true_val.type.is_error or self.false_val.type.is_error):
6230             error(self.pos, "Incompatable types in conditional expression (%s; %s)" %
6231                 (self.true_val.type, self.false_val.type))
6232         self.type = PyrexTypes.error_type
6233
6234     def check_const(self):
6235         return (self.test.check_const()
6236             and self.true_val.check_const()
6237             and self.false_val.check_const())
6238
6239     def generate_evaluation_code(self, code):
6240         # Because subexprs may not be evaluated we can use a more optimal
6241         # subexpr allocation strategy than the default, so override evaluation_code.
6242
6243         code.mark_pos(self.pos)
6244         self.allocate_temp_result(code)
6245         self.test.generate_evaluation_code(code)
6246         code.putln("if (%s) {" % self.test.result() )
6247         self.eval_and_get(code, self.true_val)
6248         code.putln("} else {")
6249         self.eval_and_get(code, self.false_val)
6250         code.putln("}")
6251         self.test.generate_disposal_code(code)
6252         self.test.free_temps(code)
6253
6254     def eval_and_get(self, code, expr):
6255         expr.generate_evaluation_code(code)
6256         expr.make_owned_reference(code)
6257         code.putln("%s = %s;" % (self.result(), expr.result()))
6258         expr.generate_post_assignment_code(code)
6259         expr.free_temps(code)
6260
6261 richcmp_constants = {
6262     "<" : "Py_LT",
6263     "<=": "Py_LE",
6264     "==": "Py_EQ",
6265     "!=": "Py_NE",
6266     "<>": "Py_NE",
6267     ">" : "Py_GT",
6268     ">=": "Py_GE",
6269 }
6270
6271 class CmpNode(object):
6272     #  Mixin class containing code common to PrimaryCmpNodes
6273     #  and CascadedCmpNodes.
6274
6275     special_bool_cmp_function = None
6276
6277     def infer_type(self, env):
6278         # TODO: Actually implement this (after merging with -unstable).
6279         return py_object_type
6280
6281     def calculate_cascaded_constant_result(self, operand1_result):
6282         func = compile_time_binary_operators[self.operator]
6283         operand2_result = self.operand2.constant_result
6284         result = func(operand1_result, operand2_result)
6285         if self.cascade:
6286             self.cascade.calculate_cascaded_constant_result(operand2_result)
6287             if self.cascade.constant_result:
6288                 self.constant_result = result and self.cascade.constant_result
6289         else:
6290             self.constant_result = result
6291
6292     def cascaded_compile_time_value(self, operand1, denv):
6293         func = get_compile_time_binop(self)
6294         operand2 = self.operand2.compile_time_value(denv)
6295         try:
6296             result = func(operand1, operand2)
6297         except Exception, e:
6298             self.compile_time_value_error(e)
6299             result = None
6300         if result:
6301             cascade = self.cascade
6302             if cascade:
6303                 # FIXME: I bet this must call cascaded_compile_time_value()
6304                 result = result and cascade.cascaded_compile_time_value(operand2, denv)
6305         return result
6306
6307     def is_cpp_comparison(self):
6308         return self.operand1.type.is_cpp_class or self.operand2.type.is_cpp_class
6309
6310     def find_common_int_type(self, env, op, operand1, operand2):
6311         # type1 != type2 and at least one of the types is not a C int
6312         type1 = operand1.type
6313         type2 = operand2.type
6314         type1_can_be_int = False
6315         type2_can_be_int = False
6316
6317         if isinstance(operand1, (StringNode, BytesNode, UnicodeNode)) \
6318                and operand1.can_coerce_to_char_literal():
6319             type1_can_be_int = True
6320         if isinstance(operand2, (StringNode, BytesNode, UnicodeNode)) \
6321                  and operand2.can_coerce_to_char_literal():
6322             type2_can_be_int = True
6323
6324         if type1.is_int:
6325             if type2_can_be_int:
6326                 return type1
6327         elif type2.is_int:
6328             if type1_can_be_int:
6329                 return type2
6330         elif type1_can_be_int:
6331             if type2_can_be_int:
6332                 return PyrexTypes.c_uchar_type
6333
6334         return None
6335
6336     def find_common_type(self, env, op, operand1, common_type=None):
6337         operand2 = self.operand2
6338         type1 = operand1.type
6339         type2 = operand2.type
6340
6341         new_common_type = None
6342
6343         # catch general errors
6344         if type1 == str_type and (type2.is_string or type2 in (bytes_type, unicode_type)) or \
6345                type2 == str_type and (type1.is_string or type1 in (bytes_type, unicode_type)):
6346             error(self.pos, "Comparisons between bytes/unicode and str are not portable to Python 3")
6347             new_common_type = error_type
6348
6349         # try to use numeric comparisons where possible
6350         elif type1.is_complex or type2.is_complex:
6351             if op not in ('==', '!='):
6352                 error(self.pos, "complex types are unordered")
6353                 new_common_type = error_type
6354             if type1.is_pyobject:
6355                 new_common_type = type1
6356             elif type2.is_pyobject:
6357                 new_common_type = type2
6358             else:
6359                 new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
6360         elif type1.is_numeric and type2.is_numeric:
6361             new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
6362         elif common_type is None or not common_type.is_pyobject:
6363             new_common_type = self.find_common_int_type(env, op, operand1, operand2)
6364
6365         if new_common_type is None:
6366             # fall back to generic type compatibility tests
6367             if type1 == type2:
6368                 new_common_type = type1
6369             elif type1.is_pyobject or type2.is_pyobject:
6370                 if type2.is_numeric or type2.is_string:
6371                     if operand2.check_for_coercion_error(type1):
6372                         new_common_type = error_type
6373                     else:
6374                         new_common_type = py_object_type
6375                 elif type1.is_numeric or type1.is_string:
6376                     if operand1.check_for_coercion_error(type2):
6377                         new_common_type = error_type
6378                     else:
6379                         new_common_type = py_object_type
6380                 elif py_object_type.assignable_from(type1) and py_object_type.assignable_from(type2):
6381                     new_common_type = py_object_type
6382                 else:
6383                     # one Python type and one non-Python type, not assignable
6384                     self.invalid_types_error(operand1, op, operand2)
6385                     new_common_type = error_type
6386             elif type1.assignable_from(type2):
6387                 new_common_type = type1
6388             elif type2.assignable_from(type1):
6389                 new_common_type = type2
6390             else:
6391                 # C types that we couldn't handle up to here are an error
6392                 self.invalid_types_error(operand1, op, operand2)
6393                 new_common_type = error_type
6394
6395         if new_common_type.is_string and (isinstance(operand1, BytesNode) or
6396                                           isinstance(operand2, BytesNode)):
6397             # special case when comparing char* to bytes literal: must
6398             # compare string values!
6399             new_common_type = bytes_type
6400
6401         # recursively merge types
6402         if common_type is None or new_common_type.is_error:
6403             common_type = new_common_type
6404         else:
6405             # we could do a lot better by splitting the comparison
6406             # into a non-Python part and a Python part, but this is
6407             # safer for now
6408             common_type = PyrexTypes.spanning_type(common_type, new_common_type)
6409
6410         if self.cascade:
6411             common_type = self.cascade.find_common_type(env, self.operator, operand2, common_type)
6412
6413         return common_type
6414
6415     def invalid_types_error(self, operand1, op, operand2):
6416         error(self.pos, "Invalid types for '%s' (%s, %s)" %
6417               (op, operand1.type, operand2.type))
6418
6419     def is_python_comparison(self):
6420         return (not self.is_ptr_contains()
6421             and not self.is_c_string_contains()
6422             and (self.has_python_operands()
6423                  or (self.cascade and self.cascade.is_python_comparison())
6424                  or self.operator in ('in', 'not_in')))
6425
6426     def coerce_operands_to(self, dst_type, env):
6427         operand2 = self.operand2
6428         if operand2.type != dst_type:
6429             self.operand2 = operand2.coerce_to(dst_type, env)
6430         if self.cascade:
6431             self.cascade.coerce_operands_to(dst_type, env)
6432
6433     def is_python_result(self):
6434         return ((self.has_python_operands() and
6435                  self.special_bool_cmp_function is None and
6436                  self.operator not in ('is', 'is_not', 'in', 'not_in') and
6437                  not self.is_c_string_contains() and
6438                  not self.is_ptr_contains())
6439             or (self.cascade and self.cascade.is_python_result()))
6440
6441     def is_c_string_contains(self):
6442         return self.operator in ('in', 'not_in') and \
6443                ((self.operand1.type.is_int
6444                  and (self.operand2.type.is_string or self.operand2.type is bytes_type)) or
6445                 (self.operand1.type is PyrexTypes.c_py_unicode_type
6446                  and self.operand2.type is unicode_type))
6447
6448     def is_ptr_contains(self):
6449         if self.operator in ('in', 'not_in'):
6450             container_type = self.operand2.type
6451             return (container_type.is_ptr or container_type.is_array) \
6452                 and not container_type.is_string
6453
6454     def find_special_bool_compare_function(self, env):
6455         if self.operator in ('==', '!='):
6456             type1, type2 = self.operand1.type, self.operand2.type
6457             if type1.is_pyobject and type2.is_pyobject:
6458                 if type1 is Builtin.unicode_type or type2 is Builtin.unicode_type:
6459                     env.use_utility_code(pyunicode_equals_utility_code)
6460                     self.special_bool_cmp_function = "__Pyx_PyUnicode_Equals"
6461                     return True
6462         return False
6463
6464     def generate_operation_code(self, code, result_code,
6465             operand1, op , operand2):
6466         if self.type.is_pyobject:
6467             coerce_result = "__Pyx_PyBool_FromLong"
6468         else:
6469             coerce_result = ""
6470         if 'not' in op:
6471             negation = "!"
6472         else:
6473             negation = ""
6474         if self.special_bool_cmp_function:
6475             if operand1.type.is_pyobject:
6476                 result1 = operand1.py_result()
6477             else:
6478                 result1 = operand1.result()
6479             if operand2.type.is_pyobject:
6480                 result2 = operand2.py_result()
6481             else:
6482                 result2 = operand2.result()
6483             code.putln("%s = %s(%s, %s, %s); %s" % (
6484                 result_code,
6485                 self.special_bool_cmp_function,
6486                 result1,
6487                 result2,
6488                 richcmp_constants[op],
6489                 code.error_goto_if_neg(result_code, self.pos)))
6490         elif op == 'in' or op == 'not_in':
6491             code.globalstate.use_utility_code(contains_utility_code)
6492             if self.type.is_pyobject:
6493                 coerce_result = "__Pyx_PyBoolOrNull_FromLong"
6494             if op == 'not_in':
6495                 negation = "__Pyx_NegateNonNeg"
6496             if operand2.type is dict_type:
6497                 method = "PyDict_Contains"
6498             else:
6499                 method = "PySequence_Contains"
6500             if self.type.is_pyobject:
6501                 error_clause = code.error_goto_if_null
6502                 got_ref = "__Pyx_XGOTREF(%s); " % result_code
6503             else:
6504                 error_clause = code.error_goto_if_neg
6505                 got_ref = ""
6506             code.putln(
6507                 "%s = %s(%s(%s(%s, %s))); %s%s" % (
6508                     result_code,
6509                     coerce_result,
6510                     negation,
6511                     method,
6512                     operand2.py_result(),
6513                     operand1.py_result(),
6514                     got_ref,
6515                     error_clause(result_code, self.pos)))
6516         elif (operand1.type.is_pyobject
6517             and op not in ('is', 'is_not')):
6518                 code.putln("%s = PyObject_RichCompare(%s, %s, %s); %s" % (
6519                         result_code,
6520                         operand1.py_result(),
6521                         operand2.py_result(),
6522                         richcmp_constants[op],
6523                         code.error_goto_if_null(result_code, self.pos)))
6524                 code.put_gotref(result_code)
6525         elif operand1.type.is_complex:
6526             if op == "!=":
6527                 negation = "!"
6528             else:
6529                 negation = ""
6530             code.putln("%s = %s(%s%s(%s, %s));" % (
6531                 result_code,
6532                 coerce_result,
6533                 negation,
6534                 operand1.type.unary_op('eq'),
6535                 operand1.result(),
6536                 operand2.result()))
6537         else:
6538             type1 = operand1.type
6539             type2 = operand2.type
6540             if (type1.is_extension_type or type2.is_extension_type) \
6541                     and not type1.same_as(type2):
6542                 common_type = py_object_type
6543             elif type1.is_numeric:
6544                 common_type = PyrexTypes.widest_numeric_type(type1, type2)
6545             else:
6546                 common_type = type1
6547             code1 = operand1.result_as(common_type)
6548             code2 = operand2.result_as(common_type)
6549             code.putln("%s = %s(%s %s %s);" % (
6550                 result_code,
6551                 coerce_result,
6552                 code1,
6553                 self.c_operator(op),
6554                 code2))
6555
6556     def c_operator(self, op):
6557         if op == 'is':
6558             return "=="
6559         elif op == 'is_not':
6560             return "!="
6561         else:
6562             return op
6563
6564 contains_utility_code = UtilityCode(
6565 proto="""
6566 static CYTHON_INLINE long __Pyx_NegateNonNeg(long b) { return unlikely(b < 0) ? b : !b; }
6567 static CYTHON_INLINE PyObject* __Pyx_PyBoolOrNull_FromLong(long b) {
6568     return unlikely(b < 0) ? NULL : __Pyx_PyBool_FromLong(b);
6569 }
6570 """)
6571
6572 char_in_bytes_utility_code = UtilityCode(
6573 proto="""
6574 static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); /*proto*/
6575 """,
6576 impl="""
6577 static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) {
6578     const Py_ssize_t length = PyBytes_GET_SIZE(bytes);
6579     char* char_start = PyBytes_AS_STRING(bytes);
6580     char* pos;
6581     for (pos=char_start; pos < char_start+length; pos++) {
6582         if (character == pos[0]) return 1;
6583     }
6584     return 0;
6585 }
6586 """)
6587
6588 pyunicode_in_unicode_utility_code = UtilityCode(
6589 proto="""
6590 static CYTHON_INLINE int __Pyx_UnicodeContains(PyObject* unicode, Py_UNICODE character); /*proto*/
6591 """,
6592 impl="""
6593 static CYTHON_INLINE int __Pyx_UnicodeContains(PyObject* unicode, Py_UNICODE character) {
6594     const Py_ssize_t length = PyUnicode_GET_SIZE(unicode);
6595     Py_UNICODE* char_start = PyUnicode_AS_UNICODE(unicode);
6596     Py_UNICODE* pos;
6597     for (pos=char_start; pos < char_start+length; pos++) {
6598         if (character == pos[0]) return 1;
6599     }
6600     return 0;
6601 }
6602 """)
6603
6604 pyunicode_equals_utility_code = UtilityCode(
6605 proto="""
6606 static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/
6607 """,
6608 impl="""
6609 static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) {
6610     if (s1 == s2) {   /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */
6611         return (equals == Py_EQ);
6612     } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) {
6613         if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) {
6614             return (equals == Py_NE);
6615         } else if (PyUnicode_GET_SIZE(s1) == 1) {
6616             if (equals == Py_EQ)
6617                 return (PyUnicode_AS_UNICODE(s1)[0] == PyUnicode_AS_UNICODE(s2)[0]);
6618             else
6619                 return (PyUnicode_AS_UNICODE(s1)[0] != PyUnicode_AS_UNICODE(s2)[0]);
6620         } else {
6621             int result = PyUnicode_Compare(s1, s2);
6622             if ((result == -1) && unlikely(PyErr_Occurred()))
6623                 return -1;
6624             return (equals == Py_EQ) ? (result == 0) : (result != 0);
6625         }
6626     } else if ((s1 == Py_None) & (s2 == Py_None)) {
6627         return (equals == Py_EQ);
6628     } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) {
6629         return (equals == Py_NE);
6630     } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) {
6631         return (equals == Py_NE);
6632     } else {
6633         int result;
6634         PyObject* py_result = PyObject_RichCompare(s1, s2, equals);
6635         if (!py_result)
6636             return -1;
6637         result = __Pyx_PyObject_IsTrue(py_result);
6638         Py_DECREF(py_result);
6639         return result;
6640     }
6641 }
6642 """)
6643
6644
6645 class PrimaryCmpNode(ExprNode, CmpNode):
6646     #  Non-cascaded comparison or first comparison of
6647     #  a cascaded sequence.
6648     #
6649     #  operator      string
6650     #  operand1      ExprNode
6651     #  operand2      ExprNode
6652     #  cascade       CascadedCmpNode
6653
6654     #  We don't use the subexprs mechanism, because
6655     #  things here are too complicated for it to handle.
6656     #  Instead, we override all the framework methods
6657     #  which use it.
6658
6659     child_attrs = ['operand1', 'operand2', 'cascade']
6660
6661     cascade = None
6662
6663     def infer_type(self, env):
6664         # TODO: Actually implement this (after merging with -unstable).
6665         return py_object_type
6666
6667     def type_dependencies(self, env):
6668         return ()
6669
6670     def calculate_constant_result(self):
6671         self.calculate_cascaded_constant_result(self.operand1.constant_result)
6672
6673     def compile_time_value(self, denv):
6674         operand1 = self.operand1.compile_time_value(denv)
6675         return self.cascaded_compile_time_value(operand1, denv)
6676
6677     def analyse_types(self, env):
6678         self.operand1.analyse_types(env)
6679         self.operand2.analyse_types(env)
6680         if self.is_cpp_comparison():
6681             self.analyse_cpp_comparison(env)
6682             if self.cascade:
6683                 error(self.pos, "Cascading comparison not yet supported for cpp types.")
6684             return
6685         if self.cascade:
6686             self.cascade.analyse_types(env)
6687
6688         if self.operator in ('in', 'not_in'):
6689             if self.is_c_string_contains():
6690                 self.is_pycmp = False
6691                 common_type = None
6692                 if self.cascade:
6693                     error(self.pos, "Cascading comparison not yet supported for 'int_val in string'.")
6694                     return
6695                 if self.operand2.type is unicode_type:
6696                     env.use_utility_code(pyunicode_in_unicode_utility_code)
6697                 else:
6698                     if self.operand1.type is PyrexTypes.c_uchar_type:
6699                         self.operand1 = self.operand1.coerce_to(PyrexTypes.c_char_type, env)
6700                     if self.operand2.type is not bytes_type:
6701                         self.operand2 = self.operand2.coerce_to(bytes_type, env)
6702                     env.use_utility_code(char_in_bytes_utility_code)
6703                 self.operand2 = self.operand2.as_none_safe_node(
6704                     "argument of type 'NoneType' is not iterable")
6705             elif self.is_ptr_contains():
6706                 if self.cascade:
6707                     error(self.pos, "Cascading comparison not yet supported for 'val in sliced pointer'.")
6708                 self.type = PyrexTypes.c_bint_type
6709                 # Will be transformed by IterationTransform
6710                 return
6711             else:
6712                 if self.operand2.type is dict_type:
6713                     self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
6714                 common_type = py_object_type
6715                 self.is_pycmp = True
6716         elif self.find_special_bool_compare_function(env):
6717             common_type = None # if coercion needed, the method call above has already done it
6718             self.is_pycmp = False # result is bint
6719             self.is_temp = True # must check for error return
6720         else:
6721             common_type = self.find_common_type(env, self.operator, self.operand1)
6722             self.is_pycmp = common_type.is_pyobject
6723
6724         if common_type is not None and not common_type.is_error:
6725             if self.operand1.type != common_type:
6726                 self.operand1 = self.operand1.coerce_to(common_type, env)
6727             self.coerce_operands_to(common_type, env)
6728
6729         if self.cascade:
6730             self.operand2 = self.operand2.coerce_to_simple(env)
6731             self.cascade.coerce_cascaded_operands_to_temp(env)
6732         if self.is_python_result():
6733             self.type = PyrexTypes.py_object_type
6734         else:
6735             self.type = PyrexTypes.c_bint_type
6736         cdr = self.cascade
6737         while cdr:
6738             cdr.type = self.type
6739             cdr = cdr.cascade
6740         if self.is_pycmp or self.cascade:
6741             self.is_temp = 1
6742
6743     def analyse_cpp_comparison(self, env):
6744         type1 = self.operand1.type
6745         type2 = self.operand2.type
6746         entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
6747         if entry is None:
6748             error(self.pos, "Invalid types for '%s' (%s, %s)" %
6749                 (self.operator, type1, type2))
6750             self.type = PyrexTypes.error_type
6751             self.result_code = "<error>"
6752             return
6753         func_type = entry.type
6754         if func_type.is_ptr:
6755             func_type = func_type.base_type
6756         if len(func_type.args) == 1:
6757             self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
6758         else:
6759             self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
6760             self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
6761         self.type = func_type.return_type
6762
6763     def has_python_operands(self):
6764         return (self.operand1.type.is_pyobject
6765             or self.operand2.type.is_pyobject)
6766
6767     def check_const(self):
6768         if self.cascade:
6769             self.not_const()
6770             return False
6771         else:
6772             return self.operand1.check_const() and self.operand2.check_const()
6773
6774     def calculate_result_code(self):
6775         if self.operand1.type.is_complex:
6776             if self.operator == "!=":
6777                 negation = "!"
6778             else:
6779                 negation = ""
6780             return "(%s%s(%s, %s))" % (
6781                 negation,
6782                 self.operand1.type.binary_op('=='),
6783                 self.operand1.result(),
6784                 self.operand2.result())
6785         elif self.is_c_string_contains():
6786             if self.operand2.type is bytes_type:
6787                 method = "__Pyx_BytesContains"
6788             else:
6789                 method = "__Pyx_UnicodeContains"
6790             if self.operator == "not_in":
6791                 negation = "!"
6792             else:
6793                 negation = ""
6794             return "(%s%s(%s, %s))" % (
6795                 negation,
6796                 method,
6797                 self.operand2.result(),
6798                 self.operand1.result())
6799         else:
6800             return "(%s %s %s)" % (
6801                 self.operand1.result(),
6802                 self.c_operator(self.operator),
6803                 self.operand2.result())
6804
6805     def generate_evaluation_code(self, code):
6806         self.operand1.generate_evaluation_code(code)
6807         self.operand2.generate_evaluation_code(code)
6808         if self.is_temp:
6809             self.allocate_temp_result(code)
6810             self.generate_operation_code(code, self.result(),
6811                 self.operand1, self.operator, self.operand2)
6812             if self.cascade:
6813                 self.cascade.generate_evaluation_code(code,
6814                     self.result(), self.operand2)
6815             self.operand1.generate_disposal_code(code)
6816             self.operand1.free_temps(code)
6817             self.operand2.generate_disposal_code(code)
6818             self.operand2.free_temps(code)
6819
6820     def generate_subexpr_disposal_code(self, code):
6821         #  If this is called, it is a non-cascaded cmp,
6822         #  so only need to dispose of the two main operands.
6823         self.operand1.generate_disposal_code(code)
6824         self.operand2.generate_disposal_code(code)
6825
6826     def free_subexpr_temps(self, code):
6827         #  If this is called, it is a non-cascaded cmp,
6828         #  so only need to dispose of the two main operands.
6829         self.operand1.free_temps(code)
6830         self.operand2.free_temps(code)
6831
6832     def annotate(self, code):
6833         self.operand1.annotate(code)
6834         self.operand2.annotate(code)
6835         if self.cascade:
6836             self.cascade.annotate(code)
6837
6838
6839 class CascadedCmpNode(Node, CmpNode):
6840     #  A CascadedCmpNode is not a complete expression node. It
6841     #  hangs off the side of another comparison node, shares
6842     #  its left operand with that node, and shares its result
6843     #  with the PrimaryCmpNode at the head of the chain.
6844     #
6845     #  operator      string
6846     #  operand2      ExprNode
6847     #  cascade       CascadedCmpNode
6848
6849     child_attrs = ['operand2', 'cascade']
6850
6851     cascade = None
6852     constant_result = constant_value_not_set # FIXME: where to calculate this?
6853
6854     def infer_type(self, env):
6855         # TODO: Actually implement this (after merging with -unstable).
6856         return py_object_type
6857
6858     def type_dependencies(self, env):
6859         return ()
6860
6861     def has_constant_result(self):
6862         return self.constant_result is not constant_value_not_set and \
6863                self.constant_result is not not_a_constant
6864
6865     def analyse_types(self, env):
6866         self.operand2.analyse_types(env)
6867         if self.cascade:
6868             self.cascade.analyse_types(env)
6869
6870     def has_python_operands(self):
6871         return self.operand2.type.is_pyobject
6872
6873     def coerce_operands_to_pyobjects(self, env):
6874         self.operand2 = self.operand2.coerce_to_pyobject(env)
6875         if self.operand2.type is dict_type and self.operator in ('in', 'not_in'):
6876             self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
6877         if self.cascade:
6878             self.cascade.coerce_operands_to_pyobjects(env)
6879
6880     def coerce_cascaded_operands_to_temp(self, env):
6881         if self.cascade:
6882             #self.operand2 = self.operand2.coerce_to_temp(env) #CTT
6883             self.operand2 = self.operand2.coerce_to_simple(env)
6884             self.cascade.coerce_cascaded_operands_to_temp(env)
6885
6886     def generate_evaluation_code(self, code, result, operand1):
6887         if self.type.is_pyobject:
6888             code.putln("if (__Pyx_PyObject_IsTrue(%s)) {" % result)
6889             code.put_decref(result, self.type)
6890         else:
6891             code.putln("if (%s) {" % result)
6892         self.operand2.generate_evaluation_code(code)
6893         self.generate_operation_code(code, result,
6894             operand1, self.operator, self.operand2)
6895         if self.cascade:
6896             self.cascade.generate_evaluation_code(
6897                 code, result, self.operand2)
6898         # Cascaded cmp result is always temp
6899         self.operand2.generate_disposal_code(code)
6900         self.operand2.free_temps(code)
6901         code.putln("}")
6902
6903     def annotate(self, code):
6904         self.operand2.annotate(code)
6905         if self.cascade:
6906             self.cascade.annotate(code)
6907
6908
6909 binop_node_classes = {
6910     "or":       BoolBinopNode,
6911     "and":      BoolBinopNode,
6912     "|":        IntBinopNode,
6913     "^":        IntBinopNode,
6914     "&":        IntBinopNode,
6915     "<<":       IntBinopNode,
6916     ">>":       IntBinopNode,
6917     "+":        AddNode,
6918     "-":        SubNode,
6919     "*":        MulNode,
6920     "/":        DivNode,
6921     "//":       DivNode,
6922     "%":        ModNode,
6923     "**":       PowNode
6924 }
6925
6926 def binop_node(pos, operator, operand1, operand2, inplace=False):
6927     # Construct binop node of appropriate class for
6928     # given operator.
6929     return binop_node_classes[operator](pos,
6930         operator = operator,
6931         operand1 = operand1,
6932         operand2 = operand2,
6933         inplace = inplace)
6934
6935 #-------------------------------------------------------------------
6936 #
6937 #  Coercion nodes
6938 #
6939 #  Coercion nodes are special in that they are created during
6940 #  the analyse_types phase of parse tree processing.
6941 #  Their __init__ methods consequently incorporate some aspects
6942 #  of that phase.
6943 #
6944 #-------------------------------------------------------------------
6945
6946 class CoercionNode(ExprNode):
6947     #  Abstract base class for coercion nodes.
6948     #
6949     #  arg       ExprNode       node being coerced
6950
6951     subexprs = ['arg']
6952     constant_result = not_a_constant
6953
6954     def __init__(self, arg):
6955         self.pos = arg.pos
6956         self.arg = arg
6957         if debug_coercion:
6958             print("%s Coercing %s" % (self, self.arg))
6959
6960     def calculate_constant_result(self):
6961         # constant folding can break type coercion, so this is disabled
6962         pass
6963
6964     def annotate(self, code):
6965         self.arg.annotate(code)
6966         if self.arg.type != self.type:
6967             file, line, col = self.pos
6968             code.annotate((file, line, col-1), AnnotationItem(style='coerce', tag='coerce', text='[%s] to [%s]' % (self.arg.type, self.type)))
6969
6970
6971 class CastNode(CoercionNode):
6972     #  Wrap a node in a C type cast.
6973
6974     def __init__(self, arg, new_type):
6975         CoercionNode.__init__(self, arg)
6976         self.type = new_type
6977
6978     def may_be_none(self):
6979         return self.arg.may_be_none()
6980
6981     def calculate_result_code(self):
6982         return self.arg.result_as(self.type)
6983
6984     def generate_result_code(self, code):
6985         self.arg.generate_result_code(code)
6986
6987
6988 class PyTypeTestNode(CoercionNode):
6989     #  This node is used to check that a generic Python
6990     #  object is an instance of a particular extension type.
6991     #  This node borrows the result of its argument node.
6992
6993     def __init__(self, arg, dst_type, env, notnone=False):
6994         #  The arg is know to be a Python object, and
6995         #  the dst_type is known to be an extension type.
6996         assert dst_type.is_extension_type or dst_type.is_builtin_type, "PyTypeTest on non extension type"
6997         CoercionNode.__init__(self, arg)
6998         self.type = dst_type
6999         self.result_ctype = arg.ctype()
7000         self.notnone = notnone
7001
7002     nogil_check = Node.gil_error
7003     gil_message = "Python type test"
7004
7005     def analyse_types(self, env):
7006         pass
7007
7008     def may_be_none(self):
7009         if self.notnone:
7010             return False
7011         return self.arg.may_be_none()
7012
7013     def result_in_temp(self):
7014         return self.arg.result_in_temp()
7015
7016     def is_ephemeral(self):
7017         return self.arg.is_ephemeral()
7018
7019     def calculate_constant_result(self):
7020         # FIXME
7021         pass
7022
7023     def calculate_result_code(self):
7024         return self.arg.result()
7025
7026     def generate_result_code(self, code):
7027         if self.type.typeobj_is_available():
7028             if not self.type.is_builtin_type:
7029                 code.globalstate.use_utility_code(type_test_utility_code)
7030             code.putln(
7031                 "if (!(%s)) %s" % (
7032                     self.type.type_test_code(self.arg.py_result(), self.notnone),
7033                     code.error_goto(self.pos)))
7034         else:
7035             error(self.pos, "Cannot test type of extern C class "
7036                 "without type object name specification")
7037
7038     def generate_post_assignment_code(self, code):
7039         self.arg.generate_post_assignment_code(code)
7040
7041     def free_temps(self, code):
7042         self.arg.free_temps(code)
7043
7044
7045 class NoneCheckNode(CoercionNode):
7046     # This node is used to check that a Python object is not None and
7047     # raises an appropriate exception (as specified by the creating
7048     # transform).
7049
7050     def __init__(self, arg, exception_type_cname, exception_message):
7051         CoercionNode.__init__(self, arg)
7052         self.type = arg.type
7053         self.result_ctype = arg.ctype()
7054         self.exception_type_cname = exception_type_cname
7055         self.exception_message = exception_message
7056
7057     def analyse_types(self, env):
7058         pass
7059
7060     def may_be_none(self):
7061         return False
7062
7063     def result_in_temp(self):
7064         return self.arg.result_in_temp()
7065
7066     def calculate_result_code(self):
7067         return self.arg.result()
7068
7069     def generate_result_code(self, code):
7070         code.putln(
7071             "if (unlikely(%s == Py_None)) {" % self.arg.result())
7072         code.putln('PyErr_SetString(%s, "%s"); %s ' % (
7073             self.exception_type_cname,
7074             StringEncoding.escape_byte_string(
7075                 self.exception_message.encode('UTF-8')),
7076             code.error_goto(self.pos)))
7077         code.putln("}")
7078
7079     def generate_post_assignment_code(self, code):
7080         self.arg.generate_post_assignment_code(code)
7081
7082     def free_temps(self, code):
7083         self.arg.free_temps(code)
7084
7085
7086 class CoerceToPyTypeNode(CoercionNode):
7087     #  This node is used to convert a C data type
7088     #  to a Python object.
7089
7090     type = py_object_type
7091     is_temp = 1
7092
7093     def __init__(self, arg, env, type=py_object_type):
7094         CoercionNode.__init__(self, arg)
7095         if not arg.type.create_to_py_utility_code(env):
7096             error(arg.pos,
7097                   "Cannot convert '%s' to Python object" % arg.type)
7098         if type is py_object_type:
7099             # be specific about some known types
7100             if arg.type.is_string:
7101                 self.type = bytes_type
7102             elif arg.type is PyrexTypes.c_py_unicode_type:
7103                 self.type = unicode_type
7104             elif arg.type.is_complex:
7105                 self.type = Builtin.complex_type
7106         else:
7107             # FIXME: check that the target type and the resulting type are compatible
7108             pass
7109
7110     gil_message = "Converting to Python object"
7111
7112     def may_be_none(self):
7113         # FIXME: is this always safe?
7114         return False
7115
7116     def coerce_to_boolean(self, env):
7117         arg_type = self.arg.type
7118         if (arg_type == PyrexTypes.c_bint_type or
7119             (arg_type.is_pyobject and arg_type.name == 'bool')):
7120             return self.arg.coerce_to_temp(env)
7121         else:
7122             return CoerceToBooleanNode(self, env)
7123
7124     def coerce_to_integer(self, env):
7125         # If not already some C integer type, coerce to longint.
7126         if self.arg.type.is_int:
7127             return self.arg
7128         else:
7129             return self.arg.coerce_to(PyrexTypes.c_long_type, env)
7130
7131     def analyse_types(self, env):
7132         # The arg is always already analysed
7133         pass
7134
7135     def generate_result_code(self, code):
7136         function = self.arg.type.to_py_function
7137         code.putln('%s = %s(%s); %s' % (
7138             self.result(),
7139             function,
7140             self.arg.result(),
7141             code.error_goto_if_null(self.result(), self.pos)))
7142         code.put_gotref(self.py_result())
7143
7144
7145 class CoerceIntToBytesNode(CoerceToPyTypeNode):
7146     #  This node is used to convert a C int type to a Python bytes
7147     #  object.
7148
7149     is_temp = 1
7150
7151     def __init__(self, arg, env):
7152         arg = arg.coerce_to_simple(env)
7153         CoercionNode.__init__(self, arg)
7154         self.type = Builtin.bytes_type
7155
7156     def generate_result_code(self, code):
7157         arg = self.arg
7158         arg_result = arg.result()
7159         if arg.type not in (PyrexTypes.c_char_type,
7160                             PyrexTypes.c_uchar_type,
7161                             PyrexTypes.c_schar_type):
7162             if arg.type.signed:
7163                 code.putln("if ((%s < 0) || (%s > 255)) {" % (
7164                     arg_result, arg_result))
7165             else:
7166                 code.putln("if (%s > 255) {" % arg_result)
7167             code.putln('PyErr_Format(PyExc_OverflowError, '
7168                        '"value too large to pack into a byte"); %s' % (
7169                            code.error_goto(self.pos)))
7170             code.putln('}')
7171         temp = None
7172         if arg.type is not PyrexTypes.c_char_type:
7173             temp = code.funcstate.allocate_temp(PyrexTypes.c_char_type, manage_ref=False)
7174             code.putln("%s = (char)%s;" % (temp, arg_result))
7175             arg_result = temp
7176         code.putln('%s = PyBytes_FromStringAndSize(&%s, 1); %s' % (
7177             self.result(),
7178             arg_result,
7179             code.error_goto_if_null(self.result(), self.pos)))
7180         if temp is not None:
7181             code.funcstate.release_temp(temp)
7182         code.put_gotref(self.py_result())
7183
7184
7185 class CoerceFromPyTypeNode(CoercionNode):
7186     #  This node is used to convert a Python object
7187     #  to a C data type.
7188
7189     def __init__(self, result_type, arg, env):
7190         CoercionNode.__init__(self, arg)
7191         self.type = result_type
7192         self.is_temp = 1
7193         if not result_type.create_from_py_utility_code(env):
7194             error(arg.pos,
7195                   "Cannot convert Python object to '%s'" % result_type)
7196         if self.type.is_string and self.arg.is_ephemeral():
7197             error(arg.pos,
7198                   "Obtaining char * from temporary Python value")
7199
7200     def analyse_types(self, env):
7201         # The arg is always already analysed
7202         pass
7203
7204     def generate_result_code(self, code):
7205         function = self.type.from_py_function
7206         operand = self.arg.py_result()
7207         rhs = "%s(%s)" % (function, operand)
7208         if self.type.is_enum:
7209             rhs = typecast(self.type, c_long_type, rhs)
7210         code.putln('%s = %s; %s' % (
7211             self.result(),
7212             rhs,
7213             code.error_goto_if(self.type.error_condition(self.result()), self.pos)))
7214         if self.type.is_pyobject:
7215             code.put_gotref(self.py_result())
7216
7217
7218 class CoerceToBooleanNode(CoercionNode):
7219     #  This node is used when a result needs to be used
7220     #  in a boolean context.
7221
7222     type = PyrexTypes.c_bint_type
7223
7224     _special_builtins = {
7225         Builtin.list_type    : 'PyList_GET_SIZE',
7226         Builtin.tuple_type   : 'PyTuple_GET_SIZE',
7227         Builtin.bytes_type   : 'PyBytes_GET_SIZE',
7228         Builtin.unicode_type : 'PyUnicode_GET_SIZE',
7229         }
7230
7231     def __init__(self, arg, env):
7232         CoercionNode.__init__(self, arg)
7233         if arg.type.is_pyobject:
7234             self.is_temp = 1
7235
7236     def nogil_check(self, env):
7237         if self.arg.type.is_pyobject and self._special_builtins.get(self.arg.type) is None:
7238             self.gil_error()
7239
7240     gil_message = "Truth-testing Python object"
7241
7242     def check_const(self):
7243         if self.is_temp:
7244             self.not_const()
7245             return False
7246         return self.arg.check_const()
7247
7248     def calculate_result_code(self):
7249         return "(%s != 0)" % self.arg.result()
7250
7251     def generate_result_code(self, code):
7252         if not self.is_temp:
7253             return
7254         test_func = self._special_builtins.get(self.arg.type)
7255         if test_func is not None:
7256             code.putln("%s = (%s != Py_None) && (%s(%s) != 0);" % (
7257                        self.result(),
7258                        self.arg.py_result(),
7259                        test_func,
7260                        self.arg.py_result()))
7261         else:
7262             code.putln(
7263                 "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
7264                     self.result(),
7265                     self.arg.py_result(),
7266                     code.error_goto_if_neg(self.result(), self.pos)))
7267
7268 class CoerceToComplexNode(CoercionNode):
7269
7270     def __init__(self, arg, dst_type, env):
7271         if arg.type.is_complex:
7272             arg = arg.coerce_to_simple(env)
7273         self.type = dst_type
7274         CoercionNode.__init__(self, arg)
7275         dst_type.create_declaration_utility_code(env)
7276
7277     def calculate_result_code(self):
7278         if self.arg.type.is_complex:
7279             real_part = "__Pyx_CREAL(%s)" % self.arg.result()
7280             imag_part = "__Pyx_CIMAG(%s)" % self.arg.result()
7281         else:
7282             real_part = self.arg.result()
7283             imag_part = "0"
7284         return "%s(%s, %s)" % (
7285                 self.type.from_parts,
7286                 real_part,
7287                 imag_part)
7288
7289     def generate_result_code(self, code):
7290         pass
7291
7292 class CoerceToTempNode(CoercionNode):
7293     #  This node is used to force the result of another node
7294     #  to be stored in a temporary. It is only used if the
7295     #  argument node's result is not already in a temporary.
7296
7297     def __init__(self, arg, env):
7298         CoercionNode.__init__(self, arg)
7299         self.type = self.arg.type
7300         self.constant_result = self.arg.constant_result
7301         self.is_temp = 1
7302         if self.type.is_pyobject:
7303             self.result_ctype = py_object_type
7304
7305     gil_message = "Creating temporary Python reference"
7306
7307     def analyse_types(self, env):
7308         # The arg is always already analysed
7309         pass
7310
7311     def coerce_to_boolean(self, env):
7312         self.arg = self.arg.coerce_to_boolean(env)
7313         if self.arg.is_simple():
7314             return self.arg
7315         self.type = self.arg.type
7316         self.result_ctype = self.type
7317         return self
7318
7319     def generate_result_code(self, code):
7320         #self.arg.generate_evaluation_code(code) # Already done
7321         # by generic generate_subexpr_evaluation_code!
7322         code.putln("%s = %s;" % (
7323             self.result(), self.arg.result_as(self.ctype())))
7324         if self.type.is_pyobject and self.use_managed_ref:
7325             code.put_incref(self.result(), self.ctype())
7326
7327
7328 class CloneNode(CoercionNode):
7329     #  This node is employed when the result of another node needs
7330     #  to be used multiple times. The argument node's result must
7331     #  be in a temporary. This node "borrows" the result from the
7332     #  argument node, and does not generate any evaluation or
7333     #  disposal code for it. The original owner of the argument
7334     #  node is responsible for doing those things.
7335
7336     subexprs = [] # Arg is not considered a subexpr
7337     nogil_check = None
7338
7339     def __init__(self, arg):
7340         CoercionNode.__init__(self, arg)
7341         if hasattr(arg, 'type'):
7342             self.type = arg.type
7343             self.result_ctype = arg.result_ctype
7344         if hasattr(arg, 'entry'):
7345             self.entry = arg.entry
7346
7347     def result(self):
7348         return self.arg.result()
7349
7350     def type_dependencies(self, env):
7351         return self.arg.type_dependencies(env)
7352
7353     def infer_type(self, env):
7354         return self.arg.infer_type(env)
7355
7356     def analyse_types(self, env):
7357         self.type = self.arg.type
7358         self.result_ctype = self.arg.result_ctype
7359         self.is_temp = 1
7360         if hasattr(self.arg, 'entry'):
7361             self.entry = self.arg.entry
7362
7363     def generate_evaluation_code(self, code):
7364         pass
7365
7366     def generate_result_code(self, code):
7367         pass
7368
7369     def generate_disposal_code(self, code):
7370         pass
7371
7372     def free_temps(self, code):
7373         pass
7374
7375
7376 class ModuleRefNode(ExprNode):
7377     # Simple returns the module object
7378
7379     type = py_object_type
7380     is_temp = False
7381     subexprs = []
7382
7383     def analyse_types(self, env):
7384         pass
7385
7386     def may_be_none(self):
7387         return False
7388
7389     def calculate_result_code(self):
7390         return Naming.module_cname
7391
7392     def generate_result_code(self, code):
7393         pass
7394
7395 class DocstringRefNode(ExprNode):
7396     # Extracts the docstring of the body element
7397
7398     subexprs = ['body']
7399     type = py_object_type
7400     is_temp = True
7401
7402     def __init__(self, pos, body):
7403         ExprNode.__init__(self, pos)
7404         assert body.type.is_pyobject
7405         self.body = body
7406
7407     def analyse_types(self, env):
7408         pass
7409
7410     def generate_result_code(self, code):
7411         code.putln('%s = __Pyx_GetAttrString(%s, "__doc__"); %s' % (
7412             self.result(), self.body.result(),
7413             code.error_goto_if_null(self.result(), self.pos)))
7414         code.put_gotref(self.result())
7415
7416
7417
7418 #------------------------------------------------------------------------------------
7419 #
7420 #  Runtime support code
7421 #
7422 #------------------------------------------------------------------------------------
7423
7424 get_name_interned_utility_code = UtilityCode(
7425 proto = """
7426 static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
7427 """,
7428 impl = """
7429 static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
7430     PyObject *result;
7431     result = PyObject_GetAttr(dict, name);
7432     if (!result)
7433         PyErr_SetObject(PyExc_NameError, name);
7434     return result;
7435 }
7436 """)
7437
7438 #------------------------------------------------------------------------------------
7439
7440 import_utility_code = UtilityCode(
7441 proto = """
7442 static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/
7443 """,
7444 impl = """
7445 static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) {
7446     PyObject *py_import = 0;
7447     PyObject *empty_list = 0;
7448     PyObject *module = 0;
7449     PyObject *global_dict = 0;
7450     PyObject *empty_dict = 0;
7451     PyObject *list;
7452     py_import = __Pyx_GetAttrString(%(BUILTINS)s, "__import__");
7453     if (!py_import)
7454         goto bad;
7455     if (from_list)
7456         list = from_list;
7457     else {
7458         empty_list = PyList_New(0);
7459         if (!empty_list)
7460             goto bad;
7461         list = empty_list;
7462     }
7463     global_dict = PyModule_GetDict(%(GLOBALS)s);
7464     if (!global_dict)
7465         goto bad;
7466     empty_dict = PyDict_New();
7467     if (!empty_dict)
7468         goto bad;
7469     module = PyObject_CallFunctionObjArgs(py_import,
7470         name, global_dict, empty_dict, list, NULL);
7471 bad:
7472     Py_XDECREF(empty_list);
7473     Py_XDECREF(py_import);
7474     Py_XDECREF(empty_dict);
7475     return module;
7476 }
7477 """ % {
7478     "BUILTINS": Naming.builtins_cname,
7479     "GLOBALS":  Naming.module_cname,
7480 })
7481
7482 #------------------------------------------------------------------------------------
7483
7484 get_exception_utility_code = UtilityCode(
7485 proto = """
7486 static PyObject *__Pyx_GetExcValue(void); /*proto*/
7487 """,
7488 impl = """
7489 static PyObject *__Pyx_GetExcValue(void) {
7490     PyObject *type = 0, *value = 0, *tb = 0;
7491     PyObject *tmp_type, *tmp_value, *tmp_tb;
7492     PyObject *result = 0;
7493     PyThreadState *tstate = PyThreadState_Get();
7494     PyErr_Fetch(&type, &value, &tb);
7495     PyErr_NormalizeException(&type, &value, &tb);
7496     if (PyErr_Occurred())
7497         goto bad;
7498     if (!value) {
7499         value = Py_None;
7500         Py_INCREF(value);
7501     }
7502     tmp_type = tstate->exc_type;
7503     tmp_value = tstate->exc_value;
7504     tmp_tb = tstate->exc_traceback;
7505     tstate->exc_type = type;
7506     tstate->exc_value = value;
7507     tstate->exc_traceback = tb;
7508     /* Make sure tstate is in a consistent state when we XDECREF
7509     these objects (XDECREF may run arbitrary code). */
7510     Py_XDECREF(tmp_type);
7511     Py_XDECREF(tmp_value);
7512     Py_XDECREF(tmp_tb);
7513     result = value;
7514     Py_XINCREF(result);
7515     type = 0;
7516     value = 0;
7517     tb = 0;
7518 bad:
7519     Py_XDECREF(type);
7520     Py_XDECREF(value);
7521     Py_XDECREF(tb);
7522     return result;
7523 }
7524 """)
7525
7526 #------------------------------------------------------------------------------------
7527
7528 type_test_utility_code = UtilityCode(
7529 proto = """
7530 static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/
7531 """,
7532 impl = """
7533 static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) {
7534     if (unlikely(!type)) {
7535         PyErr_Format(PyExc_SystemError, "Missing type object");
7536         return 0;
7537     }
7538     if (likely(PyObject_TypeCheck(obj, type)))
7539         return 1;
7540     PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s",
7541                  Py_TYPE(obj)->tp_name, type->tp_name);
7542     return 0;
7543 }
7544 """)
7545
7546 #------------------------------------------------------------------------------------
7547
7548 find_py2_metaclass_utility_code = UtilityCode(
7549 proto = '''
7550 static PyObject *__Pyx_FindPy2Metaclass(PyObject *bases); /*proto*/
7551 ''',
7552 impl = '''
7553 static PyObject *__Pyx_FindPy2Metaclass(PyObject *bases) {
7554     PyObject *metaclass;
7555     /* Default metaclass */
7556 #if PY_MAJOR_VERSION < 3
7557     if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7558         PyObject *base = PyTuple_GET_ITEM(bases, 0);
7559         metaclass = PyObject_GetAttrString(base, "__class__");
7560         if (!metaclass) {
7561             PyErr_Clear();
7562             metaclass = (PyObject*) Py_TYPE(base);
7563         }
7564     } else {
7565         metaclass = (PyObject *) &PyClass_Type;
7566     }
7567 #else
7568     if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7569         PyObject *base = PyTuple_GET_ITEM(bases, 0);
7570         metaclass = (PyObject*) Py_TYPE(base);
7571     } else {
7572         metaclass = (PyObject *) &PyType_Type;
7573     }
7574 #endif
7575     Py_INCREF(metaclass);
7576     return metaclass;
7577 }
7578 ''')
7579
7580 create_class_utility_code = UtilityCode(
7581 proto = """
7582 static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name,
7583                                    PyObject *modname); /*proto*/
7584 """,
7585 impl = """
7586 static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name,
7587                                    PyObject *modname) {
7588     PyObject *result;
7589     PyObject *metaclass;
7590
7591     if (PyDict_SetItemString(dict, "__module__", modname) < 0)
7592         return NULL;
7593
7594     /* Python2 __metaclass__ */
7595     metaclass = PyDict_GetItemString(dict, "__metaclass__");
7596     if (metaclass) {
7597         Py_INCREF(metaclass);
7598     } else {
7599         metaclass = __Pyx_FindPy2Metaclass(bases);
7600     }
7601     result = PyObject_CallFunctionObjArgs(metaclass, name, bases, dict, NULL);
7602     Py_DECREF(metaclass);
7603     return result;
7604 }
7605 """,
7606 requires = [find_py2_metaclass_utility_code])
7607
7608 #------------------------------------------------------------------------------------
7609
7610 create_py3class_utility_code = UtilityCode(
7611 proto = """
7612 static PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw); /*proto*/
7613 static PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *mkw, PyObject *modname, PyObject *doc); /*proto*/
7614 static PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, PyObject *mkw); /*proto*/
7615 """,
7616 impl = """
7617 PyObject *__Pyx_Py3MetaclassGet(PyObject *bases, PyObject *mkw) {
7618     PyObject *metaclass = PyDict_GetItemString(mkw, "metaclass");
7619     if (metaclass) {
7620         Py_INCREF(metaclass);
7621         if (PyDict_DelItemString(mkw, "metaclass") < 0) {
7622             Py_DECREF(metaclass);
7623             return NULL;
7624         }
7625         return metaclass;
7626     }
7627     return __Pyx_FindPy2Metaclass(bases);
7628 }
7629
7630 PyObject *__Pyx_Py3MetaclassPrepare(PyObject *metaclass, PyObject *bases, PyObject *name, PyObject *mkw,
7631                                     PyObject *modname, PyObject *doc) {
7632     PyObject *prep;
7633     PyObject *pargs;
7634     PyObject *ns;
7635     PyObject *str;
7636
7637     prep = PyObject_GetAttrString(metaclass, "__prepare__");
7638     if (!prep) {
7639         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
7640             return NULL;
7641         PyErr_Clear();
7642         return PyDict_New();
7643     }
7644     pargs = PyTuple_New(2);
7645     if (!pargs) {
7646         Py_DECREF(prep);
7647         return NULL;
7648     }
7649
7650     Py_INCREF(name);
7651     Py_INCREF(bases);
7652     PyTuple_SET_ITEM(pargs, 0, name);
7653     PyTuple_SET_ITEM(pargs, 1, bases);
7654
7655     ns = PyObject_Call(prep, pargs, mkw);
7656
7657     Py_DECREF(prep);
7658     Py_DECREF(pargs);
7659
7660     if (ns == NULL)
7661         return NULL;
7662
7663     /* Required here to emulate assignment order */
7664     /* XXX: use consts here */
7665     #if PY_MAJOR_VERSION >= 3
7666     str = PyUnicode_FromString("__module__");
7667     #else
7668     str = PyString_FromString("__module__");
7669     #endif
7670     if (!str) {
7671         Py_DECREF(ns);
7672         return NULL;
7673     }
7674
7675     if (PyObject_SetItem(ns, str, modname) < 0) {
7676         Py_DECREF(ns);
7677         Py_DECREF(str);
7678         return NULL;
7679     }
7680     Py_DECREF(str);
7681     if (doc) {
7682         #if PY_MAJOR_VERSION >= 3
7683         str = PyUnicode_FromString("__doc__");
7684         #else
7685         str = PyString_FromString("__doc__");
7686         #endif
7687         if (!str) {
7688             Py_DECREF(ns);
7689             return NULL;
7690         }
7691         if (PyObject_SetItem(ns, str, doc) < 0) {
7692             Py_DECREF(ns);
7693             Py_DECREF(str);
7694             return NULL;
7695         }
7696         Py_DECREF(str);
7697     }
7698     return ns;
7699 }
7700
7701 PyObject *__Pyx_Py3ClassCreate(PyObject *metaclass, PyObject *name, PyObject *bases, PyObject *dict, PyObject *mkw) {
7702     PyObject *result;
7703     PyObject *margs = PyTuple_New(3);
7704     if (!margs)
7705         return NULL;
7706     Py_INCREF(name);
7707     Py_INCREF(bases);
7708     Py_INCREF(dict);
7709     PyTuple_SET_ITEM(margs, 0, name);
7710     PyTuple_SET_ITEM(margs, 1, bases);
7711     PyTuple_SET_ITEM(margs, 2, dict);
7712     result = PyObject_Call(metaclass, margs, mkw);
7713     Py_DECREF(margs);
7714     return result;
7715 }
7716 """,
7717 requires = [find_py2_metaclass_utility_code])
7718
7719 #------------------------------------------------------------------------------------
7720
7721 cpp_exception_utility_code = UtilityCode(
7722 proto = """
7723 #ifndef __Pyx_CppExn2PyErr
7724 static void __Pyx_CppExn2PyErr() {
7725   try {
7726     if (PyErr_Occurred())
7727       ; // let the latest Python exn pass through and ignore the current one
7728     else
7729       throw;
7730   } catch (const std::invalid_argument& exn) {
7731     // Catch a handful of different errors here and turn them into the
7732     // equivalent Python errors.
7733     // Change invalid_argument to ValueError
7734     PyErr_SetString(PyExc_ValueError, exn.what());
7735   } catch (const std::out_of_range& exn) {
7736     // Change out_of_range to IndexError
7737     PyErr_SetString(PyExc_IndexError, exn.what());
7738   } catch (const std::exception& exn) {
7739     PyErr_SetString(PyExc_RuntimeError, exn.what());
7740   }
7741   catch (...)
7742   {
7743     PyErr_SetString(PyExc_RuntimeError, "Unknown exception");
7744   }
7745 }
7746 #endif
7747 """,
7748 impl = ""
7749 )
7750
7751 pyerr_occurred_withgil_utility_code= UtilityCode(
7752 proto = """
7753 static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void); /* proto */
7754 """,
7755 impl = """
7756 static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void) {
7757   int err;
7758   #ifdef WITH_THREAD
7759   PyGILState_STATE _save = PyGILState_Ensure();
7760   #endif
7761   err = !!PyErr_Occurred();
7762   #ifdef WITH_THREAD
7763   PyGILState_Release(_save);
7764   #endif
7765   return err;
7766 }
7767 """
7768 )
7769
7770 #------------------------------------------------------------------------------------
7771
7772 raise_noneattr_error_utility_code = UtilityCode(
7773 proto = """
7774 static CYTHON_INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname);
7775 """,
7776 impl = '''
7777 static CYTHON_INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname) {
7778     PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", attrname);
7779 }
7780 ''')
7781
7782 raise_noneindex_error_utility_code = UtilityCode(
7783 proto = """
7784 static CYTHON_INLINE void __Pyx_RaiseNoneIndexingError(void);
7785 """,
7786 impl = '''
7787 static CYTHON_INLINE void __Pyx_RaiseNoneIndexingError(void) {
7788     PyErr_SetString(PyExc_TypeError, "'NoneType' object is unsubscriptable");
7789 }
7790 ''')
7791
7792 raise_none_iter_error_utility_code = UtilityCode(
7793 proto = """
7794 static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void);
7795 """,
7796 impl = '''
7797 static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) {
7798     PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
7799 }
7800 ''')
7801
7802 #------------------------------------------------------------------------------------
7803
7804 getitem_dict_utility_code = UtilityCode(
7805 proto = """
7806 #if PY_MAJOR_VERSION >= 3
7807 static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) {
7808     PyObject *value;
7809     if (unlikely(d == Py_None)) {
7810         __Pyx_RaiseNoneIndexingError();
7811         return NULL;
7812     }
7813     value = PyDict_GetItemWithError(d, key);
7814     if (unlikely(!value)) {
7815         if (!PyErr_Occurred())
7816             PyErr_SetObject(PyExc_KeyError, key);
7817         return NULL;
7818     }
7819     Py_INCREF(value);
7820     return value;
7821 }
7822 #else
7823     #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key)
7824 #endif
7825 """,
7826 requires = [raise_noneindex_error_utility_code])
7827
7828 #------------------------------------------------------------------------------------
7829
7830 getitem_int_pyunicode_utility_code = UtilityCode(
7831 proto = '''
7832 #define __Pyx_GetItemInt_Unicode(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7833                                                __Pyx_GetItemInt_Unicode_Fast(o, i) : \\
7834                                                __Pyx_GetItemInt_Unicode_Generic(o, to_py_func(i)))
7835
7836 static CYTHON_INLINE Py_UNICODE __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i) {
7837     if (likely((0 <= i) & (i < PyUnicode_GET_SIZE(ustring)))) {
7838         return PyUnicode_AS_UNICODE(ustring)[i];
7839     } else if ((-PyUnicode_GET_SIZE(ustring) <= i) & (i < 0)) {
7840         i += PyUnicode_GET_SIZE(ustring);
7841         return PyUnicode_AS_UNICODE(ustring)[i];
7842     } else {
7843         PyErr_SetString(PyExc_IndexError, "string index out of range");
7844         return (Py_UNICODE)-1;
7845     }
7846 }
7847
7848 static CYTHON_INLINE Py_UNICODE __Pyx_GetItemInt_Unicode_Generic(PyObject* ustring, PyObject* j) {
7849     Py_UNICODE uchar;
7850     PyObject *uchar_string;
7851     if (!j) return (Py_UNICODE)-1;
7852     uchar_string = PyObject_GetItem(ustring, j);
7853     Py_DECREF(j);
7854     if (!uchar_string) return (Py_UNICODE)-1;
7855     uchar = PyUnicode_AS_UNICODE(uchar_string)[0];
7856     Py_DECREF(uchar_string);
7857     return uchar;
7858 }
7859 ''')
7860
7861 getitem_int_utility_code = UtilityCode(
7862 proto = """
7863
7864 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) {
7865     PyObject *r;
7866     if (!j) return NULL;
7867     r = PyObject_GetItem(o, j);
7868     Py_DECREF(j);
7869     return r;
7870 }
7871
7872 """ + ''.join([
7873 """
7874 #define __Pyx_GetItemInt_%(type)s(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7875                                                     __Pyx_GetItemInt_%(type)s_Fast(o, i) : \\
7876                                                     __Pyx_GetItemInt_Generic(o, to_py_func(i)))
7877
7878 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_%(type)s_Fast(PyObject *o, Py_ssize_t i) {
7879     if (likely(o != Py_None)) {
7880         if (likely((0 <= i) & (i < Py%(type)s_GET_SIZE(o)))) {
7881             PyObject *r = Py%(type)s_GET_ITEM(o, i);
7882             Py_INCREF(r);
7883             return r;
7884         }
7885         else if ((-Py%(type)s_GET_SIZE(o) <= i) & (i < 0)) {
7886             PyObject *r = Py%(type)s_GET_ITEM(o, Py%(type)s_GET_SIZE(o) + i);
7887             Py_INCREF(r);
7888             return r;
7889         }
7890     }
7891     return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
7892 }
7893 """ % {'type' : type_name} for type_name in ('List', 'Tuple')
7894 ]) + """
7895
7896 #define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7897                                                     __Pyx_GetItemInt_Fast(o, i) : \\
7898                                                     __Pyx_GetItemInt_Generic(o, to_py_func(i)))
7899
7900 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) {
7901     PyObject *r;
7902     if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
7903         r = PyList_GET_ITEM(o, i);
7904         Py_INCREF(r);
7905     }
7906     else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) {
7907         r = PyTuple_GET_ITEM(o, i);
7908         Py_INCREF(r);
7909     }
7910     else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) {
7911         r = PySequence_GetItem(o, i);
7912     }
7913     else {
7914         r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
7915     }
7916     return r;
7917 }
7918 """,
7919 impl = """
7920 """)
7921
7922
7923
7924 #------------------------------------------------------------------------------------
7925
7926 setitem_int_utility_code = UtilityCode(
7927 proto = """
7928 #define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7929                                                     __Pyx_SetItemInt_Fast(o, i, v) : \\
7930                                                     __Pyx_SetItemInt_Generic(o, to_py_func(i), v))
7931
7932 static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) {
7933     int r;
7934     if (!j) return -1;
7935     r = PyObject_SetItem(o, j, v);
7936     Py_DECREF(j);
7937     return r;
7938 }
7939
7940 static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) {
7941     if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
7942         Py_INCREF(v);
7943         Py_DECREF(PyList_GET_ITEM(o, i));
7944         PyList_SET_ITEM(o, i, v);
7945         return 1;
7946     }
7947     else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0)))
7948         return PySequence_SetItem(o, i, v);
7949     else {
7950         PyObject *j = PyInt_FromSsize_t(i);
7951         return __Pyx_SetItemInt_Generic(o, j, v);
7952     }
7953 }
7954 """,
7955 impl = """
7956 """)
7957
7958 #------------------------------------------------------------------------------------
7959
7960 delitem_int_utility_code = UtilityCode(
7961 proto = """
7962 #define __Pyx_DelItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7963                                                     __Pyx_DelItemInt_Fast(o, i) : \\
7964                                                     __Pyx_DelItem_Generic(o, to_py_func(i)))
7965
7966 static CYTHON_INLINE int __Pyx_DelItem_Generic(PyObject *o, PyObject *j) {
7967     int r;
7968     if (!j) return -1;
7969     r = PyObject_DelItem(o, j);
7970     Py_DECREF(j);
7971     return r;
7972 }
7973
7974 static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i) {
7975     if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && likely(i >= 0))
7976         return PySequence_DelItem(o, i);
7977     else {
7978         PyObject *j = PyInt_FromSsize_t(i);
7979         return __Pyx_DelItem_Generic(o, j);
7980     }
7981 }
7982 """,
7983 impl = """
7984 """)
7985
7986 #------------------------------------------------------------------------------------
7987
7988 raise_too_many_values_to_unpack = UtilityCode(
7989 proto = """
7990 static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected);
7991 """,
7992 impl = '''
7993 static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) {
7994     PyErr_Format(PyExc_ValueError,
7995         #if PY_VERSION_HEX < 0x02050000
7996             "too many values to unpack (expected %d)", (int)expected);
7997         #else
7998             "too many values to unpack (expected %zd)", expected);
7999         #endif
8000 }
8001 ''')
8002
8003 raise_need_more_values_to_unpack = UtilityCode(
8004 proto = """
8005 static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index);
8006 """,
8007 impl = '''
8008 static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) {
8009     PyErr_Format(PyExc_ValueError,
8010         #if PY_VERSION_HEX < 0x02050000
8011                  "need more than %d value%s to unpack", (int)index,
8012         #else
8013                  "need more than %zd value%s to unpack", index,
8014         #endif
8015                  (index == 1) ? "" : "s");
8016 }
8017 ''')
8018
8019 #------------------------------------------------------------------------------------
8020
8021 tuple_unpacking_error_code = UtilityCode(
8022 proto = """
8023 static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/
8024 """,
8025 impl = """
8026 static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) {
8027     if (t == Py_None) {
8028       __Pyx_RaiseNoneNotIterableError();
8029     } else if (PyTuple_GET_SIZE(t) < index) {
8030       __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t));
8031     } else {
8032       __Pyx_RaiseTooManyValuesError(index);
8033     }
8034 }
8035 """,
8036 requires = [raise_none_iter_error_utility_code,
8037             raise_need_more_values_to_unpack,
8038             raise_too_many_values_to_unpack]
8039 )
8040
8041 unpacking_utility_code = UtilityCode(
8042 proto = """
8043 static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/
8044 static int __Pyx_EndUnpack(PyObject *, Py_ssize_t expected); /*proto*/
8045 """,
8046 impl = """
8047 static PyObject *__Pyx_UnpackItem(PyObject *iter, Py_ssize_t index) {
8048     PyObject *item;
8049     if (!(item = PyIter_Next(iter))) {
8050         if (!PyErr_Occurred()) {
8051             __Pyx_RaiseNeedMoreValuesError(index);
8052         }
8053     }
8054     return item;
8055 }
8056
8057 static int __Pyx_EndUnpack(PyObject *iter, Py_ssize_t expected) {
8058     PyObject *item;
8059     if ((item = PyIter_Next(iter))) {
8060         Py_DECREF(item);
8061         __Pyx_RaiseTooManyValuesError(expected);
8062         return -1;
8063     }
8064     else if (!PyErr_Occurred())
8065         return 0;
8066     else
8067         return -1;
8068 }
8069 """,
8070 requires = [raise_need_more_values_to_unpack,
8071             raise_too_many_values_to_unpack]
8072 )
8073
8074 #------------------------------------------------------------------------------------
8075
8076 # CPython supports calling functions with non-dict kwargs by
8077 # converting them to a dict first
8078
8079 kwargs_call_utility_code = UtilityCode(
8080 proto = """
8081 static PyObject* __Pyx_PyEval_CallObjectWithKeywords(PyObject*, PyObject*, PyObject*); /*proto*/
8082 """,
8083 impl = """
8084 static PyObject* __Pyx_PyEval_CallObjectWithKeywords(PyObject *callable, PyObject *args, PyObject *kwargs) {
8085     PyObject* result;
8086     if (likely(PyDict_Check(kwargs))) {
8087         return PyEval_CallObjectWithKeywords(callable, args, kwargs);
8088     } else {
8089         PyObject* real_dict;
8090         real_dict = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, kwargs, NULL);
8091         if (unlikely(!real_dict))
8092             return NULL;
8093         result = PyEval_CallObjectWithKeywords(callable, args, real_dict);
8094         Py_DECREF(real_dict);
8095         return result; /* may be NULL */
8096     }
8097 }
8098 """,
8099 )
8100
8101
8102 #------------------------------------------------------------------------------------
8103
8104 int_pow_utility_code = UtilityCode(
8105 proto="""
8106 static CYTHON_INLINE %(type)s %(func_name)s(%(type)s, %(type)s); /* proto */
8107 """,
8108 impl="""
8109 static CYTHON_INLINE %(type)s %(func_name)s(%(type)s b, %(type)s e) {
8110     %(type)s t = b;
8111     switch (e) {
8112         case 3:
8113             t *= b;
8114         case 2:
8115             t *= b;
8116         case 1:
8117             return t;
8118         case 0:
8119             return 1;
8120     }
8121     if (unlikely(e<0)) return 0;
8122     t = 1;
8123     while (likely(e)) {
8124         t *= (b * (e&1)) | ((~e)&1);    /* 1 or b */
8125         b *= b;
8126         e >>= 1;
8127     }
8128     return t;
8129 }
8130 """)
8131
8132 # ------------------------------ Division ------------------------------------
8133
8134 div_int_utility_code = UtilityCode(
8135 proto="""
8136 static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s, %(type)s); /* proto */
8137 """,
8138 impl="""
8139 static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s a, %(type)s b) {
8140     %(type)s q = a / b;
8141     %(type)s r = a - q*b;
8142     q -= ((r != 0) & ((r ^ b) < 0));
8143     return q;
8144 }
8145 """)
8146
8147 mod_int_utility_code = UtilityCode(
8148 proto="""
8149 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
8150 """,
8151 impl="""
8152 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
8153     %(type)s r = a %% b;
8154     r += ((r != 0) & ((r ^ b) < 0)) * b;
8155     return r;
8156 }
8157 """)
8158
8159 mod_float_utility_code = UtilityCode(
8160 proto="""
8161 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
8162 """,
8163 impl="""
8164 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
8165     %(type)s r = fmod%(math_h_modifier)s(a, b);
8166     r += ((r != 0) & ((r < 0) ^ (b < 0))) * b;
8167     return r;
8168 }
8169 """)
8170
8171 cdivision_warning_utility_code = UtilityCode(
8172 proto="""
8173 static int __Pyx_cdivision_warning(void); /* proto */
8174 """,
8175 impl="""
8176 static int __Pyx_cdivision_warning(void) {
8177     return PyErr_WarnExplicit(PyExc_RuntimeWarning,
8178                               "division with oppositely signed operands, C and Python semantics differ",
8179                               %(FILENAME)s,
8180                               %(LINENO)s,
8181                               __Pyx_MODULE_NAME,
8182                               NULL);
8183 }
8184 """ % {
8185     'FILENAME': Naming.filename_cname,
8186     'LINENO':  Naming.lineno_cname,
8187 })
8188
8189 # from intobject.c
8190 division_overflow_test_code = UtilityCode(
8191 proto="""
8192 #define UNARY_NEG_WOULD_OVERFLOW(x)     \
8193         (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x)))
8194 """)
8195
8196
8197 binding_cfunc_utility_code = UtilityCode(
8198 proto="""
8199 #define %(binding_cfunc)s_USED 1
8200
8201 typedef struct {
8202     PyCFunctionObject func;
8203 } %(binding_cfunc)s_object;
8204
8205 static PyTypeObject %(binding_cfunc)s_type;
8206 static PyTypeObject *%(binding_cfunc)s = NULL;
8207
8208 static PyObject *%(binding_cfunc)s_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module); /* proto */
8209 #define %(binding_cfunc)s_New(ml, self) %(binding_cfunc)s_NewEx(ml, self, NULL)
8210
8211 static int %(binding_cfunc)s_init(void); /* proto */
8212 """ % Naming.__dict__,
8213 impl="""
8214
8215 static PyObject *%(binding_cfunc)s_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) {
8216         %(binding_cfunc)s_object *op = PyObject_GC_New(%(binding_cfunc)s_object, %(binding_cfunc)s);
8217     if (op == NULL)
8218         return NULL;
8219         op->func.m_ml = ml;
8220         Py_XINCREF(self);
8221         op->func.m_self = self;
8222         Py_XINCREF(module);
8223         op->func.m_module = module;
8224         PyObject_GC_Track(op);
8225         return (PyObject *)op;
8226 }
8227
8228 static void %(binding_cfunc)s_dealloc(%(binding_cfunc)s_object *m) {
8229         PyObject_GC_UnTrack(m);
8230         Py_XDECREF(m->func.m_self);
8231         Py_XDECREF(m->func.m_module);
8232     PyObject_GC_Del(m);
8233 }
8234
8235 static PyObject *%(binding_cfunc)s_descr_get(PyObject *func, PyObject *obj, PyObject *type) {
8236         if (obj == Py_None)
8237                 obj = NULL;
8238         return PyMethod_New(func, obj, type);
8239 }
8240
8241 static int %(binding_cfunc)s_init(void) {
8242     %(binding_cfunc)s_type = PyCFunction_Type;
8243     %(binding_cfunc)s_type.tp_name = __Pyx_NAMESTR("cython_binding_builtin_function_or_method");
8244     %(binding_cfunc)s_type.tp_dealloc = (destructor)%(binding_cfunc)s_dealloc;
8245     %(binding_cfunc)s_type.tp_descr_get = %(binding_cfunc)s_descr_get;
8246     if (PyType_Ready(&%(binding_cfunc)s_type) < 0) {
8247         return -1;
8248     }
8249     %(binding_cfunc)s = &%(binding_cfunc)s_type;
8250     return 0;
8251
8252 }
8253 """ % Naming.__dict__)