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