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