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