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