cleanup
[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
3936     def calculate_result_code(self):
3937         if len(self.args) > 0:
3938             error(self.pos, "Positive length tuples must be constructed.")
3939         else:
3940             return Naming.empty_tuple
3941
3942     def calculate_constant_result(self):
3943         self.constant_result = tuple([
3944                 arg.constant_result for arg in self.args])
3945
3946     def compile_time_value(self, denv):
3947         values = self.compile_time_value_list(denv)
3948         try:
3949             return tuple(values)
3950         except Exception, e:
3951             self.compile_time_value_error(e)
3952     
3953     def generate_operation_code(self, code):
3954         if len(self.args) == 0:
3955             # result_code is Naming.empty_tuple
3956             return
3957         code.putln(
3958             "%s = PyTuple_New(%s); %s" % (
3959                 self.result(),
3960                 len(self.args),
3961                 code.error_goto_if_null(self.result(), self.pos)))
3962         code.put_gotref(self.py_result())
3963         for i in range(len(self.args)):
3964             arg = self.args[i]
3965             if not arg.result_in_temp():
3966                 code.put_incref(arg.result(), arg.ctype())
3967             code.putln(
3968                 "PyTuple_SET_ITEM(%s, %s, %s);" % (
3969                     self.result(),
3970                     i,
3971                     arg.py_result()))
3972             code.put_giveref(arg.py_result())
3973     
3974     def generate_subexpr_disposal_code(self, code):
3975         # We call generate_post_assignment_code here instead
3976         # of generate_disposal_code, because values were stored
3977         # in the tuple using a reference-stealing operation.
3978         for arg in self.args:
3979             arg.generate_post_assignment_code(code)
3980             # Should NOT call free_temps -- this is invoked by the default
3981             # generate_evaluation_code which will do that.
3982
3983
3984 class ListNode(SequenceNode):
3985     #  List constructor.
3986     
3987     # obj_conversion_errors    [PyrexError]   used internally
3988     # orignial_args            [ExprNode]     used internally
3989
3990     obj_conversion_errors = []
3991     type = list_type
3992
3993     gil_message = "Constructing Python list"
3994     
3995     def type_dependencies(self, env):
3996         return ()
3997     
3998     def infer_type(self, env):
3999         # TOOD: Infer non-object list arrays.
4000         return list_type
4001
4002     def analyse_expressions(self, env):
4003         SequenceNode.analyse_expressions(self, env)
4004         self.coerce_to_pyobject(env)
4005
4006     def analyse_types(self, env):
4007         hold_errors()
4008         self.original_args = list(self.args)
4009         SequenceNode.analyse_types(self, env)
4010         self.obj_conversion_errors = held_errors()
4011         release_errors(ignore=True)
4012         
4013     def coerce_to(self, dst_type, env):
4014         if dst_type.is_pyobject:
4015             for err in self.obj_conversion_errors:
4016                 report_error(err)
4017             self.obj_conversion_errors = []
4018             if not self.type.subtype_of(dst_type):
4019                 error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
4020         elif dst_type.is_ptr:
4021             base_type = dst_type.base_type
4022             self.type = PyrexTypes.CArrayType(base_type, len(self.args))
4023             for i in range(len(self.original_args)):
4024                 arg = self.args[i]
4025                 if isinstance(arg, CoerceToPyTypeNode):
4026                     arg = arg.arg
4027                 self.args[i] = arg.coerce_to(base_type, env)
4028         elif dst_type.is_struct:
4029             if len(self.args) > len(dst_type.scope.var_entries):
4030                 error(self.pos, "Too may members for '%s'" % dst_type)
4031             else:
4032                 if len(self.args) < len(dst_type.scope.var_entries):
4033                     warning(self.pos, "Too few members for '%s'" % dst_type, 1)
4034                 for i, (arg, member) in enumerate(zip(self.original_args, dst_type.scope.var_entries)):
4035                     if isinstance(arg, CoerceToPyTypeNode):
4036                         arg = arg.arg
4037                     self.args[i] = arg.coerce_to(member.type, env)
4038             self.type = dst_type
4039         else:
4040             self.type = error_type
4041             error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
4042         return self
4043         
4044     def release_temp(self, env):
4045         if self.type.is_array:
4046             # To be valid C++, we must allocate the memory on the stack 
4047             # manually and be sure not to reuse it for something else. 
4048             pass
4049         else:
4050             SequenceNode.release_temp(self, env)
4051
4052     def calculate_constant_result(self):
4053         self.constant_result = [
4054             arg.constant_result for arg in self.args]
4055
4056     def compile_time_value(self, denv):
4057         return self.compile_time_value_list(denv)
4058
4059     def generate_operation_code(self, code):
4060         if self.type.is_pyobject:
4061             for err in self.obj_conversion_errors:
4062                 report_error(err)
4063             code.putln("%s = PyList_New(%s); %s" %
4064                 (self.result(),
4065                 len(self.args),
4066                 code.error_goto_if_null(self.result(), self.pos)))
4067             code.put_gotref(self.py_result())
4068             for i in range(len(self.args)):
4069                 arg = self.args[i]
4070                 #if not arg.is_temp:
4071                 if not arg.result_in_temp():
4072                     code.put_incref(arg.result(), arg.ctype())
4073                 code.putln("PyList_SET_ITEM(%s, %s, %s);" %
4074                     (self.result(),
4075                     i,
4076                     arg.py_result()))
4077                 code.put_giveref(arg.py_result())
4078         elif self.type.is_array:
4079             for i, arg in enumerate(self.args):
4080                 code.putln("%s[%s] = %s;" % (
4081                                 self.result(),
4082                                 i,
4083                                 arg.result()))
4084         elif self.type.is_struct:
4085             for arg, member in zip(self.args, self.type.scope.var_entries):
4086                 code.putln("%s.%s = %s;" % (
4087                         self.result(),
4088                         member.cname,
4089                         arg.result()))
4090         else:
4091             raise InternalError("List type never specified")
4092
4093     def generate_subexpr_disposal_code(self, code):
4094         # We call generate_post_assignment_code here instead
4095         # of generate_disposal_code, because values were stored
4096         # in the list using a reference-stealing operation.
4097         for arg in self.args:
4098             arg.generate_post_assignment_code(code)
4099             # Should NOT call free_temps -- this is invoked by the default
4100             # generate_evaluation_code which will do that.
4101
4102
4103 class ScopedExprNode(ExprNode):
4104     # Abstract base class for ExprNodes that have their own local
4105     # scope, such as generator expressions.
4106     #
4107     # expr_scope    Scope  the inner scope of the expression
4108
4109     subexprs = []
4110     expr_scope = None
4111
4112     def analyse_types(self, env):
4113         # nothing to do here, the children will be analysed separately
4114         pass
4115
4116     def analyse_expressions(self, env):
4117         # nothing to do here, the children will be analysed separately
4118         pass
4119
4120     def analyse_scoped_expressions(self, env):
4121         # this is called with the expr_scope as env
4122         pass
4123
4124     def init_scope(self, outer_scope, expr_scope=None):
4125         self.expr_scope = expr_scope
4126
4127
4128 class ComprehensionNode(ScopedExprNode):
4129     subexprs = ["target"]
4130     child_attrs = ["loop", "append"]
4131
4132     # leak loop variables or not?  non-leaking Py3 behaviour is
4133     # default, except for list comprehensions where the behaviour
4134     # differs in Py2 and Py3 (see Parsing.py)
4135     has_local_scope = True
4136
4137     def infer_type(self, env):
4138         return self.target.infer_type(env)
4139
4140     def analyse_declarations(self, env):
4141         self.append.target = self # this is used in the PyList_Append of the inner loop
4142         self.init_scope(env)
4143         self.loop.analyse_declarations(self.expr_scope or env)
4144
4145     def init_scope(self, outer_scope, expr_scope=None):
4146         if expr_scope is not None:
4147             self.expr_scope = expr_scope
4148         elif self.has_local_scope:
4149             self.expr_scope = Symtab.GeneratorExpressionScope(outer_scope)
4150         else:
4151             self.expr_scope = None
4152
4153     def analyse_types(self, env):
4154         self.target.analyse_expressions(env)
4155         self.type = self.target.type
4156         if not self.has_local_scope:
4157             self.loop.analyse_expressions(env)
4158
4159     def analyse_expressions(self, env):
4160         self.analyse_types(env)
4161
4162     def analyse_scoped_expressions(self, env):
4163         if self.has_local_scope:
4164             self.loop.analyse_expressions(env)
4165
4166     def may_be_none(self):
4167         return False
4168
4169     def calculate_result_code(self):
4170         return self.target.result()
4171     
4172     def generate_result_code(self, code):
4173         self.generate_operation_code(code)
4174
4175     def generate_operation_code(self, code):
4176         self.loop.generate_execution_code(code)
4177
4178     def annotate(self, code):
4179         self.loop.annotate(code)
4180
4181
4182 class ComprehensionAppendNode(Node):
4183     # Need to be careful to avoid infinite recursion:
4184     # target must not be in child_attrs/subexprs
4185
4186     child_attrs = ['expr']
4187
4188     type = PyrexTypes.c_int_type
4189     
4190     def analyse_expressions(self, env):
4191         self.expr.analyse_expressions(env)
4192         if not self.expr.type.is_pyobject:
4193             self.expr = self.expr.coerce_to_pyobject(env)
4194
4195     def generate_execution_code(self, code):
4196         if self.target.type is list_type:
4197             function = "PyList_Append"
4198         elif self.target.type is set_type:
4199             function = "PySet_Add"
4200         else:
4201             raise InternalError(
4202                 "Invalid type for comprehension node: %s" % self.target.type)
4203
4204         self.expr.generate_evaluation_code(code)
4205         code.putln(code.error_goto_if("%s(%s, (PyObject*)%s)" % (
4206             function,
4207             self.target.result(),
4208             self.expr.result()
4209             ), self.pos))
4210         self.expr.generate_disposal_code(code)
4211         self.expr.free_temps(code)
4212
4213     def generate_function_definitions(self, env, code):
4214         self.expr.generate_function_definitions(env, code)
4215
4216     def annotate(self, code):
4217         self.expr.annotate(code)
4218
4219 class DictComprehensionAppendNode(ComprehensionAppendNode):
4220     child_attrs = ['key_expr', 'value_expr']
4221
4222     def analyse_expressions(self, env):
4223         self.key_expr.analyse_expressions(env)
4224         if not self.key_expr.type.is_pyobject:
4225             self.key_expr = self.key_expr.coerce_to_pyobject(env)
4226         self.value_expr.analyse_expressions(env)
4227         if not self.value_expr.type.is_pyobject:
4228             self.value_expr = self.value_expr.coerce_to_pyobject(env)
4229
4230     def generate_execution_code(self, code):
4231         self.key_expr.generate_evaluation_code(code)
4232         self.value_expr.generate_evaluation_code(code)
4233         code.putln(code.error_goto_if("PyDict_SetItem(%s, (PyObject*)%s, (PyObject*)%s)" % (
4234             self.target.result(),
4235             self.key_expr.result(),
4236             self.value_expr.result()
4237             ), self.pos))
4238         self.key_expr.generate_disposal_code(code)
4239         self.key_expr.free_temps(code)
4240         self.value_expr.generate_disposal_code(code)
4241         self.value_expr.free_temps(code)
4242
4243     def generate_function_definitions(self, env, code):
4244         self.key_expr.generate_function_definitions(env, code)
4245         self.value_expr.generate_function_definitions(env, code)
4246
4247     def annotate(self, code):
4248         self.key_expr.annotate(code)
4249         self.value_expr.annotate(code)
4250
4251
4252 class GeneratorExpressionNode(ScopedExprNode):
4253     # A generator expression, e.g.  (i for i in range(10))
4254     #
4255     # Result is a generator.
4256     #
4257     # loop      ForStatNode   the for-loop, containing a YieldExprNode
4258
4259     child_attrs = ["loop"]
4260
4261     type = py_object_type
4262
4263     def analyse_declarations(self, env):
4264         self.init_scope(env)
4265         self.loop.analyse_declarations(self.expr_scope)
4266
4267     def init_scope(self, outer_scope, expr_scope=None):
4268         if expr_scope is not None:
4269             self.expr_scope = expr_scope
4270         else:
4271             self.expr_scope = Symtab.GeneratorExpressionScope(outer_scope)
4272
4273     def analyse_types(self, env):
4274         self.is_temp = True
4275
4276     def analyse_scoped_expressions(self, env):
4277         self.loop.analyse_expressions(env)
4278
4279     def may_be_none(self):
4280         return False
4281
4282     def annotate(self, code):
4283         self.loop.annotate(code)
4284
4285
4286 class InlinedGeneratorExpressionNode(GeneratorExpressionNode):
4287     # An inlined generator expression for which the result is
4288     # calculated inside of the loop.  This will only be created by
4289     # transforms when replacing builtin calls on generator
4290     # expressions.
4291     #
4292     # loop           ForStatNode      the for-loop, not containing any YieldExprNodes
4293     # result_node    ResultRefNode    the reference to the result value temp
4294     # orig_func      String           the name of the builtin function this node replaces
4295
4296     child_attrs = ["loop"]
4297
4298     def analyse_types(self, env):
4299         self.type = self.result_node.type
4300         self.is_temp = True
4301
4302     def coerce_to(self, dst_type, env):
4303         if self.orig_func == 'sum' and dst_type.is_numeric:
4304             # we can optimise by dropping the aggregation variable into C
4305             self.result_node.type = self.type = dst_type
4306             return self
4307         return GeneratorExpressionNode.coerce_to(self, dst_type, env)
4308
4309     def generate_result_code(self, code):
4310         self.result_node.result_code = self.result()
4311         self.loop.generate_execution_code(code)
4312
4313
4314 class SetNode(ExprNode):
4315     #  Set constructor.
4316
4317     type = set_type
4318
4319     subexprs = ['args']
4320
4321     gil_message = "Constructing Python set"
4322     
4323     def analyse_types(self, env):
4324         for i in range(len(self.args)):
4325             arg = self.args[i]
4326             arg.analyse_types(env)
4327             self.args[i] = arg.coerce_to_pyobject(env)
4328         self.type = set_type
4329         self.is_temp = 1
4330
4331     def may_be_none(self):
4332         return False
4333
4334     def calculate_constant_result(self):
4335         self.constant_result = set([
4336                 arg.constant_result for arg in self.args])
4337
4338     def compile_time_value(self, denv):
4339         values = [arg.compile_time_value(denv) for arg in self.args]
4340         try:
4341             return set(values)
4342         except Exception, e:
4343             self.compile_time_value_error(e)
4344
4345     def generate_evaluation_code(self, code):
4346         code.globalstate.use_utility_code(Builtin.py23_set_utility_code)
4347         self.allocate_temp_result(code)
4348         code.putln(
4349             "%s = PySet_New(0); %s" % (
4350                 self.result(),
4351                 code.error_goto_if_null(self.result(), self.pos)))
4352         code.put_gotref(self.py_result())
4353         for arg in self.args:
4354             arg.generate_evaluation_code(code)
4355             code.putln(
4356                 code.error_goto_if_neg(
4357                     "PySet_Add(%s, %s)" % (self.result(), arg.py_result()),
4358                     self.pos))
4359             arg.generate_disposal_code(code)
4360             arg.free_temps(code)
4361
4362
4363 class DictNode(ExprNode):
4364     #  Dictionary constructor.
4365     #
4366     #  key_value_pairs  [DictItemNode]
4367     #
4368     # obj_conversion_errors    [PyrexError]   used internally
4369     
4370     subexprs = ['key_value_pairs']
4371     is_temp = 1
4372     type = dict_type
4373
4374     obj_conversion_errors = []
4375
4376     def calculate_constant_result(self):
4377         self.constant_result = dict([
4378                 item.constant_result for item in self.key_value_pairs])
4379     
4380     def compile_time_value(self, denv):
4381         pairs = [(item.key.compile_time_value(denv), item.value.compile_time_value(denv))
4382             for item in self.key_value_pairs]
4383         try:
4384             return dict(pairs)
4385         except Exception, e:
4386             self.compile_time_value_error(e)
4387     
4388     def type_dependencies(self, env):
4389         return ()
4390     
4391     def infer_type(self, env):
4392         # TOOD: Infer struct constructors.
4393         return dict_type
4394
4395     def analyse_types(self, env):
4396         hold_errors()
4397         for item in self.key_value_pairs:
4398             item.analyse_types(env)
4399         self.obj_conversion_errors = held_errors()
4400         release_errors(ignore=True)
4401
4402     def may_be_none(self):
4403         return False
4404         
4405     def coerce_to(self, dst_type, env):
4406         if dst_type.is_pyobject:
4407             self.release_errors()
4408             if not self.type.subtype_of(dst_type):
4409                 error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
4410         elif dst_type.is_struct_or_union:
4411             self.type = dst_type
4412             if not dst_type.is_struct and len(self.key_value_pairs) != 1:
4413                 error(self.pos, "Exactly one field must be specified to convert to union '%s'" % dst_type)
4414             elif dst_type.is_struct and len(self.key_value_pairs) < len(dst_type.scope.var_entries):
4415                 warning(self.pos, "Not all members given for struct '%s'" % dst_type, 1)
4416             for item in self.key_value_pairs:
4417                 if isinstance(item.key, CoerceToPyTypeNode):
4418                     item.key = item.key.arg
4419                 if not isinstance(item.key, (UnicodeNode, StringNode, BytesNode)):
4420                     error(item.key.pos, "Invalid struct field identifier")
4421                     item.key = StringNode(item.key.pos, value="<error>")
4422                 else:
4423                     key = str(item.key.value) # converts string literals to unicode in Py3
4424                     member = dst_type.scope.lookup_here(key)
4425                     if not member:
4426                         error(item.key.pos, "struct '%s' has no field '%s'" % (dst_type, key))
4427                     else:
4428                         value = item.value
4429                         if isinstance(value, CoerceToPyTypeNode):
4430                             value = value.arg
4431                         item.value = value.coerce_to(member.type, env)
4432         else:
4433             self.type = error_type
4434             error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
4435         return self
4436     
4437     def release_errors(self):
4438         for err in self.obj_conversion_errors:
4439             report_error(err)
4440         self.obj_conversion_errors = []
4441
4442     gil_message = "Constructing Python dict"
4443
4444     def generate_evaluation_code(self, code):
4445         #  Custom method used here because key-value
4446         #  pairs are evaluated and used one at a time.
4447         code.mark_pos(self.pos)
4448         self.allocate_temp_result(code)
4449         if self.type.is_pyobject:
4450             self.release_errors()
4451             code.putln(
4452                 "%s = PyDict_New(); %s" % (
4453                     self.result(),
4454                     code.error_goto_if_null(self.result(), self.pos)))
4455             code.put_gotref(self.py_result())
4456         for item in self.key_value_pairs:
4457             item.generate_evaluation_code(code)
4458             if self.type.is_pyobject:
4459                 code.put_error_if_neg(self.pos, 
4460                     "PyDict_SetItem(%s, %s, %s)" % (
4461                         self.result(),
4462                         item.key.py_result(),
4463                         item.value.py_result()))
4464             else:
4465                 code.putln("%s.%s = %s;" % (
4466                         self.result(),
4467                         item.key.value,
4468                         item.value.result()))
4469             item.generate_disposal_code(code)
4470             item.free_temps(code)
4471             
4472     def annotate(self, code):
4473         for item in self.key_value_pairs:
4474             item.annotate(code)
4475             
4476 class DictItemNode(ExprNode):
4477     # Represents a single item in a DictNode
4478     #
4479     # key          ExprNode
4480     # value        ExprNode
4481     subexprs = ['key', 'value']
4482
4483     nogil_check = None # Parent DictNode takes care of it
4484
4485     def calculate_constant_result(self):
4486         self.constant_result = (
4487             self.key.constant_result, self.value.constant_result)
4488             
4489     def analyse_types(self, env):
4490         self.key.analyse_types(env)
4491         self.value.analyse_types(env)
4492         self.key = self.key.coerce_to_pyobject(env)
4493         self.value = self.value.coerce_to_pyobject(env)
4494         
4495     def generate_evaluation_code(self, code):
4496         self.key.generate_evaluation_code(code)
4497         self.value.generate_evaluation_code(code)
4498
4499     def generate_disposal_code(self, code):
4500         self.key.generate_disposal_code(code)
4501         self.value.generate_disposal_code(code)
4502
4503     def free_temps(self, code):
4504         self.key.free_temps(code)
4505         self.value.free_temps(code)
4506         
4507     def __iter__(self):
4508         return iter([self.key, self.value])
4509
4510 class ModuleNameMixin(object):
4511     def set_mod_name(self, env):
4512         self.module_name = env.global_scope().qualified_name
4513
4514     def get_py_mod_name(self, code):
4515         return code.get_py_string_const(
4516                  self.module_name, identifier=True)
4517
4518 class ClassNode(ExprNode, ModuleNameMixin):
4519     #  Helper class used in the implementation of Python
4520     #  class definitions. Constructs a class object given
4521     #  a name, tuple of bases and class dictionary.
4522     #
4523     #  name         EncodedString      Name of the class
4524     #  bases        ExprNode           Base class tuple
4525     #  dict         ExprNode           Class dict (not owned by this node)
4526     #  doc          ExprNode or None   Doc string
4527     #  module_name  EncodedString      Name of defining module
4528     #  keyword_args ExprNode or None   Py3 Dict of keyword arguments, passed to __new__
4529     #  starstar_arg ExprNode or None   Py3 Dict of extra keyword args, same here
4530     
4531     subexprs = ['bases', 'keyword_args', 'starstar_arg', 'doc']
4532
4533     def analyse_types(self, env):
4534         self.bases.analyse_types(env)
4535         if self.doc:
4536             self.doc.analyse_types(env)
4537             self.doc = self.doc.coerce_to_pyobject(env)
4538         if self.keyword_args:
4539             self.keyword_args.analyse_types(env)
4540         if self.starstar_arg:
4541             self.starstar_arg.analyse_types(env)
4542             # make sure we have a Python object as **kwargs mapping
4543             self.starstar_arg = \
4544                 self.starstar_arg.coerce_to_pyobject(env)
4545         self.type = py_object_type
4546         self.is_temp = 1
4547         env.use_utility_code(create_class_utility_code);
4548         #TODO(craig,haoyu) This should be moved to a better place
4549         self.set_mod_name(env)
4550
4551     def may_be_none(self):
4552         return True
4553
4554     gil_message = "Constructing Python class"
4555
4556     def generate_result_code(self, code):
4557         cname = code.intern_identifier(self.name)
4558         if self.keyword_args and self.starstar_arg:
4559             code.put_error_if_neg(self.pos,
4560                 "PyDict_Update(%s, %s)" % (
4561                     self.keyword_args.py_result(),
4562                     self.starstar_arg.py_result()))
4563             keyword_code = self.keyword_args.py_result()
4564         elif self.keyword_args:
4565             keyword_code = self.keyword_args.py_result()
4566         elif self.starstar_arg:
4567             keyword_code = self.starstar_arg.py_result()
4568         else:
4569             keyword_code = 'NULL'
4570
4571         if self.doc:
4572             code.put_error_if_neg(self.pos, 
4573                 'PyDict_SetItemString(%s, "__doc__", %s)' % (
4574                     self.dict.py_result(),
4575                     self.doc.py_result()))
4576         py_mod_name = self.get_py_mod_name(code)
4577         code.putln(
4578             '%s = __Pyx_CreateClass(%s, %s, %s, %s, %s); %s' % (
4579                 self.result(),
4580                 self.bases.py_result(),
4581                 self.dict.py_result(),
4582                 cname,
4583                 py_mod_name,
4584                 keyword_code,
4585                 code.error_goto_if_null(self.result(), self.pos)))
4586         code.put_gotref(self.py_result())
4587
4588
4589 class BoundMethodNode(ExprNode):
4590     #  Helper class used in the implementation of Python
4591     #  class definitions. Constructs an bound method
4592     #  object from a class and a function.
4593     #
4594     #  function      ExprNode   Function object
4595     #  self_object   ExprNode   self object
4596     
4597     subexprs = ['function']
4598     
4599     def analyse_types(self, env):
4600         self.function.analyse_types(env)
4601         self.type = py_object_type
4602         self.is_temp = 1
4603
4604     gil_message = "Constructing an bound method"
4605
4606     def generate_result_code(self, code):
4607         code.putln(
4608             "%s = PyMethod_New(%s, %s, (PyObject*)%s->ob_type); %s" % (
4609                 self.result(),
4610                 self.function.py_result(),
4611                 self.self_object.py_result(),
4612                 self.self_object.py_result(),
4613                 code.error_goto_if_null(self.result(), self.pos)))
4614         code.put_gotref(self.py_result())
4615
4616 class UnboundMethodNode(ExprNode):
4617     #  Helper class used in the implementation of Python
4618     #  class definitions. Constructs an unbound method
4619     #  object from a class and a function.
4620     #
4621     #  function      ExprNode   Function object
4622     
4623     type = py_object_type
4624     is_temp = 1
4625     
4626     subexprs = ['function']
4627     
4628     def analyse_types(self, env):
4629         self.function.analyse_types(env)
4630
4631     def may_be_none(self):
4632         return False
4633
4634     gil_message = "Constructing an unbound method"
4635
4636     def generate_result_code(self, code):
4637         class_cname = code.pyclass_stack[-1].classobj.result()
4638         code.putln(
4639             "%s = PyMethod_New(%s, 0, %s); %s" % (
4640                 self.result(),
4641                 self.function.py_result(),
4642                 class_cname,
4643                 code.error_goto_if_null(self.result(), self.pos)))
4644         code.put_gotref(self.py_result())
4645
4646
4647 class PyCFunctionNode(ExprNode, ModuleNameMixin):
4648     #  Helper class used in the implementation of Python
4649     #  class definitions. Constructs a PyCFunction object
4650     #  from a PyMethodDef struct.
4651     #
4652     #  pymethdef_cname   string             PyMethodDef structure
4653     #  self_object       ExprNode or None
4654     #  binding           bool
4655     #  module_name       EncodedString      Name of defining module
4656
4657     subexprs = []
4658     self_object = None
4659     binding = False
4660     
4661     type = py_object_type
4662     is_temp = 1
4663     
4664     def analyse_types(self, env):
4665         if self.binding:
4666             env.use_utility_code(binding_cfunc_utility_code)
4667
4668         #TODO(craig,haoyu) This should be moved to a better place
4669         self.set_mod_name(env)
4670
4671     def may_be_none(self):
4672         return False
4673     
4674     gil_message = "Constructing Python function"
4675
4676     def self_result_code(self):
4677         if self.self_object is None:
4678             self_result = "NULL"
4679         else:
4680             self_result = self.self_object.py_result()
4681         return self_result
4682
4683     def generate_result_code(self, code):
4684         if self.binding:
4685             constructor = "%s_NewEx" % Naming.binding_cfunc
4686         else:
4687             constructor = "PyCFunction_NewEx"
4688         py_mod_name = self.get_py_mod_name(code)
4689         code.putln(
4690             '%s = %s(&%s, %s, %s); %s' % (
4691                 self.result(),
4692                 constructor,
4693                 self.pymethdef_cname,
4694                 self.self_result_code(),
4695                 py_mod_name,
4696                 code.error_goto_if_null(self.result(), self.pos)))
4697         code.put_gotref(self.py_result())
4698
4699 class InnerFunctionNode(PyCFunctionNode):
4700     # Special PyCFunctionNode that depends on a closure class
4701     #
4702     binding = True
4703     
4704     def self_result_code(self):
4705         return "((PyObject*)%s)" % Naming.cur_scope_cname
4706
4707 class LambdaNode(InnerFunctionNode):
4708     # Lambda expression node (only used as a function reference)
4709     #
4710     # args          [CArgDeclNode]         formal arguments
4711     # star_arg      PyArgDeclNode or None  * argument
4712     # starstar_arg  PyArgDeclNode or None  ** argument
4713     # lambda_name   string                 a module-globally unique lambda name
4714     # result_expr   ExprNode
4715     # def_node      DefNode                the underlying function 'def' node
4716
4717     child_attrs = ['def_node']
4718
4719     def_node = None
4720     name = StringEncoding.EncodedString('<lambda>')
4721
4722     def analyse_declarations(self, env):
4723         #self.def_node.needs_closure = self.needs_closure
4724         self.def_node.analyse_declarations(env)
4725         self.pymethdef_cname = self.def_node.entry.pymethdef_cname
4726         env.add_lambda_def(self.def_node)
4727
4728 class YieldExprNode(ExprNode):
4729     # Yield expression node
4730     #
4731     # arg         ExprNode   the value to return from the generator
4732     # label_name  string     name of the C label used for this yield
4733
4734     subexprs = ['arg']
4735     type = py_object_type
4736
4737     def analyse_types(self, env):
4738         self.is_temp = 1
4739         if self.arg is not None:
4740             self.arg.analyse_types(env)
4741             if not self.arg.type.is_pyobject:
4742                 self.arg = self.arg.coerce_to_pyobject(env)
4743         error(self.pos, "Generators are not supported")
4744
4745     def generate_result_code(self, code):
4746         self.label_name = code.new_label('resume_from_yield')
4747         code.use_label(self.label_name)
4748         code.putln("/* FIXME: save temporary variables */")
4749         code.putln("/* FIXME: return from function, yielding value */")
4750         code.put_label(self.label_name)
4751         code.putln("/* FIXME: restore temporary variables and  */")
4752         code.putln("/* FIXME: extract sent value from closure */")
4753
4754
4755 #-------------------------------------------------------------------
4756 #
4757 #  Unary operator nodes
4758 #
4759 #-------------------------------------------------------------------
4760
4761 compile_time_unary_operators = {
4762     'not': operator.not_,
4763     '~': operator.inv,
4764     '-': operator.neg,
4765     '+': operator.pos,
4766 }
4767
4768 class UnopNode(ExprNode):
4769     #  operator     string
4770     #  operand      ExprNode
4771     #
4772     #  Processing during analyse_expressions phase:
4773     #
4774     #    analyse_c_operation
4775     #      Called when the operand is not a pyobject.
4776     #      - Check operand type and coerce if needed.
4777     #      - Determine result type and result code fragment.
4778     #      - Allocate temporary for result if needed.
4779     
4780     subexprs = ['operand']
4781     infix = True
4782
4783     def calculate_constant_result(self):
4784         func = compile_time_unary_operators[self.operator]
4785         self.constant_result = func(self.operand.constant_result)
4786     
4787     def compile_time_value(self, denv):
4788         func = compile_time_unary_operators.get(self.operator)
4789         if not func:
4790             error(self.pos,
4791                 "Unary '%s' not supported in compile-time expression"
4792                     % self.operator)
4793         operand = self.operand.compile_time_value(denv)
4794         try:
4795             return func(operand)
4796         except Exception, e:
4797             self.compile_time_value_error(e)
4798     
4799     def infer_type(self, env):
4800         operand_type = self.operand.infer_type(env)
4801         if operand_type.is_pyobject:
4802             return py_object_type
4803         else:
4804             return operand_type
4805
4806     def analyse_types(self, env):
4807         self.operand.analyse_types(env)
4808         if self.is_py_operation():
4809             self.coerce_operand_to_pyobject(env)
4810             self.type = py_object_type
4811             self.is_temp = 1
4812         elif self.is_cpp_operation():
4813             self.analyse_cpp_operation(env)
4814         else:
4815             self.analyse_c_operation(env)
4816     
4817     def check_const(self):
4818         return self.operand.check_const()
4819     
4820     def is_py_operation(self):
4821         return self.operand.type.is_pyobject
4822
4823     def nogil_check(self, env):
4824         if self.is_py_operation():
4825             self.gil_error()
4826
4827     def is_cpp_operation(self):
4828         type = self.operand.type
4829         return type.is_cpp_class
4830     
4831     def coerce_operand_to_pyobject(self, env):
4832         self.operand = self.operand.coerce_to_pyobject(env)
4833     
4834     def generate_result_code(self, code):
4835         if self.operand.type.is_pyobject:
4836             self.generate_py_operation_code(code)
4837     
4838     def generate_py_operation_code(self, code):
4839         function = self.py_operation_function()
4840         code.putln(
4841             "%s = %s(%s); %s" % (
4842                 self.result(), 
4843                 function, 
4844                 self.operand.py_result(),
4845                 code.error_goto_if_null(self.result(), self.pos)))
4846         code.put_gotref(self.py_result())
4847         
4848     def type_error(self):
4849         if not self.operand.type.is_error:
4850             error(self.pos, "Invalid operand type for '%s' (%s)" %
4851                 (self.operator, self.operand.type))
4852         self.type = PyrexTypes.error_type
4853
4854     def analyse_cpp_operation(self, env):
4855         type = self.operand.type
4856         if type.is_ptr:
4857             type = type.base_type
4858         function = type.scope.lookup("operator%s" % self.operator)
4859         if not function:
4860             error(self.pos, "'%s' operator not defined for %s"
4861                 % (self.operator, type))
4862             self.type_error()
4863             return
4864         func_type = function.type
4865         if func_type.is_ptr:
4866             func_type = func_type.base_type
4867         self.type = func_type.return_type
4868
4869
4870 class NotNode(ExprNode):
4871     #  'not' operator
4872     #
4873     #  operand   ExprNode
4874     
4875     type = PyrexTypes.c_bint_type
4876
4877     subexprs = ['operand']
4878     
4879     def calculate_constant_result(self):
4880         self.constant_result = not self.operand.constant_result
4881
4882     def compile_time_value(self, denv):
4883         operand = self.operand.compile_time_value(denv)
4884         try:
4885             return not operand
4886         except Exception, e:
4887             self.compile_time_value_error(e)
4888
4889     def infer_type(self, env):
4890         return PyrexTypes.c_bint_type
4891     
4892     def analyse_types(self, env):
4893         self.operand.analyse_types(env)
4894         self.operand = self.operand.coerce_to_boolean(env)
4895     
4896     def calculate_result_code(self):
4897         return "(!%s)" % self.operand.result()
4898     
4899     def generate_result_code(self, code):
4900         pass
4901
4902
4903 class UnaryPlusNode(UnopNode):
4904     #  unary '+' operator
4905     
4906     operator = '+'
4907     
4908     def analyse_c_operation(self, env):
4909         self.type = self.operand.type
4910     
4911     def py_operation_function(self):
4912         return "PyNumber_Positive"
4913     
4914     def calculate_result_code(self):
4915         if self.is_cpp_operation():
4916             return "(+%s)" % self.operand.result()
4917         else:
4918             return self.operand.result()
4919
4920
4921 class UnaryMinusNode(UnopNode):
4922     #  unary '-' operator
4923     
4924     operator = '-'
4925     
4926     def analyse_c_operation(self, env):
4927         if self.operand.type.is_numeric:
4928             self.type = self.operand.type
4929         else:
4930             self.type_error()
4931         if self.type.is_complex:
4932             self.infix = False
4933     
4934     def py_operation_function(self):
4935         return "PyNumber_Negative"
4936     
4937     def calculate_result_code(self):
4938         if self.infix:
4939             return "(-%s)" % self.operand.result()
4940         else:
4941             return "%s(%s)" % (self.operand.type.unary_op('-'), self.operand.result())
4942
4943     def get_constant_c_result_code(self):
4944         value = self.operand.get_constant_c_result_code()
4945         if value:
4946             return "(-%s)" % (value)
4947
4948 class TildeNode(UnopNode):
4949     #  unary '~' operator
4950
4951     def analyse_c_operation(self, env):
4952         if self.operand.type.is_int:
4953             self.type = self.operand.type
4954         else:
4955             self.type_error()
4956
4957     def py_operation_function(self):
4958         return "PyNumber_Invert"
4959     
4960     def calculate_result_code(self):
4961         return "(~%s)" % self.operand.result()
4962
4963
4964 class CUnopNode(UnopNode):
4965
4966     def is_py_operation(self):
4967         return False
4968
4969 class DereferenceNode(CUnopNode):
4970     #  unary * operator
4971
4972     operator = '*'
4973     
4974     def analyse_c_operation(self, env):
4975         if self.operand.type.is_ptr:
4976             self.type = self.operand.type.base_type
4977         else:
4978             self.type_error()
4979
4980     def calculate_result_code(self):
4981         return "(*%s)" % self.operand.result()
4982
4983
4984 class DecrementIncrementNode(CUnopNode):
4985     #  unary ++/-- operator
4986     
4987     def analyse_c_operation(self, env):
4988         if self.operand.type.is_ptr or self.operand.type.is_numeric:
4989             self.type = self.operand.type
4990         else:
4991             self.type_error()
4992
4993     def calculate_result_code(self):
4994         if self.is_prefix:
4995             return "(%s%s)" % (self.operator, self.operand.result())
4996         else:
4997             return "(%s%s)" % (self.operand.result(), self.operator)
4998
4999 def inc_dec_constructor(is_prefix, operator):
5000     return lambda pos, **kwds: DecrementIncrementNode(pos, is_prefix=is_prefix, operator=operator, **kwds)
5001
5002
5003 class AmpersandNode(ExprNode):
5004     #  The C address-of operator.
5005     #
5006     #  operand  ExprNode
5007     
5008     subexprs = ['operand']
5009     
5010     def infer_type(self, env):
5011         return PyrexTypes.c_ptr_type(self.operand.infer_type(env))
5012
5013     def analyse_types(self, env):
5014         self.operand.analyse_types(env)
5015         argtype = self.operand.type
5016         if not (argtype.is_cfunction or self.operand.is_lvalue()):
5017             self.error("Taking address of non-lvalue")
5018             return
5019         if argtype.is_pyobject:
5020             self.error("Cannot take address of Python variable")
5021             return
5022         self.type = PyrexTypes.c_ptr_type(argtype)
5023     
5024     def check_const(self):
5025         return self.operand.check_const_addr()
5026     
5027     def error(self, mess):
5028         error(self.pos, mess)
5029         self.type = PyrexTypes.error_type
5030         self.result_code = "<error>"
5031     
5032     def calculate_result_code(self):
5033         return "(&%s)" % self.operand.result()
5034
5035     def generate_result_code(self, code):
5036         pass
5037     
5038
5039 unop_node_classes = {
5040     "+":  UnaryPlusNode,
5041     "-":  UnaryMinusNode,
5042     "~":  TildeNode,
5043 }
5044
5045 def unop_node(pos, operator, operand):
5046     # Construct unnop node of appropriate class for 
5047     # given operator.
5048     if isinstance(operand, IntNode) and operator == '-':
5049         return IntNode(pos = operand.pos, value = str(-Utils.str_to_number(operand.value)))
5050     elif isinstance(operand, UnopNode) and operand.operator == operator:
5051         warning(pos, "Python has no increment/decrement operator: %s%sx = %s(%sx) = x" % ((operator,)*4), 5)
5052     return unop_node_classes[operator](pos, 
5053         operator = operator, 
5054         operand = operand)
5055
5056
5057 class TypecastNode(ExprNode):
5058     #  C type cast
5059     #
5060     #  operand      ExprNode
5061     #  base_type    CBaseTypeNode
5062     #  declarator   CDeclaratorNode
5063     #
5064     #  If used from a transform, one can if wanted specify the attribute
5065     #  "type" directly and leave base_type and declarator to None
5066     
5067     subexprs = ['operand']
5068     base_type = declarator = type = None
5069     
5070     def type_dependencies(self, env):
5071         return ()
5072     
5073     def infer_type(self, env):
5074         if self.type is None:
5075             base_type = self.base_type.analyse(env)
5076             _, self.type = self.declarator.analyse(base_type, env)
5077         return self.type
5078     
5079     def analyse_types(self, env):
5080         if self.type is None:
5081             base_type = self.base_type.analyse(env)
5082             _, self.type = self.declarator.analyse(base_type, env)
5083         if self.type.is_cfunction:
5084             error(self.pos,
5085                 "Cannot cast to a function type")
5086             self.type = PyrexTypes.error_type
5087         self.operand.analyse_types(env)
5088         to_py = self.type.is_pyobject
5089         from_py = self.operand.type.is_pyobject
5090         if from_py and not to_py and self.operand.is_ephemeral() and not self.type.is_numeric:
5091             error(self.pos, "Casting temporary Python object to non-numeric non-Python type")
5092         if to_py and not from_py:
5093             if self.type is bytes_type and self.operand.type.is_int:
5094                 # FIXME: the type cast node isn't needed in this case
5095                 # and can be dropped once analyse_types() can return a
5096                 # different node
5097                 self.operand = CoerceIntToBytesNode(self.operand, env)
5098             elif self.operand.type.can_coerce_to_pyobject(env):
5099                 self.result_ctype = py_object_type
5100                 self.operand = self.operand.coerce_to_pyobject(env)
5101             else:
5102                 if self.operand.type.is_ptr:
5103                     if not (self.operand.type.base_type.is_void or self.operand.type.base_type.is_struct):
5104                         error(self.pos, "Python objects cannot be cast from pointers of primitive types")
5105                 else:
5106                     # Should this be an error? 
5107                     warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.operand.type, self.type))
5108                 self.operand = self.operand.coerce_to_simple(env)
5109         elif from_py and not to_py:
5110             if self.type.create_from_py_utility_code(env):
5111                 self.operand = self.operand.coerce_to(self.type, env)
5112             elif self.type.is_ptr:
5113                 if not (self.type.base_type.is_void or self.type.base_type.is_struct):
5114                     error(self.pos, "Python objects cannot be cast to pointers of primitive types")
5115             else:
5116                 warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.type, self.operand.type))
5117         elif from_py and to_py:
5118             if self.typecheck and self.type.is_extension_type:
5119                 self.operand = PyTypeTestNode(self.operand, self.type, env, notnone=True)
5120         elif self.type.is_complex and self.operand.type.is_complex:
5121             self.operand = self.operand.coerce_to_simple(env)
5122
5123     def nogil_check(self, env):
5124         if self.type and self.type.is_pyobject and self.is_temp:
5125             self.gil_error()
5126
5127     def check_const(self):
5128         return self.operand.check_const()
5129
5130     def calculate_constant_result(self):
5131         # we usually do not know the result of a type cast at code
5132         # generation time
5133         pass
5134     
5135     def calculate_result_code(self):
5136         if self.type.is_complex:
5137             operand_result = self.operand.result()
5138             if self.operand.type.is_complex:
5139                 real_part = self.type.real_type.cast_code("__Pyx_CREAL(%s)" % operand_result)
5140                 imag_part = self.type.real_type.cast_code("__Pyx_CIMAG(%s)" % operand_result)
5141             else:
5142                 real_part = self.type.real_type.cast_code(operand_result)
5143                 imag_part = "0"
5144             return "%s(%s, %s)" % (
5145                     self.type.from_parts,
5146                     real_part,
5147                     imag_part)    
5148         else:
5149             return self.type.cast_code(self.operand.result())
5150     
5151     def get_constant_c_result_code(self):
5152         operand_result = self.operand.get_constant_c_result_code()
5153         if operand_result:
5154             return self.type.cast_code(operand_result)
5155     
5156     def result_as(self, type):
5157         if self.type.is_pyobject and not self.is_temp:
5158             #  Optimise away some unnecessary casting
5159             return self.operand.result_as(type)
5160         else:
5161             return ExprNode.result_as(self, type)
5162
5163     def generate_result_code(self, code):
5164         if self.is_temp:
5165             code.putln(
5166                 "%s = (PyObject *)%s;" % (
5167                     self.result(),
5168                     self.operand.result()))
5169             code.put_incref(self.result(), self.ctype())
5170
5171
5172 class SizeofNode(ExprNode):
5173     #  Abstract base class for sizeof(x) expression nodes.
5174     
5175     type = PyrexTypes.c_size_t_type
5176
5177     def check_const(self):
5178         return True
5179
5180     def generate_result_code(self, code):
5181         pass
5182
5183
5184 class SizeofTypeNode(SizeofNode):
5185     #  C sizeof function applied to a type
5186     #
5187     #  base_type   CBaseTypeNode
5188     #  declarator  CDeclaratorNode
5189     
5190     subexprs = []
5191     arg_type = None
5192     
5193     def analyse_types(self, env):
5194         # we may have incorrectly interpreted a dotted name as a type rather than an attribute
5195         # this could be better handled by more uniformly treating types as runtime-available objects
5196         if 0 and self.base_type.module_path:
5197             path = self.base_type.module_path
5198             obj = env.lookup(path[0])
5199             if obj.as_module is None:
5200                 operand = NameNode(pos=self.pos, name=path[0])
5201                 for attr in path[1:]:
5202                     operand = AttributeNode(pos=self.pos, obj=operand, attribute=attr)
5203                 operand = AttributeNode(pos=self.pos, obj=operand, attribute=self.base_type.name)
5204                 self.operand = operand
5205                 self.__class__ = SizeofVarNode
5206                 self.analyse_types(env)
5207                 return
5208         if self.arg_type is None:
5209             base_type = self.base_type.analyse(env)
5210             _, arg_type = self.declarator.analyse(base_type, env)
5211             self.arg_type = arg_type
5212         self.check_type()
5213         
5214     def check_type(self):
5215         arg_type = self.arg_type
5216         if arg_type.is_pyobject and not arg_type.is_extension_type:
5217             error(self.pos, "Cannot take sizeof Python object")
5218         elif arg_type.is_void:
5219             error(self.pos, "Cannot take sizeof void")
5220         elif not arg_type.is_complete():
5221             error(self.pos, "Cannot take sizeof incomplete type '%s'" % arg_type)
5222         
5223     def calculate_result_code(self):
5224         if self.arg_type.is_extension_type:
5225             # the size of the pointer is boring
5226             # we want the size of the actual struct
5227             arg_code = self.arg_type.declaration_code("", deref=1)
5228         else:
5229             arg_code = self.arg_type.declaration_code("")
5230         return "(sizeof(%s))" % arg_code
5231     
5232
5233 class SizeofVarNode(SizeofNode):
5234     #  C sizeof function applied to a variable
5235     #
5236     #  operand   ExprNode
5237     
5238     subexprs = ['operand']
5239     
5240     def analyse_types(self, env):
5241         # We may actually be looking at a type rather than a variable...
5242         # If we are, traditional analysis would fail...
5243         operand_as_type = self.operand.analyse_as_type(env)
5244         if operand_as_type:
5245             self.arg_type = operand_as_type
5246             self.__class__ = SizeofTypeNode
5247             self.check_type()
5248         else:
5249             self.operand.analyse_types(env)
5250     
5251     def calculate_result_code(self):
5252         return "(sizeof(%s))" % self.operand.result()
5253     
5254     def generate_result_code(self, code):
5255         pass
5256
5257 class TypeofNode(ExprNode):
5258     #  Compile-time type of an expression, as a string.
5259     #
5260     #  operand   ExprNode
5261     #  literal   StringNode # internal
5262     
5263     literal = None
5264     type = py_object_type
5265     
5266     subexprs = ['literal'] # 'operand' will be ignored after type analysis!
5267     
5268     def analyse_types(self, env):
5269         self.operand.analyse_types(env)
5270         self.literal = StringNode(
5271             self.pos, value=StringEncoding.EncodedString(str(self.operand.type)))
5272         self.literal.analyse_types(env)
5273         self.literal = self.literal.coerce_to_pyobject(env)
5274
5275     def may_be_none(self):
5276         return False
5277
5278     def generate_evaluation_code(self, code):
5279         self.literal.generate_evaluation_code(code)
5280     
5281     def calculate_result_code(self):
5282         return self.literal.calculate_result_code()
5283
5284 #-------------------------------------------------------------------
5285 #
5286 #  Binary operator nodes
5287 #
5288 #-------------------------------------------------------------------
5289
5290 def _not_in(x, seq):
5291     return x not in seq
5292
5293 compile_time_binary_operators = {
5294     '<': operator.lt,
5295     '<=': operator.le,
5296     '==': operator.eq,
5297     '!=': operator.ne,
5298     '>=': operator.ge,
5299     '>': operator.gt,
5300     'is': operator.is_,
5301     'is_not': operator.is_not,
5302     '+': operator.add,
5303     '&': operator.and_,
5304     '/': operator.truediv,
5305     '//': operator.floordiv,
5306     '<<': operator.lshift,
5307     '%': operator.mod,
5308     '*': operator.mul,
5309     '|': operator.or_,
5310     '**': operator.pow,
5311     '>>': operator.rshift,
5312     '-': operator.sub,
5313     '^': operator.xor,
5314     'in': operator.contains,
5315     'not_in': _not_in,
5316 }
5317
5318 def get_compile_time_binop(node):
5319     func = compile_time_binary_operators.get(node.operator)
5320     if not func:
5321         error(node.pos,
5322             "Binary '%s' not supported in compile-time expression"
5323                 % node.operator)
5324     return func
5325
5326 class BinopNode(ExprNode):
5327     #  operator     string
5328     #  operand1     ExprNode
5329     #  operand2     ExprNode
5330     #
5331     #  Processing during analyse_expressions phase:
5332     #
5333     #    analyse_c_operation
5334     #      Called when neither operand is a pyobject.
5335     #      - Check operand types and coerce if needed.
5336     #      - Determine result type and result code fragment.
5337     #      - Allocate temporary for result if needed.
5338     
5339     subexprs = ['operand1', 'operand2']
5340     inplace = False
5341
5342     def calculate_constant_result(self):
5343         func = compile_time_binary_operators[self.operator]
5344         self.constant_result = func(
5345             self.operand1.constant_result,
5346             self.operand2.constant_result)
5347
5348     def compile_time_value(self, denv):
5349         func = get_compile_time_binop(self)
5350         operand1 = self.operand1.compile_time_value(denv)
5351         operand2 = self.operand2.compile_time_value(denv)
5352         try:
5353             return func(operand1, operand2)
5354         except Exception, e:
5355             self.compile_time_value_error(e)
5356     
5357     def infer_type(self, env):
5358         return self.result_type(self.operand1.infer_type(env),
5359                                 self.operand2.infer_type(env))
5360     
5361     def analyse_types(self, env):
5362         self.operand1.analyse_types(env)
5363         self.operand2.analyse_types(env)
5364         self.analyse_operation(env)
5365     
5366     def analyse_operation(self, env):
5367         if self.is_py_operation():
5368             self.coerce_operands_to_pyobjects(env)
5369             self.type = self.result_type(self.operand1.type,
5370                                          self.operand2.type)
5371             assert self.type.is_pyobject
5372             self.is_temp = 1
5373         elif self.is_cpp_operation():
5374             self.analyse_cpp_operation(env)
5375         else:
5376             self.analyse_c_operation(env)
5377     
5378     def is_py_operation(self):
5379         return self.is_py_operation_types(self.operand1.type, self.operand2.type)
5380     
5381     def is_py_operation_types(self, type1, type2):
5382         return type1.is_pyobject or type2.is_pyobject
5383
5384     def is_cpp_operation(self):
5385         return (self.operand1.type.is_cpp_class
5386             or self.operand2.type.is_cpp_class)
5387     
5388     def analyse_cpp_operation(self, env):
5389         type1 = self.operand1.type
5390         type2 = self.operand2.type
5391         entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
5392         if not entry:
5393             self.type_error()
5394             return
5395         func_type = entry.type
5396         if func_type.is_ptr:
5397             func_type = func_type.base_type
5398         if len(func_type.args) == 1:
5399             self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
5400         else:
5401             self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
5402             self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
5403         self.type = func_type.return_type
5404     
5405     def result_type(self, type1, type2):
5406         if self.is_py_operation_types(type1, type2):
5407             if type2.is_string:
5408                 type2 = Builtin.bytes_type
5409             if type1.is_string:
5410                 type1 = Builtin.bytes_type
5411             elif self.operator == '%' \
5412                      and type1 in (Builtin.str_type, Builtin.unicode_type):
5413                 # note that  b'%s' % b'abc'  doesn't work in Py3
5414                 return type1
5415             if type1.is_builtin_type:
5416                 if type1 is type2:
5417                     if self.operator in '**%+|&^':
5418                         # FIXME: at least these operators should be safe - others?
5419                         return type1
5420                 elif self.operator == '*':
5421                     if type1 in (Builtin.bytes_type, Builtin.str_type, Builtin.unicode_type):
5422                         return type1
5423                     # multiplication of containers/numbers with an
5424                     # integer value always (?) returns the same type
5425                     if type2.is_int:
5426                         return type1
5427             elif type2.is_builtin_type and type1.is_int and self.operator == '*':
5428                 # multiplication of containers/numbers with an
5429                 # integer value always (?) returns the same type
5430                 return type2
5431             return py_object_type
5432         else:
5433             return self.compute_c_result_type(type1, type2)
5434
5435     def nogil_check(self, env):
5436         if self.is_py_operation():
5437             self.gil_error()
5438         
5439     def coerce_operands_to_pyobjects(self, env):
5440         self.operand1 = self.operand1.coerce_to_pyobject(env)
5441         self.operand2 = self.operand2.coerce_to_pyobject(env)
5442     
5443     def check_const(self):
5444         return self.operand1.check_const() and self.operand2.check_const()
5445     
5446     def generate_result_code(self, code):
5447         #print "BinopNode.generate_result_code:", self.operand1, self.operand2 ###
5448         if self.operand1.type.is_pyobject:
5449             function = self.py_operation_function()
5450             if self.operator == '**':
5451                 extra_args = ", Py_None"
5452             else:
5453                 extra_args = ""
5454             code.putln(
5455                 "%s = %s(%s, %s%s); %s" % (
5456                     self.result(), 
5457                     function, 
5458                     self.operand1.py_result(),
5459                     self.operand2.py_result(),
5460                     extra_args,
5461                     code.error_goto_if_null(self.result(), self.pos)))
5462             code.put_gotref(self.py_result())
5463     
5464     def type_error(self):
5465         if not (self.operand1.type.is_error
5466                 or self.operand2.type.is_error):
5467             error(self.pos, "Invalid operand types for '%s' (%s; %s)" %
5468                 (self.operator, self.operand1.type, 
5469                     self.operand2.type))
5470         self.type = PyrexTypes.error_type
5471
5472
5473 class CBinopNode(BinopNode):
5474     
5475     def analyse_types(self, env):
5476         BinopNode.analyse_types(self, env)
5477         if self.is_py_operation():
5478             self.type = PyrexTypes.error_type
5479     
5480     def py_operation_function():
5481         return ""
5482         
5483     def calculate_result_code(self):
5484         return "(%s %s %s)" % (
5485             self.operand1.result(), 
5486             self.operator, 
5487             self.operand2.result())
5488
5489
5490 def c_binop_constructor(operator):
5491     def make_binop_node(pos, **operands):
5492         return CBinopNode(pos, operator=operator, **operands)
5493     return make_binop_node
5494
5495 class NumBinopNode(BinopNode):
5496     #  Binary operation taking numeric arguments.
5497     
5498     infix = True
5499     
5500     def analyse_c_operation(self, env):
5501         type1 = self.operand1.type
5502         type2 = self.operand2.type
5503         self.type = self.compute_c_result_type(type1, type2)
5504         if not self.type:
5505             self.type_error()
5506             return
5507         if self.type.is_complex:
5508             self.infix = False
5509         if not self.infix or (type1.is_numeric and type2.is_numeric):
5510             self.operand1 = self.operand1.coerce_to(self.type, env)
5511             self.operand2 = self.operand2.coerce_to(self.type, env)
5512     
5513     def compute_c_result_type(self, type1, type2):
5514         if self.c_types_okay(type1, type2):
5515             return PyrexTypes.widest_numeric_type(type1, type2)
5516         else:
5517             return None
5518
5519     def get_constant_c_result_code(self):
5520         value1 = self.operand1.get_constant_c_result_code()
5521         value2 = self.operand2.get_constant_c_result_code()
5522         if value1 and value2:
5523             return "(%s %s %s)" % (value1, self.operator, value2)
5524         else:
5525             return None
5526     
5527     def c_types_okay(self, type1, type2):
5528         #print "NumBinopNode.c_types_okay:", type1, type2 ###
5529         return (type1.is_numeric  or type1.is_enum) \
5530             and (type2.is_numeric  or type2.is_enum)
5531
5532     def calculate_result_code(self):
5533         if self.infix:
5534             return "(%s %s %s)" % (
5535                 self.operand1.result(), 
5536                 self.operator, 
5537                 self.operand2.result())
5538         else:
5539             func = self.type.binary_op(self.operator)
5540             if func is None:
5541                 error(self.pos, "binary operator %s not supported for %s" % (self.operator, self.type))
5542             return "%s(%s, %s)" % (
5543                 func,
5544                 self.operand1.result(),
5545                 self.operand2.result())
5546     
5547     def is_py_operation_types(self, type1, type2):
5548         return (type1 is PyrexTypes.c_py_unicode_type or
5549                 type2 is PyrexTypes.c_py_unicode_type or
5550                 BinopNode.is_py_operation_types(self, type1, type2))
5551     
5552     def py_operation_function(self):
5553         fuction = self.py_functions[self.operator]
5554         if self.inplace:
5555             fuction = fuction.replace('PyNumber_', 'PyNumber_InPlace')
5556         return fuction
5557
5558     py_functions = {
5559         "|":        "PyNumber_Or",
5560         "^":        "PyNumber_Xor",
5561         "&":        "PyNumber_And",
5562         "<<":       "PyNumber_Lshift",
5563         ">>":       "PyNumber_Rshift",
5564         "+":        "PyNumber_Add",
5565         "-":        "PyNumber_Subtract",
5566         "*":        "PyNumber_Multiply",
5567         "/":        "__Pyx_PyNumber_Divide",
5568         "//":       "PyNumber_FloorDivide",
5569         "%":        "PyNumber_Remainder",
5570         "**":       "PyNumber_Power"
5571     }
5572
5573 class IntBinopNode(NumBinopNode):
5574     #  Binary operation taking integer arguments.
5575     
5576     def c_types_okay(self, type1, type2):
5577         #print "IntBinopNode.c_types_okay:", type1, type2 ###
5578         return (type1.is_int or type1.is_enum) \
5579             and (type2.is_int or type2.is_enum)
5580
5581     
5582 class AddNode(NumBinopNode):
5583     #  '+' operator.
5584     
5585     def is_py_operation_types(self, type1, type2):
5586         if type1.is_string and type2.is_string:
5587             return 1
5588         else:
5589             return NumBinopNode.is_py_operation_types(self, type1, type2)
5590
5591     def compute_c_result_type(self, type1, type2):
5592         #print "AddNode.compute_c_result_type:", type1, self.operator, type2 ###
5593         if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
5594             return type1
5595         elif (type2.is_ptr or type2.is_array) and (type1.is_int or type1.is_enum):
5596             return type2
5597         else:
5598             return NumBinopNode.compute_c_result_type(
5599                 self, type1, type2)
5600
5601
5602 class SubNode(NumBinopNode):
5603     #  '-' operator.
5604     
5605     def compute_c_result_type(self, type1, type2):
5606         if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
5607             return type1
5608         elif (type1.is_ptr or type1.is_array) and (type2.is_ptr or type2.is_array):
5609             return PyrexTypes.c_int_type
5610         else:
5611             return NumBinopNode.compute_c_result_type(
5612                 self, type1, type2)
5613
5614
5615 class MulNode(NumBinopNode):
5616     #  '*' operator.
5617     
5618     def is_py_operation_types(self, type1, type2):
5619         if (type1.is_string and type2.is_int) \
5620             or (type2.is_string and type1.is_int):
5621                 return 1
5622         else:
5623             return NumBinopNode.is_py_operation_types(self, type1, type2)
5624
5625
5626 class DivNode(NumBinopNode):
5627     #  '/' or '//' operator.
5628     
5629     cdivision = None
5630     truedivision = None   # == "unknown" if operator == '/'
5631     ctruedivision = False
5632     cdivision_warnings = False
5633     zerodivision_check = None
5634
5635     def find_compile_time_binary_operator(self, op1, op2):
5636         func = compile_time_binary_operators[self.operator]
5637         if self.operator == '/' and self.truedivision is None:
5638             # => true div for floats, floor div for integers
5639             if isinstance(op1, (int,long)) and isinstance(op2, (int,long)):
5640                 func = compile_time_binary_operators['//']
5641         return func
5642
5643     def calculate_constant_result(self):
5644         op1 = self.operand1.constant_result
5645         op2 = self.operand2.constant_result
5646         func = self.find_compile_time_binary_operator(op1, op2)
5647         self.constant_result = func(
5648             self.operand1.constant_result,
5649             self.operand2.constant_result)
5650
5651     def compile_time_value(self, denv):
5652         operand1 = self.operand1.compile_time_value(denv)
5653         operand2 = self.operand2.compile_time_value(denv)
5654         try:
5655             func = self.find_compile_time_binary_operator(
5656                 self, operand1, operand2)
5657             return func(operand1, operand2)
5658         except Exception, e:
5659             self.compile_time_value_error(e)
5660
5661     def analyse_operation(self, env):
5662         if self.cdivision or env.directives['cdivision']:
5663             self.ctruedivision = False
5664         else:
5665             self.ctruedivision = self.truedivision
5666         NumBinopNode.analyse_operation(self, env)
5667         if self.is_cpp_operation():
5668             self.cdivision = True
5669         if not self.type.is_pyobject:
5670             self.zerodivision_check = (
5671                 self.cdivision is None and not env.directives['cdivision']
5672                 and (not self.operand2.has_constant_result() or
5673                      self.operand2.constant_result == 0))
5674             if self.zerodivision_check or env.directives['cdivision_warnings']:
5675                 # Need to check ahead of time to warn or raise zero division error
5676                 self.operand1 = self.operand1.coerce_to_simple(env)
5677                 self.operand2 = self.operand2.coerce_to_simple(env)
5678                 if env.nogil:
5679                     error(self.pos, "Pythonic division not allowed without gil, consider using cython.cdivision(True)")
5680
5681     def compute_c_result_type(self, type1, type2):
5682         if self.operator == '/' and self.ctruedivision:
5683             if not type1.is_float and not type2.is_float:
5684                 widest_type = PyrexTypes.widest_numeric_type(type1, PyrexTypes.c_double_type)
5685                 widest_type = PyrexTypes.widest_numeric_type(type2, widest_type)
5686                 return widest_type
5687         return NumBinopNode.compute_c_result_type(self, type1, type2)
5688
5689     def zero_division_message(self):
5690         if self.type.is_int:
5691             return "integer division or modulo by zero"
5692         else:
5693             return "float division"
5694
5695     def generate_evaluation_code(self, code):
5696         if not self.type.is_pyobject and not self.type.is_complex:
5697             if self.cdivision is None:
5698                 self.cdivision = (code.globalstate.directives['cdivision'] 
5699                                     or not self.type.signed
5700                                     or self.type.is_float)
5701             if not self.cdivision:
5702                 code.globalstate.use_utility_code(div_int_utility_code.specialize(self.type))
5703         NumBinopNode.generate_evaluation_code(self, code)
5704         self.generate_div_warning_code(code)
5705     
5706     def generate_div_warning_code(self, code):
5707         if not self.type.is_pyobject:
5708             if self.zerodivision_check:
5709                 if not self.infix:
5710                     zero_test = "%s(%s)" % (self.type.unary_op('zero'), self.operand2.result())
5711                 else:
5712                     zero_test = "%s == 0" % self.operand2.result()
5713                 code.putln("if (unlikely(%s)) {" % zero_test)
5714                 code.putln('PyErr_Format(PyExc_ZeroDivisionError, "%s");' % self.zero_division_message())
5715                 code.putln(code.error_goto(self.pos))
5716                 code.putln("}")
5717                 if self.type.is_int and self.type.signed and self.operator != '%':
5718                     code.globalstate.use_utility_code(division_overflow_test_code)
5719                     code.putln("else if (sizeof(%s) == sizeof(long) && unlikely(%s == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(%s))) {" % (
5720                                     self.type.declaration_code(''), 
5721                                     self.operand2.result(),
5722                                     self.operand1.result()))
5723                     code.putln('PyErr_Format(PyExc_OverflowError, "value too large to perform division");')
5724                     code.putln(code.error_goto(self.pos))
5725                     code.putln("}")
5726             if code.globalstate.directives['cdivision_warnings'] and self.operator != '/':
5727                 code.globalstate.use_utility_code(cdivision_warning_utility_code)
5728                 code.putln("if ((%s < 0) ^ (%s < 0)) {" % (
5729                                 self.operand1.result(),
5730                                 self.operand2.result()))
5731                 code.putln(code.set_error_info(self.pos));
5732                 code.put("if (__Pyx_cdivision_warning()) ")
5733                 code.put_goto(code.error_label)
5734                 code.putln("}")
5735     
5736     def calculate_result_code(self):
5737         if self.type.is_complex:
5738             return NumBinopNode.calculate_result_code(self)
5739         elif self.type.is_float and self.operator == '//':
5740             return "floor(%s / %s)" % (
5741                 self.operand1.result(),
5742                 self.operand2.result())
5743         elif self.truedivision or self.cdivision:
5744             op1 = self.operand1.result()
5745             op2 = self.operand2.result()
5746             if self.truedivision:
5747                 if self.type != self.operand1.type:
5748                     op1 = self.type.cast_code(op1)
5749                 if self.type != self.operand2.type:
5750                     op2 = self.type.cast_code(op2)
5751             return "(%s / %s)" % (op1, op2)
5752         else:
5753             return "__Pyx_div_%s(%s, %s)" % (
5754                     self.type.specialization_name(),
5755                     self.operand1.result(), 
5756                     self.operand2.result())
5757
5758
5759 class ModNode(DivNode):
5760     #  '%' operator.
5761
5762     def is_py_operation_types(self, type1, type2):
5763         return (type1.is_string
5764             or type2.is_string
5765             or NumBinopNode.is_py_operation_types(self, type1, type2))
5766
5767     def zero_division_message(self):
5768         if self.type.is_int:
5769             return "integer division or modulo by zero"
5770         else:
5771             return "float divmod()"
5772     
5773     def generate_evaluation_code(self, code):
5774         if not self.type.is_pyobject:
5775             if self.cdivision is None:
5776                 self.cdivision = code.globalstate.directives['cdivision'] or not self.type.signed
5777             if not self.cdivision:
5778                 if self.type.is_int:
5779                     code.globalstate.use_utility_code(mod_int_utility_code.specialize(self.type))
5780                 else:
5781                     code.globalstate.use_utility_code(
5782                         mod_float_utility_code.specialize(self.type, math_h_modifier=self.type.math_h_modifier))
5783         NumBinopNode.generate_evaluation_code(self, code)
5784         self.generate_div_warning_code(code)
5785     
5786     def calculate_result_code(self):
5787         if self.cdivision:
5788             if self.type.is_float:
5789                 return "fmod%s(%s, %s)" % (
5790                     self.type.math_h_modifier,
5791                     self.operand1.result(), 
5792                     self.operand2.result())
5793             else:
5794                 return "(%s %% %s)" % (
5795                     self.operand1.result(), 
5796                     self.operand2.result())
5797         else:
5798             return "__Pyx_mod_%s(%s, %s)" % (
5799                     self.type.specialization_name(),
5800                     self.operand1.result(), 
5801                     self.operand2.result())
5802
5803 class PowNode(NumBinopNode):
5804     #  '**' operator.
5805     
5806     def analyse_c_operation(self, env):
5807         NumBinopNode.analyse_c_operation(self, env)
5808         if self.type.is_complex:
5809             if self.type.real_type.is_float:
5810                 self.operand1 = self.operand1.coerce_to(self.type, env)
5811                 self.operand2 = self.operand2.coerce_to(self.type, env)
5812                 self.pow_func = "__Pyx_c_pow" + self.type.real_type.math_h_modifier
5813             else:
5814                 error(self.pos, "complex int powers not supported")
5815                 self.pow_func = "<error>"
5816         elif self.type.is_float:
5817             self.pow_func = "pow" + self.type.math_h_modifier
5818         else:
5819             self.pow_func = "__Pyx_pow_%s" % self.type.declaration_code('').replace(' ', '_')
5820             env.use_utility_code(
5821                     int_pow_utility_code.specialize(func_name=self.pow_func, 
5822                                                 type=self.type.declaration_code('')))
5823
5824     def calculate_result_code(self):
5825         # Work around MSVC overloading ambiguity.
5826         def typecast(operand):
5827             if self.type == operand.type:
5828                 return operand.result()
5829             else:
5830                 return self.type.cast_code(operand.result())
5831         return "%s(%s, %s)" % (
5832             self.pow_func, 
5833             typecast(self.operand1), 
5834             typecast(self.operand2))
5835
5836
5837 # Note: This class is temporarily "shut down" into an ineffective temp
5838 # allocation mode.
5839 #
5840 # More sophisticated temp reuse was going on before, one could have a
5841 # look at adding this again after /all/ classes are converted to the
5842 # new temp scheme. (The temp juggling cannot work otherwise).
5843 class BoolBinopNode(ExprNode):
5844     #  Short-circuiting boolean operation.
5845     #
5846     #  operator     string
5847     #  operand1     ExprNode
5848     #  operand2     ExprNode
5849     
5850     subexprs = ['operand1', 'operand2']
5851     
5852     def infer_type(self, env):
5853         type1 = self.operand1.infer_type(env)
5854         type2 = self.operand2.infer_type(env)
5855         return PyrexTypes.independent_spanning_type(type1, type2)
5856
5857     def may_be_none(self):
5858         if self.operator == 'or':
5859             return self.operand2.may_be_none()
5860         else:
5861             return self.operand1.may_be_none() or self.operand2.may_be_none()
5862
5863     def calculate_constant_result(self):
5864         if self.operator == 'and':
5865             self.constant_result = \
5866                 self.operand1.constant_result and \
5867                 self.operand2.constant_result
5868         else:
5869             self.constant_result = \
5870                 self.operand1.constant_result or \
5871                 self.operand2.constant_result
5872     
5873     def compile_time_value(self, denv):
5874         if self.operator == 'and':
5875             return self.operand1.compile_time_value(denv) \
5876                 and self.operand2.compile_time_value(denv)
5877         else:
5878             return self.operand1.compile_time_value(denv) \
5879                 or self.operand2.compile_time_value(denv)
5880     
5881     def coerce_to_boolean(self, env):
5882         return BoolBinopNode(
5883             self.pos,
5884             operator = self.operator,
5885             operand1 = self.operand1.coerce_to_boolean(env),
5886             operand2 = self.operand2.coerce_to_boolean(env),
5887             type = PyrexTypes.c_bint_type,
5888             is_temp = self.is_temp)
5889
5890     def analyse_types(self, env):
5891         self.operand1.analyse_types(env)
5892         self.operand2.analyse_types(env)
5893         self.type = PyrexTypes.independent_spanning_type(self.operand1.type, self.operand2.type)
5894         self.operand1 = self.operand1.coerce_to(self.type, env)
5895         self.operand2 = self.operand2.coerce_to(self.type, env)
5896         
5897         # For what we're about to do, it's vital that
5898         # both operands be temp nodes.
5899         self.operand1 = self.operand1.coerce_to_simple(env)
5900         self.operand2 = self.operand2.coerce_to_simple(env)
5901         self.is_temp = 1
5902
5903     gil_message = "Truth-testing Python object"
5904
5905     def check_const(self):
5906         return self.operand1.check_const() and self.operand2.check_const()
5907     
5908     def generate_evaluation_code(self, code):
5909         code.mark_pos(self.pos)
5910         self.operand1.generate_evaluation_code(code)
5911         test_result, uses_temp = self.generate_operand1_test(code)
5912         if self.operator == 'and':
5913             sense = ""
5914         else:
5915             sense = "!"
5916         code.putln(
5917             "if (%s%s) {" % (
5918                 sense,
5919                 test_result))
5920         if uses_temp:
5921             code.funcstate.release_temp(test_result)
5922         self.operand1.generate_disposal_code(code)
5923         self.operand2.generate_evaluation_code(code)
5924         self.allocate_temp_result(code)
5925         self.operand2.make_owned_reference(code)
5926         code.putln("%s = %s;" % (self.result(), self.operand2.result()))
5927         self.operand2.generate_post_assignment_code(code)
5928         self.operand2.free_temps(code)
5929         code.putln("} else {")
5930         self.operand1.make_owned_reference(code)
5931         code.putln("%s = %s;" % (self.result(), self.operand1.result()))
5932         self.operand1.generate_post_assignment_code(code)
5933         self.operand1.free_temps(code)
5934         code.putln("}")
5935     
5936     def generate_operand1_test(self, code):
5937         #  Generate code to test the truth of the first operand.
5938         if self.type.is_pyobject:
5939             test_result = code.funcstate.allocate_temp(PyrexTypes.c_bint_type,
5940                                                        manage_ref=False)
5941             code.putln(
5942                 "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
5943                     test_result,
5944                     self.operand1.py_result(),
5945                     code.error_goto_if_neg(test_result, self.pos)))
5946         else:
5947             test_result = self.operand1.result()
5948         return (test_result, self.type.is_pyobject)
5949
5950
5951 class CondExprNode(ExprNode):
5952     #  Short-circuiting conditional expression.
5953     #
5954     #  test        ExprNode
5955     #  true_val    ExprNode
5956     #  false_val   ExprNode
5957     
5958     true_val = None
5959     false_val = None
5960     
5961     subexprs = ['test', 'true_val', 'false_val']
5962     
5963     def type_dependencies(self, env):
5964         return self.true_val.type_dependencies(env) + self.false_val.type_dependencies(env)
5965     
5966     def infer_type(self, env):
5967         return PyrexTypes.independent_spanning_type(self.true_val.infer_type(env),
5968                                                     self.false_val.infer_type(env))
5969
5970     def calculate_constant_result(self):
5971         if self.test.constant_result:
5972             self.constant_result = self.true_val.constant_result
5973         else:
5974             self.constant_result = self.false_val.constant_result
5975
5976     def analyse_types(self, env):
5977         self.test.analyse_types(env)
5978         self.test = self.test.coerce_to_boolean(env)
5979         self.true_val.analyse_types(env)
5980         self.false_val.analyse_types(env)
5981         self.type = PyrexTypes.independent_spanning_type(self.true_val.type, self.false_val.type)
5982         if self.true_val.type.is_pyobject or self.false_val.type.is_pyobject:
5983             self.true_val = self.true_val.coerce_to(self.type, env)
5984             self.false_val = self.false_val.coerce_to(self.type, env)
5985         self.is_temp = 1
5986         if self.type == PyrexTypes.error_type:
5987             self.type_error()
5988         
5989     def type_error(self):
5990         if not (self.true_val.type.is_error or self.false_val.type.is_error):
5991             error(self.pos, "Incompatable types in conditional expression (%s; %s)" %
5992                 (self.true_val.type, self.false_val.type))
5993         self.type = PyrexTypes.error_type
5994     
5995     def check_const(self):
5996         return (self.test.check_const() 
5997             and self.true_val.check_const()
5998             and self.false_val.check_const())
5999     
6000     def generate_evaluation_code(self, code):
6001         # Because subexprs may not be evaluated we can use a more optimal
6002         # subexpr allocation strategy than the default, so override evaluation_code.
6003         
6004         code.mark_pos(self.pos)
6005         self.allocate_temp_result(code)
6006         self.test.generate_evaluation_code(code)
6007         code.putln("if (%s) {" % self.test.result() )
6008         self.eval_and_get(code, self.true_val)
6009         code.putln("} else {")
6010         self.eval_and_get(code, self.false_val)
6011         code.putln("}")
6012         self.test.generate_disposal_code(code)
6013         self.test.free_temps(code)
6014
6015     def eval_and_get(self, code, expr):
6016         expr.generate_evaluation_code(code)
6017         expr.make_owned_reference(code)
6018         code.putln("%s = %s;" % (self.result(), expr.result()))
6019         expr.generate_post_assignment_code(code)
6020         expr.free_temps(code)
6021
6022 richcmp_constants = {
6023     "<" : "Py_LT",
6024     "<=": "Py_LE",
6025     "==": "Py_EQ",
6026     "!=": "Py_NE",
6027     "<>": "Py_NE",
6028     ">" : "Py_GT",
6029     ">=": "Py_GE",
6030 }
6031
6032 class CmpNode(object):
6033     #  Mixin class containing code common to PrimaryCmpNodes
6034     #  and CascadedCmpNodes.
6035
6036     special_bool_cmp_function = None
6037
6038     def infer_type(self, env):
6039         # TODO: Actually implement this (after merging with -unstable).
6040         return py_object_type
6041
6042     def calculate_cascaded_constant_result(self, operand1_result):
6043         func = compile_time_binary_operators[self.operator]
6044         operand2_result = self.operand2.constant_result
6045         result = func(operand1_result, operand2_result)
6046         if self.cascade:
6047             self.cascade.calculate_cascaded_constant_result(operand2_result)
6048             if self.cascade.constant_result:
6049                 self.constant_result = result and self.cascade.constant_result
6050         else:
6051             self.constant_result = result
6052
6053     def cascaded_compile_time_value(self, operand1, denv):
6054         func = get_compile_time_binop(self)
6055         operand2 = self.operand2.compile_time_value(denv)
6056         try:
6057             result = func(operand1, operand2)
6058         except Exception, e:
6059             self.compile_time_value_error(e)
6060             result = None
6061         if result:
6062             cascade = self.cascade
6063             if cascade:
6064                 # FIXME: I bet this must call cascaded_compile_time_value()
6065                 result = result and cascade.cascaded_compile_time_value(operand2, denv)
6066         return result
6067
6068     def is_cpp_comparison(self):
6069         return self.operand1.type.is_cpp_class or self.operand2.type.is_cpp_class
6070
6071     def find_common_int_type(self, env, op, operand1, operand2):
6072         # type1 != type2 and at least one of the types is not a C int
6073         type1 = operand1.type
6074         type2 = operand2.type
6075         type1_can_be_int = False
6076         type2_can_be_int = False
6077
6078         if isinstance(operand1, (StringNode, BytesNode, UnicodeNode)) \
6079                and operand1.can_coerce_to_char_literal():
6080             type1_can_be_int = True
6081         if isinstance(operand2, (StringNode, BytesNode, UnicodeNode)) \
6082                  and operand2.can_coerce_to_char_literal():
6083             type2_can_be_int = True
6084
6085         if type1.is_int:
6086             if type2_can_be_int:
6087                 return type1
6088         elif type2.is_int:
6089             if type1_can_be_int:
6090                 return type2
6091         elif type1_can_be_int:
6092             if type2_can_be_int:
6093                 return PyrexTypes.c_uchar_type
6094
6095         return None
6096
6097     def find_common_type(self, env, op, operand1, common_type=None):
6098         operand2 = self.operand2
6099         type1 = operand1.type
6100         type2 = operand2.type
6101
6102         new_common_type = None
6103
6104         # catch general errors
6105         if type1 == str_type and (type2.is_string or type2 in (bytes_type, unicode_type)) or \
6106                type2 == str_type and (type1.is_string or type1 in (bytes_type, unicode_type)):
6107             error(self.pos, "Comparisons between bytes/unicode and str are not portable to Python 3")
6108             new_common_type = error_type
6109
6110         # try to use numeric comparisons where possible
6111         elif type1.is_complex or type2.is_complex:
6112             if op not in ('==', '!='):
6113                 error(self.pos, "complex types are unordered")
6114                 new_common_type = error_type
6115             if type1.is_pyobject:
6116                 new_common_type = type1
6117             elif type2.is_pyobject:
6118                 new_common_type = type2
6119             else:
6120                 new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
6121         elif type1.is_numeric and type2.is_numeric:
6122             new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
6123         elif common_type is None or not common_type.is_pyobject:
6124             new_common_type = self.find_common_int_type(env, op, operand1, operand2)
6125
6126         if new_common_type is None:
6127             # fall back to generic type compatibility tests
6128             if type1 == type2:
6129                 new_common_type = type1
6130             elif type1.is_pyobject or type2.is_pyobject:
6131                 if type2.is_numeric or type2.is_string:
6132                     if operand2.check_for_coercion_error(type1):
6133                         new_common_type = error_type
6134                     else:
6135                         new_common_type = py_object_type
6136                 elif type1.is_numeric or type1.is_string:
6137                     if operand1.check_for_coercion_error(type2):
6138                         new_common_type = error_type
6139                     else:
6140                         new_common_type = py_object_type
6141                 elif py_object_type.assignable_from(type1) and py_object_type.assignable_from(type2):
6142                     new_common_type = py_object_type
6143                 else:
6144                     # one Python type and one non-Python type, not assignable
6145                     self.invalid_types_error(operand1, op, operand2)
6146                     new_common_type = error_type
6147             elif type1.assignable_from(type2):
6148                 new_common_type = type1
6149             elif type2.assignable_from(type1):
6150                 new_common_type = type2
6151             else:
6152                 # C types that we couldn't handle up to here are an error
6153                 self.invalid_types_error(operand1, op, operand2)
6154                 new_common_type = error_type
6155
6156         if new_common_type.is_string and (isinstance(operand1, BytesNode) or
6157                                           isinstance(operand2, BytesNode)):
6158             # special case when comparing char* to bytes literal: must
6159             # compare string values!
6160             new_common_type = bytes_type
6161
6162         # recursively merge types
6163         if common_type is None or new_common_type.is_error:
6164             common_type = new_common_type
6165         else:
6166             # we could do a lot better by splitting the comparison
6167             # into a non-Python part and a Python part, but this is
6168             # safer for now
6169             common_type = PyrexTypes.spanning_type(common_type, new_common_type)
6170
6171         if self.cascade:
6172             common_type = self.cascade.find_common_type(env, self.operator, operand2, common_type)
6173
6174         return common_type
6175
6176     def invalid_types_error(self, operand1, op, operand2):
6177         error(self.pos, "Invalid types for '%s' (%s, %s)" %
6178               (op, operand1.type, operand2.type))
6179
6180     def is_python_comparison(self):
6181         return (not self.is_ptr_contains()
6182             and not self.is_c_string_contains()
6183             and (self.has_python_operands()
6184                  or (self.cascade and self.cascade.is_python_comparison())
6185                  or self.operator in ('in', 'not_in')))
6186
6187     def coerce_operands_to(self, dst_type, env):
6188         operand2 = self.operand2
6189         if operand2.type != dst_type:
6190             self.operand2 = operand2.coerce_to(dst_type, env)
6191         if self.cascade:
6192             self.cascade.coerce_operands_to(dst_type, env)
6193
6194     def is_python_result(self):
6195         return ((self.has_python_operands() and
6196                  self.special_bool_cmp_function is None and
6197                  self.operator not in ('is', 'is_not', 'in', 'not_in') and
6198                  not self.is_c_string_contains() and
6199                  not self.is_ptr_contains())
6200             or (self.cascade and self.cascade.is_python_result()))
6201
6202     def is_c_string_contains(self):
6203         return self.operator in ('in', 'not_in') and \
6204                ((self.operand1.type.is_int
6205                  and (self.operand2.type.is_string or self.operand2.type is bytes_type)) or
6206                 (self.operand1.type is PyrexTypes.c_py_unicode_type
6207                  and self.operand2.type is unicode_type))
6208     
6209     def is_ptr_contains(self):
6210         if self.operator in ('in', 'not_in'):
6211             container_type = self.operand2.type
6212             return (container_type.is_ptr or container_type.is_array) \
6213                 and not container_type.is_string
6214
6215     def find_special_bool_compare_function(self, env):
6216         if self.operator in ('==', '!='):
6217             type1, type2 = self.operand1.type, self.operand2.type
6218             if type1.is_pyobject and type2.is_pyobject:
6219                 if type1 is Builtin.unicode_type or type2 is Builtin.unicode_type:
6220                     env.use_utility_code(pyunicode_equals_utility_code)
6221                     self.special_bool_cmp_function = "__Pyx_PyUnicode_Equals"
6222                     return True
6223         return False
6224
6225     def generate_operation_code(self, code, result_code, 
6226             operand1, op , operand2):
6227         if self.type.is_pyobject:
6228             coerce_result = "__Pyx_PyBool_FromLong"
6229         else:
6230             coerce_result = ""
6231         if 'not' in op: 
6232             negation = "!"
6233         else: 
6234             negation = ""
6235         if self.special_bool_cmp_function:
6236             if operand1.type.is_pyobject:
6237                 result1 = operand1.py_result()
6238             else:
6239                 result1 = operand1.result()
6240             if operand2.type.is_pyobject:
6241                 result2 = operand2.py_result()
6242             else:
6243                 result2 = operand2.result()
6244             code.putln("%s = %s(%s, %s, %s); %s" % (
6245                 result_code,
6246                 self.special_bool_cmp_function,
6247                 result1,
6248                 result2,
6249                 richcmp_constants[op],
6250                 code.error_goto_if_neg(result_code, self.pos)))
6251         elif op == 'in' or op == 'not_in':
6252             code.globalstate.use_utility_code(contains_utility_code)
6253             if self.type.is_pyobject:
6254                 coerce_result = "__Pyx_PyBoolOrNull_FromLong"
6255             if op == 'not_in':
6256                 negation = "__Pyx_NegateNonNeg"
6257             if operand2.type is dict_type:
6258                 method = "PyDict_Contains"
6259             else:
6260                 method = "PySequence_Contains"
6261             if self.type.is_pyobject:
6262                 error_clause = code.error_goto_if_null
6263                 got_ref = "__Pyx_XGOTREF(%s); " % result_code
6264             else:
6265                 error_clause = code.error_goto_if_neg
6266                 got_ref = ""
6267             code.putln(
6268                 "%s = %s(%s(%s(%s, %s))); %s%s" % (
6269                     result_code,
6270                     coerce_result,
6271                     negation,
6272                     method,
6273                     operand2.py_result(), 
6274                     operand1.py_result(), 
6275                     got_ref,
6276                     error_clause(result_code, self.pos)))
6277         elif (operand1.type.is_pyobject
6278             and op not in ('is', 'is_not')):
6279                 code.putln("%s = PyObject_RichCompare(%s, %s, %s); %s" % (
6280                         result_code, 
6281                         operand1.py_result(), 
6282                         operand2.py_result(), 
6283                         richcmp_constants[op],
6284                         code.error_goto_if_null(result_code, self.pos)))
6285                 code.put_gotref(result_code)
6286         elif operand1.type.is_complex:
6287             if op == "!=": 
6288                 negation = "!"
6289             else: 
6290                 negation = ""
6291             code.putln("%s = %s(%s%s(%s, %s));" % (
6292                 result_code, 
6293                 coerce_result,
6294                 negation,
6295                 operand1.type.unary_op('eq'), 
6296                 operand1.result(), 
6297                 operand2.result()))
6298         else:
6299             type1 = operand1.type
6300             type2 = operand2.type
6301             if (type1.is_extension_type or type2.is_extension_type) \
6302                     and not type1.same_as(type2):
6303                 common_type = py_object_type
6304             elif type1.is_numeric:
6305                 common_type = PyrexTypes.widest_numeric_type(type1, type2)
6306             else:
6307                 common_type = type1
6308             code1 = operand1.result_as(common_type)
6309             code2 = operand2.result_as(common_type)
6310             code.putln("%s = %s(%s %s %s);" % (
6311                 result_code, 
6312                 coerce_result, 
6313                 code1, 
6314                 self.c_operator(op), 
6315                 code2))
6316
6317     def c_operator(self, op):
6318         if op == 'is':
6319             return "=="
6320         elif op == 'is_not':
6321             return "!="
6322         else:
6323             return op
6324     
6325 contains_utility_code = UtilityCode(
6326 proto="""
6327 static CYTHON_INLINE long __Pyx_NegateNonNeg(long b) { return unlikely(b < 0) ? b : !b; }
6328 static CYTHON_INLINE PyObject* __Pyx_PyBoolOrNull_FromLong(long b) {
6329     return unlikely(b < 0) ? NULL : __Pyx_PyBool_FromLong(b);
6330 }
6331 """)
6332
6333 char_in_bytes_utility_code = UtilityCode(
6334 proto="""
6335 static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); /*proto*/
6336 """,
6337 impl="""
6338 static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) {
6339     const Py_ssize_t length = PyBytes_GET_SIZE(bytes);
6340     char* char_start = PyBytes_AS_STRING(bytes);
6341     char* pos;
6342     for (pos=char_start; pos < char_start+length; pos++) {
6343         if (character == pos[0]) return 1;
6344     }
6345     return 0;
6346 }
6347 """)
6348
6349 pyunicode_in_unicode_utility_code = UtilityCode(
6350 proto="""
6351 static CYTHON_INLINE int __Pyx_UnicodeContains(PyObject* unicode, Py_UNICODE character); /*proto*/
6352 """,
6353 impl="""
6354 static CYTHON_INLINE int __Pyx_UnicodeContains(PyObject* unicode, Py_UNICODE character) {
6355     const Py_ssize_t length = PyUnicode_GET_SIZE(unicode);
6356     Py_UNICODE* char_start = PyUnicode_AS_UNICODE(unicode);
6357     Py_UNICODE* pos;
6358     for (pos=char_start; pos < char_start+length; pos++) {
6359         if (character == pos[0]) return 1;
6360     }
6361     return 0;
6362 }
6363 """)
6364
6365 pyunicode_equals_utility_code = UtilityCode(
6366 proto="""
6367 static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/
6368 """,
6369 impl="""
6370 static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) {
6371     if (s1 == s2) {   /* as done by PyObject_RichCompareBool(); also catches the (interned) empty string */
6372         return (equals == Py_EQ);
6373     } else if (PyUnicode_CheckExact(s1) & PyUnicode_CheckExact(s2)) {
6374         if (PyUnicode_GET_SIZE(s1) != PyUnicode_GET_SIZE(s2)) {
6375             return (equals == Py_NE);
6376         } else if (PyUnicode_GET_SIZE(s1) == 1) {
6377             if (equals == Py_EQ)
6378                 return (PyUnicode_AS_UNICODE(s1)[0] == PyUnicode_AS_UNICODE(s2)[0]);
6379             else
6380                 return (PyUnicode_AS_UNICODE(s1)[0] != PyUnicode_AS_UNICODE(s2)[0]);
6381         } else {
6382             int result = PyUnicode_Compare(s1, s2);
6383             if ((result == -1) && unlikely(PyErr_Occurred()))
6384                 return -1;
6385             return (equals == Py_EQ) ? (result == 0) : (result != 0);
6386         }
6387     } else if ((s1 == Py_None) & (s2 == Py_None)) {
6388         return (equals == Py_EQ);
6389     } else if ((s1 == Py_None) & PyUnicode_CheckExact(s2)) {
6390         return (equals == Py_NE);
6391     } else if ((s2 == Py_None) & PyUnicode_CheckExact(s1)) {
6392         return (equals == Py_NE);
6393     } else {
6394         int result;
6395         PyObject* py_result = PyObject_RichCompare(s1, s2, equals);
6396         if (!py_result)
6397             return -1;
6398         result = __Pyx_PyObject_IsTrue(py_result);
6399         Py_DECREF(py_result);
6400         return result;
6401     }
6402 }
6403 """)
6404
6405
6406 class PrimaryCmpNode(ExprNode, CmpNode):
6407     #  Non-cascaded comparison or first comparison of
6408     #  a cascaded sequence.
6409     #
6410     #  operator      string
6411     #  operand1      ExprNode
6412     #  operand2      ExprNode
6413     #  cascade       CascadedCmpNode
6414     
6415     #  We don't use the subexprs mechanism, because
6416     #  things here are too complicated for it to handle.
6417     #  Instead, we override all the framework methods
6418     #  which use it.
6419     
6420     child_attrs = ['operand1', 'operand2', 'cascade']
6421     
6422     cascade = None
6423
6424     def infer_type(self, env):
6425         # TODO: Actually implement this (after merging with -unstable).
6426         return py_object_type
6427
6428     def type_dependencies(self, env):
6429         return ()
6430
6431     def calculate_constant_result(self):
6432         self.calculate_cascaded_constant_result(self.operand1.constant_result)
6433     
6434     def compile_time_value(self, denv):
6435         operand1 = self.operand1.compile_time_value(denv)
6436         return self.cascaded_compile_time_value(operand1, denv)
6437
6438     def analyse_types(self, env):
6439         self.operand1.analyse_types(env)
6440         self.operand2.analyse_types(env)
6441         if self.is_cpp_comparison():
6442             self.analyse_cpp_comparison(env)
6443             if self.cascade:
6444                 error(self.pos, "Cascading comparison not yet supported for cpp types.")
6445             return
6446         if self.cascade:
6447             self.cascade.analyse_types(env)
6448
6449         if self.operator in ('in', 'not_in'):
6450             if self.is_c_string_contains():
6451                 self.is_pycmp = False
6452                 common_type = None
6453                 if self.cascade:
6454                     error(self.pos, "Cascading comparison not yet supported for 'int_val in string'.")
6455                     return
6456                 if self.operand2.type is unicode_type:
6457                     env.use_utility_code(pyunicode_in_unicode_utility_code)
6458                 else:
6459                     if self.operand1.type is PyrexTypes.c_uchar_type:
6460                         self.operand1 = self.operand1.coerce_to(PyrexTypes.c_char_type, env)
6461                     if self.operand2.type is not bytes_type:
6462                         self.operand2 = self.operand2.coerce_to(bytes_type, env)
6463                     env.use_utility_code(char_in_bytes_utility_code)
6464                 self.operand2 = self.operand2.as_none_safe_node(
6465                     "argument of type 'NoneType' is not iterable")
6466             elif self.is_ptr_contains():
6467                 if self.cascade:
6468                     error(self.pos, "Cascading comparison not yet supported for 'val in sliced pointer'.")
6469                 self.type = PyrexTypes.c_bint_type
6470                 # Will be transformed by IterationTransform
6471                 return
6472             else:
6473                 if self.operand2.type is dict_type:
6474                     self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
6475                 common_type = py_object_type
6476                 self.is_pycmp = True
6477         elif self.find_special_bool_compare_function(env):
6478             common_type = None # if coercion needed, the method call above has already done it
6479             self.is_pycmp = False # result is bint
6480             self.is_temp = True # must check for error return
6481         else:
6482             common_type = self.find_common_type(env, self.operator, self.operand1)
6483             self.is_pycmp = common_type.is_pyobject
6484
6485         if common_type is not None and not common_type.is_error:
6486             if self.operand1.type != common_type:
6487                 self.operand1 = self.operand1.coerce_to(common_type, env)
6488             self.coerce_operands_to(common_type, env)
6489
6490         if self.cascade:
6491             self.operand2 = self.operand2.coerce_to_simple(env)
6492             self.cascade.coerce_cascaded_operands_to_temp(env)
6493         if self.is_python_result():
6494             self.type = PyrexTypes.py_object_type
6495         else:
6496             self.type = PyrexTypes.c_bint_type
6497         cdr = self.cascade
6498         while cdr:
6499             cdr.type = self.type
6500             cdr = cdr.cascade
6501         if self.is_pycmp or self.cascade:
6502             self.is_temp = 1
6503     
6504     def analyse_cpp_comparison(self, env):
6505         type1 = self.operand1.type
6506         type2 = self.operand2.type
6507         entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
6508         if entry is None:
6509             error(self.pos, "Invalid types for '%s' (%s, %s)" %
6510                 (self.operator, type1, type2))
6511             self.type = PyrexTypes.error_type
6512             self.result_code = "<error>"
6513             return
6514         func_type = entry.type
6515         if func_type.is_ptr:
6516             func_type = func_type.base_type
6517         if len(func_type.args) == 1:
6518             self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
6519         else:
6520             self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
6521             self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
6522         self.type = func_type.return_type
6523     
6524     def has_python_operands(self):
6525         return (self.operand1.type.is_pyobject
6526             or self.operand2.type.is_pyobject)
6527     
6528     def check_const(self):
6529         if self.cascade:
6530             self.not_const()
6531             return False
6532         else:
6533             return self.operand1.check_const() and self.operand2.check_const()
6534
6535     def calculate_result_code(self):
6536         if self.operand1.type.is_complex:
6537             if self.operator == "!=":
6538                 negation = "!"
6539             else:
6540                 negation = ""
6541             return "(%s%s(%s, %s))" % (
6542                 negation,
6543                 self.operand1.type.binary_op('=='), 
6544                 self.operand1.result(), 
6545                 self.operand2.result())
6546         elif self.is_c_string_contains():
6547             if self.operand2.type is bytes_type:
6548                 method = "__Pyx_BytesContains"
6549             else:
6550                 method = "__Pyx_UnicodeContains"
6551             if self.operator == "not_in":
6552                 negation = "!"
6553             else:
6554                 negation = ""
6555             return "(%s%s(%s, %s))" % (
6556                 negation,
6557                 method,
6558                 self.operand2.result(), 
6559                 self.operand1.result())
6560         else:
6561             return "(%s %s %s)" % (
6562                 self.operand1.result(),
6563                 self.c_operator(self.operator),
6564                 self.operand2.result())
6565
6566     def generate_evaluation_code(self, code):
6567         self.operand1.generate_evaluation_code(code)
6568         self.operand2.generate_evaluation_code(code)
6569         if self.is_temp:
6570             self.allocate_temp_result(code)
6571             self.generate_operation_code(code, self.result(), 
6572                 self.operand1, self.operator, self.operand2)
6573             if self.cascade:
6574                 self.cascade.generate_evaluation_code(code,
6575                     self.result(), self.operand2)
6576             self.operand1.generate_disposal_code(code)
6577             self.operand1.free_temps(code)
6578             self.operand2.generate_disposal_code(code)
6579             self.operand2.free_temps(code)
6580
6581     def generate_subexpr_disposal_code(self, code):
6582         #  If this is called, it is a non-cascaded cmp,
6583         #  so only need to dispose of the two main operands.
6584         self.operand1.generate_disposal_code(code)
6585         self.operand2.generate_disposal_code(code)
6586         
6587     def free_subexpr_temps(self, code):
6588         #  If this is called, it is a non-cascaded cmp,
6589         #  so only need to dispose of the two main operands.
6590         self.operand1.free_temps(code)
6591         self.operand2.free_temps(code)
6592         
6593     def annotate(self, code):
6594         self.operand1.annotate(code)
6595         self.operand2.annotate(code)
6596         if self.cascade:
6597             self.cascade.annotate(code)
6598
6599
6600 class CascadedCmpNode(Node, CmpNode):
6601     #  A CascadedCmpNode is not a complete expression node. It 
6602     #  hangs off the side of another comparison node, shares 
6603     #  its left operand with that node, and shares its result 
6604     #  with the PrimaryCmpNode at the head of the chain.
6605     #
6606     #  operator      string
6607     #  operand2      ExprNode
6608     #  cascade       CascadedCmpNode
6609
6610     child_attrs = ['operand2', 'cascade']
6611
6612     cascade = None
6613     constant_result = constant_value_not_set # FIXME: where to calculate this?
6614
6615     def infer_type(self, env):
6616         # TODO: Actually implement this (after merging with -unstable).
6617         return py_object_type
6618
6619     def type_dependencies(self, env):
6620         return ()
6621
6622     def has_constant_result(self):
6623         return self.constant_result is not constant_value_not_set and \
6624                self.constant_result is not not_a_constant
6625
6626     def analyse_types(self, env):
6627         self.operand2.analyse_types(env)
6628         if self.cascade:
6629             self.cascade.analyse_types(env)
6630
6631     def has_python_operands(self):
6632         return self.operand2.type.is_pyobject
6633         
6634     def coerce_operands_to_pyobjects(self, env):
6635         self.operand2 = self.operand2.coerce_to_pyobject(env)
6636         if self.operand2.type is dict_type and self.operator in ('in', 'not_in'):
6637             self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
6638         if self.cascade:
6639             self.cascade.coerce_operands_to_pyobjects(env)
6640
6641     def coerce_cascaded_operands_to_temp(self, env):
6642         if self.cascade:
6643             #self.operand2 = self.operand2.coerce_to_temp(env) #CTT
6644             self.operand2 = self.operand2.coerce_to_simple(env)
6645             self.cascade.coerce_cascaded_operands_to_temp(env)
6646     
6647     def generate_evaluation_code(self, code, result, operand1):
6648         if self.type.is_pyobject:
6649             code.putln("if (__Pyx_PyObject_IsTrue(%s)) {" % result)
6650             code.put_decref(result, self.type)
6651         else:
6652             code.putln("if (%s) {" % result)
6653         self.operand2.generate_evaluation_code(code)
6654         self.generate_operation_code(code, result, 
6655             operand1, self.operator, self.operand2)
6656         if self.cascade:
6657             self.cascade.generate_evaluation_code(
6658                 code, result, self.operand2)
6659         # Cascaded cmp result is always temp
6660         self.operand2.generate_disposal_code(code)
6661         self.operand2.free_temps(code)
6662         code.putln("}")
6663
6664     def annotate(self, code):
6665         self.operand2.annotate(code)
6666         if self.cascade:
6667             self.cascade.annotate(code)
6668
6669
6670 binop_node_classes = {
6671     "or":       BoolBinopNode,
6672     "and":      BoolBinopNode,
6673     "|":        IntBinopNode,
6674     "^":        IntBinopNode,
6675     "&":        IntBinopNode,
6676     "<<":       IntBinopNode,
6677     ">>":       IntBinopNode,
6678     "+":        AddNode,
6679     "-":        SubNode,
6680     "*":        MulNode,
6681     "/":        DivNode,
6682     "//":       DivNode,
6683     "%":        ModNode,
6684     "**":       PowNode
6685 }
6686
6687 def binop_node(pos, operator, operand1, operand2, inplace=False):
6688     # Construct binop node of appropriate class for 
6689     # given operator.
6690     return binop_node_classes[operator](pos, 
6691         operator = operator, 
6692         operand1 = operand1, 
6693         operand2 = operand2,
6694         inplace = inplace)
6695
6696 #-------------------------------------------------------------------
6697 #
6698 #  Coercion nodes
6699 #
6700 #  Coercion nodes are special in that they are created during
6701 #  the analyse_types phase of parse tree processing.
6702 #  Their __init__ methods consequently incorporate some aspects
6703 #  of that phase.
6704 #
6705 #-------------------------------------------------------------------
6706
6707 class CoercionNode(ExprNode):
6708     #  Abstract base class for coercion nodes.
6709     #
6710     #  arg       ExprNode       node being coerced
6711     
6712     subexprs = ['arg']
6713     constant_result = not_a_constant
6714     
6715     def __init__(self, arg):
6716         self.pos = arg.pos
6717         self.arg = arg
6718         if debug_coercion:
6719             print("%s Coercing %s" % (self, self.arg))
6720
6721     def calculate_constant_result(self):
6722         # constant folding can break type coercion, so this is disabled
6723         pass
6724             
6725     def annotate(self, code):
6726         self.arg.annotate(code)
6727         if self.arg.type != self.type:
6728             file, line, col = self.pos
6729             code.annotate((file, line, col-1), AnnotationItem(style='coerce', tag='coerce', text='[%s] to [%s]' % (self.arg.type, self.type)))
6730
6731
6732 class CastNode(CoercionNode):
6733     #  Wrap a node in a C type cast.
6734     
6735     def __init__(self, arg, new_type):
6736         CoercionNode.__init__(self, arg)
6737         self.type = new_type
6738
6739     def may_be_none(self):
6740         return self.arg.may_be_none()
6741     
6742     def calculate_result_code(self):
6743         return self.arg.result_as(self.type)
6744
6745     def generate_result_code(self, code):
6746         self.arg.generate_result_code(code)
6747
6748
6749 class PyTypeTestNode(CoercionNode):
6750     #  This node is used to check that a generic Python
6751     #  object is an instance of a particular extension type.
6752     #  This node borrows the result of its argument node.
6753
6754     def __init__(self, arg, dst_type, env, notnone=False):
6755         #  The arg is know to be a Python object, and
6756         #  the dst_type is known to be an extension type.
6757         assert dst_type.is_extension_type or dst_type.is_builtin_type, "PyTypeTest on non extension type"
6758         CoercionNode.__init__(self, arg)
6759         self.type = dst_type
6760         self.result_ctype = arg.ctype()
6761         self.notnone = notnone
6762
6763     nogil_check = Node.gil_error
6764     gil_message = "Python type test"
6765     
6766     def analyse_types(self, env):
6767         pass
6768
6769     def may_be_none(self):
6770         if self.notnone:
6771             return False
6772         return self.arg.may_be_none()
6773     
6774     def result_in_temp(self):
6775         return self.arg.result_in_temp()
6776     
6777     def is_ephemeral(self):
6778         return self.arg.is_ephemeral()
6779
6780     def calculate_constant_result(self):
6781         # FIXME
6782         pass
6783
6784     def calculate_result_code(self):
6785         return self.arg.result()
6786     
6787     def generate_result_code(self, code):
6788         if self.type.typeobj_is_available():
6789             if not self.type.is_builtin_type:
6790                 code.globalstate.use_utility_code(type_test_utility_code)
6791             code.putln(
6792                 "if (!(%s)) %s" % (
6793                     self.type.type_test_code(self.arg.py_result(), self.notnone),
6794                     code.error_goto(self.pos)))
6795         else:
6796             error(self.pos, "Cannot test type of extern C class "
6797                 "without type object name specification")
6798                 
6799     def generate_post_assignment_code(self, code):
6800         self.arg.generate_post_assignment_code(code)
6801
6802     def free_temps(self, code):
6803         self.arg.free_temps(code)
6804
6805
6806 class NoneCheckNode(CoercionNode):
6807     # This node is used to check that a Python object is not None and
6808     # raises an appropriate exception (as specified by the creating
6809     # transform).
6810
6811     def __init__(self, arg, exception_type_cname, exception_message):
6812         CoercionNode.__init__(self, arg)
6813         self.type = arg.type
6814         self.result_ctype = arg.ctype()
6815         self.exception_type_cname = exception_type_cname
6816         self.exception_message = exception_message
6817
6818     def analyse_types(self, env):
6819         pass
6820
6821     def may_be_none(self):
6822         return False
6823
6824     def result_in_temp(self):
6825         return self.arg.result_in_temp()
6826
6827     def calculate_result_code(self):
6828         return self.arg.result()
6829     
6830     def generate_result_code(self, code):
6831         code.putln(
6832             "if (unlikely(%s == Py_None)) {" % self.arg.result())
6833         code.putln('PyErr_SetString(%s, "%s"); %s ' % (
6834             self.exception_type_cname,
6835             StringEncoding.escape_byte_string(
6836                 self.exception_message.encode('UTF-8')),
6837             code.error_goto(self.pos)))
6838         code.putln("}")
6839
6840     def generate_post_assignment_code(self, code):
6841         self.arg.generate_post_assignment_code(code)
6842
6843     def free_temps(self, code):
6844         self.arg.free_temps(code)
6845
6846
6847 class CoerceToPyTypeNode(CoercionNode):
6848     #  This node is used to convert a C data type
6849     #  to a Python object.
6850     
6851     type = py_object_type
6852     is_temp = 1
6853
6854     def __init__(self, arg, env, type=py_object_type):
6855         CoercionNode.__init__(self, arg)
6856         if not arg.type.create_to_py_utility_code(env):
6857             error(arg.pos,
6858                   "Cannot convert '%s' to Python object" % arg.type)
6859         if type is not py_object_type:
6860             self.type = py_object_type
6861         elif arg.type.is_string:
6862             self.type = bytes_type
6863         elif arg.type is PyrexTypes.c_py_unicode_type:
6864             self.type = unicode_type
6865
6866     gil_message = "Converting to Python object"
6867
6868     def may_be_none(self):
6869         # FIXME: is this always safe?
6870         return False
6871
6872     def coerce_to_boolean(self, env):
6873         arg_type = self.arg.type
6874         if (arg_type == PyrexTypes.c_bint_type or
6875             (arg_type.is_pyobject and arg_type.name == 'bool')):
6876             return self.arg.coerce_to_temp(env)
6877         else:
6878             return CoerceToBooleanNode(self, env)
6879     
6880     def coerce_to_integer(self, env):
6881         # If not already some C integer type, coerce to longint.
6882         if self.arg.type.is_int:
6883             return self.arg
6884         else:
6885             return self.arg.coerce_to(PyrexTypes.c_long_type, env)
6886
6887     def analyse_types(self, env):
6888         # The arg is always already analysed
6889         pass
6890
6891     def generate_result_code(self, code):
6892         function = self.arg.type.to_py_function
6893         code.putln('%s = %s(%s); %s' % (
6894             self.result(), 
6895             function, 
6896             self.arg.result(), 
6897             code.error_goto_if_null(self.result(), self.pos)))
6898         code.put_gotref(self.py_result())
6899
6900
6901 class CoerceIntToBytesNode(CoerceToPyTypeNode):
6902     #  This node is used to convert a C int type to a Python bytes
6903     #  object.
6904
6905     is_temp = 1
6906
6907     def __init__(self, arg, env):
6908         arg = arg.coerce_to_simple(env)
6909         CoercionNode.__init__(self, arg)
6910         self.type = Builtin.bytes_type
6911
6912     def generate_result_code(self, code):
6913         arg = self.arg
6914         arg_result = arg.result()
6915         if arg.type not in (PyrexTypes.c_char_type,
6916                             PyrexTypes.c_uchar_type,
6917                             PyrexTypes.c_schar_type):
6918             if arg.type.signed:
6919                 code.putln("if ((%s < 0) || (%s > 255)) {" % (
6920                     arg_result, arg_result))
6921             else:
6922                 code.putln("if (%s > 255) {" % arg_result)
6923             code.putln('PyErr_Format(PyExc_OverflowError, '
6924                        '"value too large to pack into a byte"); %s' % (
6925                            code.error_goto(self.pos)))
6926             code.putln('}')
6927         temp = None
6928         if arg.type is not PyrexTypes.c_char_type:
6929             temp = code.funcstate.allocate_temp(PyrexTypes.c_char_type, manage_ref=False)
6930             code.putln("%s = (char)%s;" % (temp, arg_result))
6931             arg_result = temp
6932         code.putln('%s = PyBytes_FromStringAndSize(&%s, 1); %s' % (
6933             self.result(),
6934             arg_result,
6935             code.error_goto_if_null(self.result(), self.pos)))
6936         if temp is not None:
6937             code.funcstate.release_temp(temp)
6938         code.put_gotref(self.py_result())
6939
6940
6941 class CoerceFromPyTypeNode(CoercionNode):
6942     #  This node is used to convert a Python object
6943     #  to a C data type.
6944
6945     def __init__(self, result_type, arg, env):
6946         CoercionNode.__init__(self, arg)
6947         self.type = result_type
6948         self.is_temp = 1
6949         if not result_type.create_from_py_utility_code(env):
6950             error(arg.pos,
6951                   "Cannot convert Python object to '%s'" % result_type)
6952         if self.type.is_string and self.arg.is_ephemeral():
6953             error(arg.pos,
6954                   "Obtaining char * from temporary Python value")
6955     
6956     def analyse_types(self, env):
6957         # The arg is always already analysed
6958         pass
6959
6960     def generate_result_code(self, code):
6961         function = self.type.from_py_function
6962         operand = self.arg.py_result()
6963         rhs = "%s(%s)" % (function, operand)
6964         if self.type.is_enum:
6965             rhs = typecast(self.type, c_long_type, rhs)
6966         code.putln('%s = %s; %s' % (
6967             self.result(), 
6968             rhs,
6969             code.error_goto_if(self.type.error_condition(self.result()), self.pos)))
6970         if self.type.is_pyobject:
6971             code.put_gotref(self.py_result())
6972
6973
6974 class CoerceToBooleanNode(CoercionNode):
6975     #  This node is used when a result needs to be used
6976     #  in a boolean context.
6977     
6978     type = PyrexTypes.c_bint_type
6979
6980     _special_builtins = {
6981         Builtin.list_type    : 'PyList_GET_SIZE',
6982         Builtin.tuple_type   : 'PyTuple_GET_SIZE',
6983         Builtin.bytes_type   : 'PyBytes_GET_SIZE',
6984         Builtin.unicode_type : 'PyUnicode_GET_SIZE',
6985         }
6986
6987     def __init__(self, arg, env):
6988         CoercionNode.__init__(self, arg)
6989         if arg.type.is_pyobject:
6990             self.is_temp = 1
6991
6992     def nogil_check(self, env):
6993         if self.arg.type.is_pyobject and self._special_builtins.get(self.arg.type) is None:
6994             self.gil_error()
6995
6996     gil_message = "Truth-testing Python object"
6997     
6998     def check_const(self):
6999         if self.is_temp:
7000             self.not_const()
7001             return False
7002         return self.arg.check_const()
7003     
7004     def calculate_result_code(self):
7005         return "(%s != 0)" % self.arg.result()
7006
7007     def generate_result_code(self, code):
7008         if not self.is_temp:
7009             return
7010         test_func = self._special_builtins.get(self.arg.type)
7011         if test_func is not None:
7012             code.putln("%s = (%s != Py_None) && (%s(%s) != 0);" % (
7013                        self.result(),
7014                        self.arg.py_result(),
7015                        test_func,
7016                        self.arg.py_result()))
7017         else:
7018             code.putln(
7019                 "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
7020                     self.result(), 
7021                     self.arg.py_result(), 
7022                     code.error_goto_if_neg(self.result(), self.pos)))
7023
7024 class CoerceToComplexNode(CoercionNode):
7025
7026     def __init__(self, arg, dst_type, env):
7027         if arg.type.is_complex:
7028             arg = arg.coerce_to_simple(env)
7029         self.type = dst_type
7030         CoercionNode.__init__(self, arg)
7031         dst_type.create_declaration_utility_code(env)
7032
7033     def calculate_result_code(self):
7034         if self.arg.type.is_complex:
7035             real_part = "__Pyx_CREAL(%s)" % self.arg.result()
7036             imag_part = "__Pyx_CIMAG(%s)" % self.arg.result()
7037         else:
7038             real_part = self.arg.result()
7039             imag_part = "0"
7040         return "%s(%s, %s)" % (
7041                 self.type.from_parts,
7042                 real_part,
7043                 imag_part)
7044     
7045     def generate_result_code(self, code):
7046         pass
7047
7048 class CoerceToTempNode(CoercionNode):
7049     #  This node is used to force the result of another node
7050     #  to be stored in a temporary. It is only used if the
7051     #  argument node's result is not already in a temporary.
7052
7053     def __init__(self, arg, env):
7054         CoercionNode.__init__(self, arg)
7055         self.type = self.arg.type
7056         self.constant_result = self.arg.constant_result
7057         self.is_temp = 1
7058         if self.type.is_pyobject:
7059             self.result_ctype = py_object_type
7060
7061     gil_message = "Creating temporary Python reference"
7062
7063     def analyse_types(self, env):
7064         # The arg is always already analysed
7065         pass
7066         
7067     def coerce_to_boolean(self, env):
7068         self.arg = self.arg.coerce_to_boolean(env)
7069         if self.arg.is_simple():
7070             return self.arg
7071         self.type = self.arg.type
7072         self.result_ctype = self.type
7073         return self
7074
7075     def generate_result_code(self, code):
7076         #self.arg.generate_evaluation_code(code) # Already done
7077         # by generic generate_subexpr_evaluation_code!
7078         code.putln("%s = %s;" % (
7079             self.result(), self.arg.result_as(self.ctype())))
7080         if self.type.is_pyobject and self.use_managed_ref:
7081             code.put_incref(self.result(), self.ctype())
7082
7083
7084 class CloneNode(CoercionNode):
7085     #  This node is employed when the result of another node needs
7086     #  to be used multiple times. The argument node's result must
7087     #  be in a temporary. This node "borrows" the result from the
7088     #  argument node, and does not generate any evaluation or
7089     #  disposal code for it. The original owner of the argument 
7090     #  node is responsible for doing those things.
7091     
7092     subexprs = [] # Arg is not considered a subexpr
7093     nogil_check = None
7094     
7095     def __init__(self, arg):
7096         CoercionNode.__init__(self, arg)
7097         if hasattr(arg, 'type'):
7098             self.type = arg.type
7099             self.result_ctype = arg.result_ctype
7100         if hasattr(arg, 'entry'):
7101             self.entry = arg.entry
7102             
7103     def result(self):
7104         return self.arg.result()
7105     
7106     def type_dependencies(self, env):
7107         return self.arg.type_dependencies(env)
7108     
7109     def infer_type(self, env):
7110         return self.arg.infer_type(env)
7111
7112     def analyse_types(self, env):
7113         self.type = self.arg.type
7114         self.result_ctype = self.arg.result_ctype
7115         self.is_temp = 1
7116         if hasattr(self.arg, 'entry'):
7117             self.entry = self.arg.entry
7118     
7119     def generate_evaluation_code(self, code):
7120         pass
7121
7122     def generate_result_code(self, code):
7123         pass
7124         
7125     def generate_disposal_code(self, code):
7126         pass
7127                 
7128     def free_temps(self, code):
7129         pass
7130
7131
7132 class ModuleRefNode(ExprNode):
7133     # Simple returns the module object
7134     
7135     type = py_object_type
7136     is_temp = False
7137     subexprs = []
7138     
7139     def analyse_types(self, env):
7140         pass
7141
7142     def may_be_none(self):
7143         return False
7144
7145     def calculate_result_code(self):
7146         return Naming.module_cname
7147
7148     def generate_result_code(self, code):
7149         pass
7150
7151 class DocstringRefNode(ExprNode):
7152     # Extracts the docstring of the body element
7153     
7154     subexprs = ['body']
7155     type = py_object_type
7156     is_temp = True
7157     
7158     def __init__(self, pos, body):
7159         ExprNode.__init__(self, pos)
7160         assert body.type.is_pyobject
7161         self.body = body
7162
7163     def analyse_types(self, env):
7164         pass
7165
7166     def generate_result_code(self, code):
7167         code.putln('%s = __Pyx_GetAttrString(%s, "__doc__"); %s' % (
7168             self.result(), self.body.result(),
7169             code.error_goto_if_null(self.result(), self.pos)))
7170         code.put_gotref(self.result())
7171
7172
7173
7174 #------------------------------------------------------------------------------------
7175 #
7176 #  Runtime support code
7177 #
7178 #------------------------------------------------------------------------------------
7179
7180 get_name_interned_utility_code = UtilityCode(
7181 proto = """
7182 static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
7183 """,
7184 impl = """
7185 static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
7186     PyObject *result;
7187     result = PyObject_GetAttr(dict, name);
7188     if (!result)
7189         PyErr_SetObject(PyExc_NameError, name);
7190     return result;
7191 }
7192 """)
7193
7194 #------------------------------------------------------------------------------------
7195
7196 import_utility_code = UtilityCode(
7197 proto = """
7198 static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/
7199 """,
7200 impl = """
7201 static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) {
7202     PyObject *py_import = 0;
7203     PyObject *empty_list = 0;
7204     PyObject *module = 0;
7205     PyObject *global_dict = 0;
7206     PyObject *empty_dict = 0;
7207     PyObject *list;
7208     py_import = __Pyx_GetAttrString(%(BUILTINS)s, "__import__");
7209     if (!py_import)
7210         goto bad;
7211     if (from_list)
7212         list = from_list;
7213     else {
7214         empty_list = PyList_New(0);
7215         if (!empty_list)
7216             goto bad;
7217         list = empty_list;
7218     }
7219     global_dict = PyModule_GetDict(%(GLOBALS)s);
7220     if (!global_dict)
7221         goto bad;
7222     empty_dict = PyDict_New();
7223     if (!empty_dict)
7224         goto bad;
7225     module = PyObject_CallFunctionObjArgs(py_import,
7226         name, global_dict, empty_dict, list, NULL);
7227 bad:
7228     Py_XDECREF(empty_list);
7229     Py_XDECREF(py_import);
7230     Py_XDECREF(empty_dict);
7231     return module;
7232 }
7233 """ % {
7234     "BUILTINS": Naming.builtins_cname,
7235     "GLOBALS":  Naming.module_cname,
7236 })
7237
7238 #------------------------------------------------------------------------------------
7239
7240 get_exception_utility_code = UtilityCode(
7241 proto = """
7242 static PyObject *__Pyx_GetExcValue(void); /*proto*/
7243 """,
7244 impl = """
7245 static PyObject *__Pyx_GetExcValue(void) {
7246     PyObject *type = 0, *value = 0, *tb = 0;
7247     PyObject *tmp_type, *tmp_value, *tmp_tb;
7248     PyObject *result = 0;
7249     PyThreadState *tstate = PyThreadState_Get();
7250     PyErr_Fetch(&type, &value, &tb);
7251     PyErr_NormalizeException(&type, &value, &tb);
7252     if (PyErr_Occurred())
7253         goto bad;
7254     if (!value) {
7255         value = Py_None;
7256         Py_INCREF(value);
7257     }
7258     tmp_type = tstate->exc_type;
7259     tmp_value = tstate->exc_value;
7260     tmp_tb = tstate->exc_traceback;
7261     tstate->exc_type = type;
7262     tstate->exc_value = value;
7263     tstate->exc_traceback = tb;
7264     /* Make sure tstate is in a consistent state when we XDECREF
7265     these objects (XDECREF may run arbitrary code). */
7266     Py_XDECREF(tmp_type);
7267     Py_XDECREF(tmp_value);
7268     Py_XDECREF(tmp_tb);
7269     result = value;
7270     Py_XINCREF(result);
7271     type = 0;
7272     value = 0;
7273     tb = 0;
7274 bad:
7275     Py_XDECREF(type);
7276     Py_XDECREF(value);
7277     Py_XDECREF(tb);
7278     return result;
7279 }
7280 """)
7281
7282 #------------------------------------------------------------------------------------
7283
7284 type_test_utility_code = UtilityCode(
7285 proto = """
7286 static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/
7287 """,
7288 impl = """
7289 static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) {
7290     if (unlikely(!type)) {
7291         PyErr_Format(PyExc_SystemError, "Missing type object");
7292         return 0;
7293     }
7294     if (likely(PyObject_TypeCheck(obj, type)))
7295         return 1;
7296     PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s",
7297                  Py_TYPE(obj)->tp_name, type->tp_name);
7298     return 0;
7299 }
7300 """)
7301
7302 #------------------------------------------------------------------------------------
7303
7304 create_class_utility_code = UtilityCode(
7305 proto = """
7306 static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name,
7307                                    PyObject *modname, PyObject *kwargs); /*proto*/
7308 static int __Pyx_PrepareClass(PyObject *metaclass, PyObject *bases, PyObject *name,
7309                               PyObject *mkw, PyObject *dict); /*proto*/
7310 """,
7311 impl = """
7312 static int __Pyx_PrepareClass(PyObject *metaclass, PyObject *bases, PyObject *name,
7313                               PyObject *mkw, PyObject *dict) {
7314     PyObject *prep;
7315     PyObject *pargs;
7316     PyObject *ns;
7317
7318     prep = PyObject_GetAttrString(metaclass, "__prepare__");
7319     if (prep == NULL) {
7320         if (!PyErr_ExceptionMatches(PyExc_AttributeError))
7321             return -1;
7322         PyErr_Clear();
7323         return 0;
7324     }
7325     pargs = PyTuple_New(2);
7326     if (!pargs) {
7327         Py_DECREF(prep);
7328         return -1;
7329     }
7330     Py_INCREF(name);
7331     Py_INCREF(bases);
7332     PyTuple_SET_ITEM(pargs, 0, name);
7333     PyTuple_SET_ITEM(pargs, 1, bases);
7334     ns = PyEval_CallObjectWithKeywords(prep, pargs, mkw);
7335     Py_DECREF(pargs);
7336     Py_DECREF(prep);
7337     if (ns == NULL)
7338         return -1;
7339     /* XXX: This is hack, merge namespace back to dict,
7340        __prepare__ should be ran before dict initialization */
7341     if (PyDict_Merge(dict, ns, 0)) {
7342         Py_DECREF(ns);
7343         return -1;
7344     }
7345     Py_DECREF(ns);
7346     return 0;
7347 }
7348
7349 static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name,
7350                                    PyObject *modname, PyObject *kwargs) {
7351     PyObject *result = NULL;
7352     PyObject *metaclass = NULL;
7353     PyObject *mkw = NULL;
7354
7355     if (PyDict_SetItemString(dict, "__module__", modname) < 0)
7356         return NULL;
7357
7358     /* Python3 metaclasses */
7359     if (kwargs) {
7360         mkw = PyDict_Copy(kwargs); /* Don't modify kwargs passed in! */
7361         if (!mkw)
7362             return NULL;
7363         metaclass = PyDict_GetItemString(mkw, "metaclass");
7364         if (metaclass) {
7365             Py_INCREF(metaclass);
7366             if (PyDict_DelItemString(mkw, "metaclass") < 0)
7367                 goto bad;
7368             if (__Pyx_PrepareClass(metaclass, bases, name, mkw, dict))
7369                 goto bad;
7370         }
7371     }
7372     if (!metaclass) {
7373         /* Python2 __metaclass__ */
7374         metaclass = PyDict_GetItemString(dict, "__metaclass__");
7375         if (!metaclass) {
7376             /* Default metaclass */
7377 #if PY_MAJOR_VERSION < 3
7378             if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7379                 PyObject *base = PyTuple_GET_ITEM(bases, 0);
7380                 metaclass = PyObject_GetAttrString(base, "__class__");
7381                 if (!metaclass) {
7382                     PyErr_Clear();
7383                     metaclass = (PyObject *)base->ob_type;
7384                 }
7385             } else
7386                 metaclass = (PyObject *) &PyClass_Type;
7387 #else
7388             if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
7389                 PyObject *base = PyTuple_GET_ITEM(bases, 0);
7390                 metaclass = (PyObject *)base->ob_type;
7391             } else
7392                 metaclass = (PyObject *) &PyType_Type;
7393 #endif
7394         }
7395         Py_INCREF(metaclass);
7396     }
7397     if (mkw && PyDict_Size(mkw) > 0) {
7398         PyObject *margs = PyTuple_New(3);
7399         if (!margs)
7400             goto bad;
7401         Py_INCREF(name);
7402         Py_INCREF(bases);
7403         Py_INCREF(dict);
7404         PyTuple_SET_ITEM(margs, 0, name);
7405         PyTuple_SET_ITEM(margs, 1, bases);
7406         PyTuple_SET_ITEM(margs, 2, dict);
7407         result = PyEval_CallObjectWithKeywords(metaclass, margs, mkw);
7408         Py_DECREF(margs);
7409     } else {
7410         result = PyObject_CallFunctionObjArgs(metaclass, name, bases, dict, NULL);
7411     }
7412 bad:
7413     Py_DECREF(metaclass);
7414     Py_XDECREF(mkw);
7415     return result;
7416 }
7417 """)
7418
7419 #------------------------------------------------------------------------------------
7420
7421 cpp_exception_utility_code = UtilityCode(
7422 proto = """
7423 #ifndef __Pyx_CppExn2PyErr
7424 static void __Pyx_CppExn2PyErr() {
7425   try {
7426     if (PyErr_Occurred())
7427       ; // let the latest Python exn pass through and ignore the current one
7428     else
7429       throw;
7430   } catch (const std::invalid_argument& exn) {
7431     // Catch a handful of different errors here and turn them into the
7432     // equivalent Python errors.
7433     // Change invalid_argument to ValueError
7434     PyErr_SetString(PyExc_ValueError, exn.what());
7435   } catch (const std::out_of_range& exn) {
7436     // Change out_of_range to IndexError
7437     PyErr_SetString(PyExc_IndexError, exn.what());
7438   } catch (const std::exception& exn) {
7439     PyErr_SetString(PyExc_RuntimeError, exn.what());
7440   }
7441   catch (...)
7442   {
7443     PyErr_SetString(PyExc_RuntimeError, "Unknown exception");
7444   }
7445 }
7446 #endif
7447 """,
7448 impl = ""
7449 )
7450
7451 pyerr_occurred_withgil_utility_code= UtilityCode(
7452 proto = """
7453 static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void); /* proto */
7454 """,
7455 impl = """
7456 static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void) {
7457   int err;
7458   #ifdef WITH_THREAD
7459   PyGILState_STATE _save = PyGILState_Ensure();
7460   #endif
7461   err = !!PyErr_Occurred();
7462   #ifdef WITH_THREAD
7463   PyGILState_Release(_save);
7464   #endif
7465   return err;
7466 }
7467 """
7468 )
7469
7470 #------------------------------------------------------------------------------------
7471
7472 raise_noneattr_error_utility_code = UtilityCode(
7473 proto = """
7474 static CYTHON_INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname);
7475 """,
7476 impl = '''
7477 static CYTHON_INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname) {
7478     PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", attrname);
7479 }
7480 ''')
7481
7482 raise_noneindex_error_utility_code = UtilityCode(
7483 proto = """
7484 static CYTHON_INLINE void __Pyx_RaiseNoneIndexingError(void);
7485 """,
7486 impl = '''
7487 static CYTHON_INLINE void __Pyx_RaiseNoneIndexingError(void) {
7488     PyErr_SetString(PyExc_TypeError, "'NoneType' object is unsubscriptable");
7489 }
7490 ''')
7491
7492 raise_none_iter_error_utility_code = UtilityCode(
7493 proto = """
7494 static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void);
7495 """,
7496 impl = '''
7497 static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) {
7498     PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
7499 }
7500 ''')
7501
7502 #------------------------------------------------------------------------------------
7503
7504 getitem_dict_utility_code = UtilityCode(
7505 proto = """
7506 #if PY_MAJOR_VERSION >= 3
7507 static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) {
7508     PyObject *value;
7509     if (unlikely(d == Py_None)) {
7510         __Pyx_RaiseNoneIndexingError();
7511         return NULL;
7512     }
7513     value = PyDict_GetItemWithError(d, key);
7514     if (unlikely(!value)) {
7515         if (!PyErr_Occurred())
7516             PyErr_SetObject(PyExc_KeyError, key);
7517         return NULL;
7518     }
7519     Py_INCREF(value);
7520     return value;
7521 }
7522 #else
7523     #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key)
7524 #endif
7525 """, 
7526 requires = [raise_noneindex_error_utility_code])
7527
7528 #------------------------------------------------------------------------------------
7529
7530 getitem_int_pyunicode_utility_code = UtilityCode(
7531 proto = '''
7532 #define __Pyx_GetItemInt_Unicode(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7533                                                __Pyx_GetItemInt_Unicode_Fast(o, i) : \\
7534                                                __Pyx_GetItemInt_Unicode_Generic(o, to_py_func(i)))
7535
7536 static CYTHON_INLINE Py_UNICODE __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i) {
7537     if (likely((0 <= i) & (i < PyUnicode_GET_SIZE(ustring)))) {
7538         return PyUnicode_AS_UNICODE(ustring)[i];
7539     } else if ((-PyUnicode_GET_SIZE(ustring) <= i) & (i < 0)) {
7540         i += PyUnicode_GET_SIZE(ustring);
7541         return PyUnicode_AS_UNICODE(ustring)[i];
7542     } else {
7543         PyErr_SetString(PyExc_IndexError, "string index out of range");
7544         return (Py_UNICODE)-1;
7545     }
7546 }
7547
7548 static CYTHON_INLINE Py_UNICODE __Pyx_GetItemInt_Unicode_Generic(PyObject* ustring, PyObject* j) {
7549     Py_UNICODE uchar;
7550     PyObject *uchar_string;
7551     if (!j) return (Py_UNICODE)-1;
7552     uchar_string = PyObject_GetItem(ustring, j);
7553     Py_DECREF(j);
7554     if (!uchar_string) return (Py_UNICODE)-1;
7555     uchar = PyUnicode_AS_UNICODE(uchar_string)[0];
7556     Py_DECREF(uchar_string);
7557     return uchar;
7558 }
7559 ''')
7560
7561 getitem_int_utility_code = UtilityCode(
7562 proto = """
7563
7564 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) {
7565     PyObject *r;
7566     if (!j) return NULL;
7567     r = PyObject_GetItem(o, j);
7568     Py_DECREF(j);
7569     return r;
7570 }
7571
7572 """ + ''.join([
7573 """
7574 #define __Pyx_GetItemInt_%(type)s(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7575                                                     __Pyx_GetItemInt_%(type)s_Fast(o, i) : \\
7576                                                     __Pyx_GetItemInt_Generic(o, to_py_func(i)))
7577
7578 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_%(type)s_Fast(PyObject *o, Py_ssize_t i) {
7579     if (likely(o != Py_None)) {
7580         if (likely((0 <= i) & (i < Py%(type)s_GET_SIZE(o)))) {
7581             PyObject *r = Py%(type)s_GET_ITEM(o, i);
7582             Py_INCREF(r);
7583             return r;
7584         }
7585         else if ((-Py%(type)s_GET_SIZE(o) <= i) & (i < 0)) {
7586             PyObject *r = Py%(type)s_GET_ITEM(o, Py%(type)s_GET_SIZE(o) + i);
7587             Py_INCREF(r);
7588             return r;
7589         }
7590     }
7591     return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
7592 }
7593 """ % {'type' : type_name} for type_name in ('List', 'Tuple')
7594 ]) + """
7595
7596 #define __Pyx_GetItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7597                                                     __Pyx_GetItemInt_Fast(o, i) : \\
7598                                                     __Pyx_GetItemInt_Generic(o, to_py_func(i)))
7599
7600 static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i) {
7601     PyObject *r;
7602     if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
7603         r = PyList_GET_ITEM(o, i);
7604         Py_INCREF(r);
7605     }
7606     else if (PyTuple_CheckExact(o) && ((0 <= i) & (i < PyTuple_GET_SIZE(o)))) {
7607         r = PyTuple_GET_ITEM(o, i);
7608         Py_INCREF(r);
7609     }
7610     else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0))) {
7611         r = PySequence_GetItem(o, i);
7612     }
7613     else {
7614         r = __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
7615     }
7616     return r;
7617 }
7618 """,
7619 impl = """
7620 """)
7621
7622
7623
7624 #------------------------------------------------------------------------------------
7625
7626 setitem_int_utility_code = UtilityCode(
7627 proto = """
7628 #define __Pyx_SetItemInt(o, i, v, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7629                                                     __Pyx_SetItemInt_Fast(o, i, v) : \\
7630                                                     __Pyx_SetItemInt_Generic(o, to_py_func(i), v))
7631
7632 static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) {
7633     int r;
7634     if (!j) return -1;
7635     r = PyObject_SetItem(o, j, v);
7636     Py_DECREF(j);
7637     return r;
7638 }
7639
7640 static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v) {
7641     if (PyList_CheckExact(o) && ((0 <= i) & (i < PyList_GET_SIZE(o)))) {
7642         Py_INCREF(v);
7643         Py_DECREF(PyList_GET_ITEM(o, i));
7644         PyList_SET_ITEM(o, i, v);
7645         return 1;
7646     }
7647     else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0)))
7648         return PySequence_SetItem(o, i, v);
7649     else {
7650         PyObject *j = PyInt_FromSsize_t(i);
7651         return __Pyx_SetItemInt_Generic(o, j, v);
7652     }
7653 }
7654 """,
7655 impl = """
7656 """)
7657
7658 #------------------------------------------------------------------------------------
7659
7660 delitem_int_utility_code = UtilityCode(
7661 proto = """
7662 #define __Pyx_DelItemInt(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
7663                                                     __Pyx_DelItemInt_Fast(o, i) : \\
7664                                                     __Pyx_DelItem_Generic(o, to_py_func(i)))
7665
7666 static CYTHON_INLINE int __Pyx_DelItem_Generic(PyObject *o, PyObject *j) {
7667     int r;
7668     if (!j) return -1;
7669     r = PyObject_DelItem(o, j);
7670     Py_DECREF(j);
7671     return r;
7672 }
7673
7674 static CYTHON_INLINE int __Pyx_DelItemInt_Fast(PyObject *o, Py_ssize_t i) {
7675     if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && likely(i >= 0))
7676         return PySequence_DelItem(o, i);
7677     else {
7678         PyObject *j = PyInt_FromSsize_t(i);
7679         return __Pyx_DelItem_Generic(o, j);
7680     }
7681 }
7682 """,
7683 impl = """
7684 """)
7685
7686 #------------------------------------------------------------------------------------
7687
7688 raise_too_many_values_to_unpack = UtilityCode(
7689 proto = """
7690 static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected);
7691 """,
7692 impl = '''
7693 static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) {
7694     PyErr_Format(PyExc_ValueError,
7695         #if PY_VERSION_HEX < 0x02050000
7696             "too many values to unpack (expected %d)", (int)expected);
7697         #else
7698             "too many values to unpack (expected %zd)", expected);
7699         #endif
7700 }
7701 ''')
7702
7703 raise_need_more_values_to_unpack = UtilityCode(
7704 proto = """
7705 static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index);
7706 """,
7707 impl = '''
7708 static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) {
7709     PyErr_Format(PyExc_ValueError,
7710         #if PY_VERSION_HEX < 0x02050000
7711                  "need more than %d value%s to unpack", (int)index,
7712         #else
7713                  "need more than %zd value%s to unpack", index,
7714         #endif
7715                  (index == 1) ? "" : "s");
7716 }
7717 ''')
7718
7719 #------------------------------------------------------------------------------------
7720
7721 tuple_unpacking_error_code = UtilityCode(
7722 proto = """
7723 static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); /*proto*/
7724 """, 
7725 impl = """
7726 static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) {
7727     if (t == Py_None) {
7728       __Pyx_RaiseNoneNotIterableError();
7729     } else if (PyTuple_GET_SIZE(t) < index) {
7730       __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t));
7731     } else {
7732       __Pyx_RaiseTooManyValuesError(index);
7733     }
7734 }
7735 """, 
7736 requires = [raise_none_iter_error_utility_code,
7737             raise_need_more_values_to_unpack,
7738             raise_too_many_values_to_unpack]
7739 )
7740
7741 unpacking_utility_code = UtilityCode(
7742 proto = """
7743 static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/
7744 static int __Pyx_EndUnpack(PyObject *, Py_ssize_t expected); /*proto*/
7745 """,
7746 impl = """
7747 static PyObject *__Pyx_UnpackItem(PyObject *iter, Py_ssize_t index) {
7748     PyObject *item;
7749     if (!(item = PyIter_Next(iter))) {
7750         if (!PyErr_Occurred()) {
7751             __Pyx_RaiseNeedMoreValuesError(index);
7752         }
7753     }
7754     return item;
7755 }
7756
7757 static int __Pyx_EndUnpack(PyObject *iter, Py_ssize_t expected) {
7758     PyObject *item;
7759     if ((item = PyIter_Next(iter))) {
7760         Py_DECREF(item);
7761         __Pyx_RaiseTooManyValuesError(expected);
7762         return -1;
7763     }
7764     else if (!PyErr_Occurred())
7765         return 0;
7766     else
7767         return -1;
7768 }
7769 """,
7770 requires = [raise_need_more_values_to_unpack,
7771             raise_too_many_values_to_unpack]
7772 )
7773
7774 #------------------------------------------------------------------------------------
7775
7776 # CPython supports calling functions with non-dict kwargs by
7777 # converting them to a dict first
7778
7779 kwargs_call_utility_code = UtilityCode(
7780 proto = """
7781 static PyObject* __Pyx_PyEval_CallObjectWithKeywords(PyObject*, PyObject*, PyObject*); /*proto*/
7782 """,
7783 impl = """
7784 static PyObject* __Pyx_PyEval_CallObjectWithKeywords(PyObject *callable, PyObject *args, PyObject *kwargs) {
7785     PyObject* result;
7786     if (likely(PyDict_Check(kwargs))) {
7787         return PyEval_CallObjectWithKeywords(callable, args, kwargs);
7788     } else {
7789         PyObject* real_dict;
7790         real_dict = PyObject_CallFunctionObjArgs((PyObject*)&PyDict_Type, kwargs, NULL);
7791         if (unlikely(!real_dict))
7792             return NULL;
7793         result = PyEval_CallObjectWithKeywords(callable, args, real_dict);
7794         Py_DECREF(real_dict);
7795         return result; /* may be NULL */
7796     }
7797 }
7798 """, 
7799 )
7800
7801
7802 #------------------------------------------------------------------------------------
7803
7804 int_pow_utility_code = UtilityCode(
7805 proto="""
7806 static CYTHON_INLINE %(type)s %(func_name)s(%(type)s, %(type)s); /* proto */
7807 """,
7808 impl="""
7809 static CYTHON_INLINE %(type)s %(func_name)s(%(type)s b, %(type)s e) {
7810     %(type)s t = b;
7811     switch (e) {
7812         case 3:
7813             t *= b;
7814         case 2:
7815             t *= b;
7816         case 1:
7817             return t;
7818         case 0:
7819             return 1;
7820     }
7821     if (unlikely(e<0)) return 0;
7822     t = 1;
7823     while (likely(e)) {
7824         t *= (b * (e&1)) | ((~e)&1);    /* 1 or b */
7825         b *= b;
7826         e >>= 1;
7827     }
7828     return t;
7829 }
7830 """)
7831
7832 # ------------------------------ Division ------------------------------------
7833
7834 div_int_utility_code = UtilityCode(
7835 proto="""
7836 static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s, %(type)s); /* proto */
7837 """,
7838 impl="""
7839 static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s a, %(type)s b) {
7840     %(type)s q = a / b;
7841     %(type)s r = a - q*b;
7842     q -= ((r != 0) & ((r ^ b) < 0));
7843     return q;
7844 }
7845 """)
7846
7847 mod_int_utility_code = UtilityCode(
7848 proto="""
7849 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
7850 """,
7851 impl="""
7852 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
7853     %(type)s r = a %% b;
7854     r += ((r != 0) & ((r ^ b) < 0)) * b;
7855     return r;
7856 }
7857 """)
7858
7859 mod_float_utility_code = UtilityCode(
7860 proto="""
7861 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
7862 """,
7863 impl="""
7864 static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
7865     %(type)s r = fmod%(math_h_modifier)s(a, b);
7866     r += ((r != 0) & ((r < 0) ^ (b < 0))) * b;
7867     return r;
7868 }
7869 """)
7870
7871 cdivision_warning_utility_code = UtilityCode(
7872 proto="""
7873 static int __Pyx_cdivision_warning(void); /* proto */
7874 """,
7875 impl="""
7876 static int __Pyx_cdivision_warning(void) {
7877     return PyErr_WarnExplicit(PyExc_RuntimeWarning, 
7878                               "division with oppositely signed operands, C and Python semantics differ",
7879                               %(FILENAME)s, 
7880                               %(LINENO)s,
7881                               __Pyx_MODULE_NAME,
7882                               NULL);
7883 }
7884 """ % {
7885     'FILENAME': Naming.filename_cname,
7886     'LINENO':  Naming.lineno_cname,
7887 })
7888
7889 # from intobject.c
7890 division_overflow_test_code = UtilityCode(
7891 proto="""
7892 #define UNARY_NEG_WOULD_OVERFLOW(x)     \
7893         (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x)))
7894 """)
7895
7896
7897 binding_cfunc_utility_code = UtilityCode(
7898 proto="""
7899 #define %(binding_cfunc)s_USED 1
7900
7901 typedef struct {
7902     PyCFunctionObject func;
7903 } %(binding_cfunc)s_object;
7904
7905 PyTypeObject %(binding_cfunc)s_type;
7906 PyTypeObject *%(binding_cfunc)s = NULL;
7907
7908 PyObject *%(binding_cfunc)s_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module); /* proto */
7909 #define %(binding_cfunc)s_New(ml, self) %(binding_cfunc)s_NewEx(ml, self, NULL)
7910
7911 int %(binding_cfunc)s_init(void); /* proto */
7912 """ % Naming.__dict__,
7913 impl="""
7914
7915 PyObject *%(binding_cfunc)s_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) {
7916         %(binding_cfunc)s_object *op = PyObject_GC_New(%(binding_cfunc)s_object, %(binding_cfunc)s);
7917     if (op == NULL)
7918         return NULL;
7919         op->func.m_ml = ml;
7920         Py_XINCREF(self);
7921         op->func.m_self = self;
7922         Py_XINCREF(module);
7923         op->func.m_module = module;
7924         PyObject_GC_Track(op);
7925         return (PyObject *)op;
7926 }
7927
7928 static void %(binding_cfunc)s_dealloc(%(binding_cfunc)s_object *m) {
7929         PyObject_GC_UnTrack(m);
7930         Py_XDECREF(m->func.m_self);
7931         Py_XDECREF(m->func.m_module);
7932     PyObject_GC_Del(m);
7933 }
7934
7935 static PyObject *%(binding_cfunc)s_descr_get(PyObject *func, PyObject *obj, PyObject *type) {
7936         if (obj == Py_None)
7937                 obj = NULL;
7938         return PyMethod_New(func, obj, type);
7939 }
7940
7941 int %(binding_cfunc)s_init(void) {
7942     %(binding_cfunc)s_type = PyCFunction_Type;
7943     %(binding_cfunc)s_type.tp_name = __Pyx_NAMESTR("cython_binding_builtin_function_or_method");
7944     %(binding_cfunc)s_type.tp_dealloc = (destructor)%(binding_cfunc)s_dealloc;
7945     %(binding_cfunc)s_type.tp_descr_get = %(binding_cfunc)s_descr_get;
7946     if (PyType_Ready(&%(binding_cfunc)s_type) < 0) {
7947         return -1;
7948     }
7949     %(binding_cfunc)s = &%(binding_cfunc)s_type;
7950     return 0;
7951
7952 }
7953 """ % Naming.__dict__)