fix list comprehensions as if conditions
[cython.git] / Cython / Compiler / Nodes.py
1
2 #
3 #   Pyrex - Parse tree nodes
4 #
5
6 import sys, os, time, copy
7
8 try:
9     set
10 except NameError:
11     # Python 2.3
12     from sets import Set as set
13
14 import Code
15 import Builtin
16 from Errors import error, warning, InternalError
17 import Naming
18 import PyrexTypes
19 import TypeSlots
20 from PyrexTypes import py_object_type, error_type, CFuncType
21 from Symtab import ModuleScope, LocalScope, ClosureScope, \
22     StructOrUnionScope, PyClassScope, CClassScope, CppClassScope
23 from Cython.Utils import open_new_file, replace_suffix
24 from Code import UtilityCode
25 from StringEncoding import EncodedString, escape_byte_string, split_string_literal
26 import Options
27 import ControlFlow
28 import DebugFlags
29
30 absolute_path_length = 0
31
32 def relative_position(pos):
33     """
34     We embed the relative filename in the generated C file, since we
35     don't want to have to regnerate and compile all the source code
36     whenever the Python install directory moves (which could happen,
37     e.g,. when distributing binaries.)
38     
39     INPUT:
40         a position tuple -- (absolute filename, line number column position)
41
42     OUTPUT:
43         relative filename
44         line number
45
46     AUTHOR: William Stein
47     """
48     global absolute_path_length
49     if absolute_path_length==0:
50         absolute_path_length = len(os.path.abspath(os.getcwd())) 
51     return (pos[0].get_filenametable_entry()[absolute_path_length+1:], pos[1])
52
53 def embed_position(pos, docstring):
54     if not Options.embed_pos_in_docstring:
55         return docstring
56     pos_line = u'File: %s (starting at line %s)' % relative_position(pos)
57     if docstring is None:
58         # unicode string
59         return EncodedString(pos_line)
60
61     # make sure we can encode the filename in the docstring encoding
62     # otherwise make the docstring a unicode string
63     encoding = docstring.encoding
64     if encoding is not None:
65         try:
66             encoded_bytes = pos_line.encode(encoding)
67         except UnicodeEncodeError:
68             encoding = None
69
70     if not docstring:
71         # reuse the string encoding of the original docstring
72         doc = EncodedString(pos_line)
73     else:
74         doc = EncodedString(pos_line + u'\n' + docstring)
75     doc.encoding = encoding
76     return doc
77
78
79 from Code import CCodeWriter
80 from types import FunctionType
81
82 def write_func_call(func):
83     def f(*args, **kwds):
84         if len(args) > 1 and isinstance(args[1], CCodeWriter):
85             # here we annotate the code with this function call
86             # but only if new code is generated
87             node, code = args[:2]
88             marker = '                    /* %s -> %s.%s %s */' % (
89                     ' ' * code.call_level,
90                     node.__class__.__name__, 
91                     func.__name__, 
92                     node.pos[1:])
93             pristine = code.buffer.stream.tell()
94             code.putln(marker)
95             start = code.buffer.stream.tell()
96             code.call_level += 4
97             res = func(*args, **kwds)
98             code.call_level -= 4
99             if start == code.buffer.stream.tell():
100                 code.buffer.stream.seek(pristine)
101             else:
102                 marker = marker.replace('->', '<-')
103                 code.putln(marker)
104             return res
105         else:
106             return func(*args, **kwds)
107     return f
108
109 class VerboseCodeWriter(type):
110     # Set this as a metaclass to trace function calls in code.
111     # This slows down code generation and makes much larger files. 
112     def __new__(cls, name, bases, attrs):
113         attrs = dict(attrs)
114         for mname, m in attrs.items():
115             if isinstance(m, FunctionType):
116                 attrs[mname] = write_func_call(m)
117         return super(VerboseCodeWriter, cls).__new__(cls, name, bases, attrs)
118
119
120 class Node(object):
121     #  pos         (string, int, int)   Source file position
122     #  is_name     boolean              Is a NameNode
123     #  is_literal  boolean              Is a ConstNode
124
125     if DebugFlags.debug_trace_code_generation:
126         __metaclass__ = VerboseCodeWriter
127     
128     is_name = 0
129     is_literal = 0
130     temps = None
131
132     # All descandants should set child_attrs to a list of the attributes
133     # containing nodes considered "children" in the tree. Each such attribute
134     # can either contain a single node or a list of nodes. See Visitor.py.
135     child_attrs = None
136     
137     def __init__(self, pos, **kw):
138         self.pos = pos
139         self.__dict__.update(kw)
140     
141     gil_message = "Operation"
142
143     nogil_check = None
144
145     def gil_error(self, env=None):
146         error(self.pos, "%s not allowed without gil" % self.gil_message)
147     
148     cpp_message = "Operation"
149     
150     def cpp_check(self, env):
151         if not env.is_cpp():
152             self.cpp_error()
153
154     def cpp_error(self):
155         error(self.pos, "%s only allowed in c++" % self.cpp_message)
156
157     def clone_node(self):
158         """Clone the node. This is defined as a shallow copy, except for member lists
159            amongst the child attributes (from get_child_accessors) which are also
160            copied. Lists containing child nodes are thus seen as a way for the node
161            to hold multiple children directly; the list is not treated as a seperate
162            level in the tree."""
163         result = copy.copy(self)
164         for attrname in result.child_attrs:
165             value = getattr(result, attrname)
166             if isinstance(value, list):
167                 setattr(result, attrname, [x for x in value])
168         return result
169     
170     
171     #
172     #  There are 4 phases of parse tree processing, applied in order to
173     #  all the statements in a given scope-block:
174     #
175     #  (0) analyse_control_flow
176     #        Create the control flow tree into which state can be asserted and
177     #        queried.
178     #
179     #  (1) analyse_declarations
180     #        Make symbol table entries for all declarations at the current
181     #        level, both explicit (def, cdef, etc.) and implicit (assignment
182     #        to an otherwise undeclared name).
183     #
184     #  (2) analyse_expressions
185     #         Determine the result types of expressions and fill in the
186     #         'type' attribute of each ExprNode. Insert coercion nodes into the
187     #         tree where needed to convert to and from Python objects. 
188     #         Allocate temporary locals for intermediate results. Fill
189     #         in the 'result_code' attribute of each ExprNode with a C code
190     #         fragment.
191     #
192     #  (3) generate_code
193     #         Emit C code for all declarations, statements and expressions.
194     #         Recursively applies the 3 processing phases to the bodies of
195     #         functions.
196     #
197     
198     def analyse_control_flow(self, env):
199         pass
200     
201     def analyse_declarations(self, env):
202         pass
203     
204     def analyse_expressions(self, env):
205         raise InternalError("analyse_expressions not implemented for %s" % \
206             self.__class__.__name__)
207     
208     def generate_code(self, code):
209         raise InternalError("generate_code not implemented for %s" % \
210             self.__class__.__name__)
211             
212     def annotate(self, code):
213         # mro does the wrong thing
214         if isinstance(self, BlockNode):
215             self.body.annotate(code)
216             
217     def end_pos(self):
218         try:
219             return self._end_pos
220         except AttributeError:
221             pos = self.pos
222             if not self.child_attrs:
223                 self._end_pos = pos
224                 return pos
225             for attr in self.child_attrs:
226                 child = getattr(self, attr)
227                 # Sometimes lists, sometimes nodes
228                 if child is None:
229                     pass
230                 elif isinstance(child, list):
231                     for c in child:
232                         pos = max(pos, c.end_pos())
233                 else:
234                     pos = max(pos, child.end_pos())
235             self._end_pos = pos
236             return pos
237
238     def dump(self, level=0, filter_out=("pos",), cutoff=100, encountered=None):
239         if cutoff == 0:
240             return "<...nesting level cutoff...>"
241         if encountered is None:
242             encountered = set()
243         if id(self) in encountered:
244             return "<%s (%d) -- already output>" % (self.__class__.__name__, id(self))
245         encountered.add(id(self))
246         
247         def dump_child(x, level):
248             if isinstance(x, Node):
249                 return x.dump(level, filter_out, cutoff-1, encountered)
250             elif isinstance(x, list):
251                 return "[%s]" % ", ".join([dump_child(item, level) for item in x])
252             else:
253                 return repr(x)
254             
255         
256         attrs = [(key, value) for key, value in self.__dict__.iteritems() if key not in filter_out]
257         if len(attrs) == 0:
258             return "<%s (%d)>" % (self.__class__.__name__, id(self))
259         else:
260             indent = "  " * level
261             res = "<%s (%d)\n" % (self.__class__.__name__, id(self))
262             for key, value in attrs:
263                 res += "%s  %s: %s\n" % (indent, key, dump_child(value, level + 1))
264             res += "%s>" % indent
265             return res
266
267 class CompilerDirectivesNode(Node):
268     """
269     Sets compiler directives for the children nodes
270     """
271     #  directives     {string:value}  A dictionary holding the right value for
272     #                                 *all* possible directives.
273     #  body           Node
274     child_attrs = ["body"]
275
276     def analyse_control_flow(self, env):
277         old = env.directives
278         env.directives = self.directives
279         self.body.analyse_control_flow(env)
280         env.directives = old
281
282     def analyse_declarations(self, env):
283         old = env.directives
284         env.directives = self.directives
285         self.body.analyse_declarations(env)
286         env.directives = old
287     
288     def analyse_expressions(self, env):
289         old = env.directives
290         env.directives = self.directives
291         self.body.analyse_expressions(env)
292         env.directives = old
293
294     def generate_function_definitions(self, env, code):
295         env_old = env.directives
296         code_old = code.globalstate.directives
297         code.globalstate.directives = self.directives
298         self.body.generate_function_definitions(env, code)
299         env.directives = env_old
300         code.globalstate.directives = code_old
301             
302     def generate_execution_code(self, code):
303         old = code.globalstate.directives
304         code.globalstate.directives = self.directives
305         self.body.generate_execution_code(code)
306         code.globalstate.directives = old
307             
308     def annotate(self, code):
309         old = code.globalstate.directives
310         code.globalstate.directives = self.directives
311         self.body.annotate(code)
312         code.globalstate.directives = old
313         
314 class BlockNode(object):
315     #  Mixin class for nodes representing a declaration block.
316
317     def generate_cached_builtins_decls(self, env, code):
318         entries = env.global_scope().undeclared_cached_builtins
319         for entry in entries:
320             code.globalstate.add_cached_builtin_decl(entry)
321         del entries[:]
322         
323
324 class StatListNode(Node):
325     # stats     a list of StatNode
326     
327     child_attrs = ["stats"]
328
329     def create_analysed(pos, env, *args, **kw):
330         node = StatListNode(pos, *args, **kw)
331         return node # No node-specific analysis necesarry
332     create_analysed = staticmethod(create_analysed)
333     
334     def analyse_control_flow(self, env):
335         for stat in self.stats:
336             stat.analyse_control_flow(env)
337
338     def analyse_declarations(self, env):
339         #print "StatListNode.analyse_declarations" ###
340         for stat in self.stats:
341             stat.analyse_declarations(env)
342     
343     def analyse_expressions(self, env):
344         #print "StatListNode.analyse_expressions" ###
345         for stat in self.stats:
346             stat.analyse_expressions(env)
347     
348     def generate_function_definitions(self, env, code):
349         #print "StatListNode.generate_function_definitions" ###
350         for stat in self.stats:
351             stat.generate_function_definitions(env, code)
352             
353     def generate_execution_code(self, code):
354         #print "StatListNode.generate_execution_code" ###
355         for stat in self.stats:
356             code.mark_pos(stat.pos)
357             stat.generate_execution_code(code)
358             
359     def annotate(self, code):
360         for stat in self.stats:
361             stat.annotate(code)
362     
363
364 class StatNode(Node):
365     #
366     #  Code generation for statements is split into the following subphases:
367     #
368     #  (1) generate_function_definitions
369     #        Emit C code for the definitions of any structs,
370     #        unions, enums and functions defined in the current
371     #        scope-block.
372     #
373     #  (2) generate_execution_code
374     #        Emit C code for executable statements.
375     #
376     
377     def generate_function_definitions(self, env, code):
378         pass
379     
380     def generate_execution_code(self, code):
381         raise InternalError("generate_execution_code not implemented for %s" % \
382             self.__class__.__name__)
383
384
385 class CDefExternNode(StatNode):
386     #  include_file   string or None
387     #  body           StatNode
388     
389     child_attrs = ["body"]
390     
391     def analyse_declarations(self, env):
392         if self.include_file:
393             env.add_include_file(self.include_file)
394         old_cinclude_flag = env.in_cinclude
395         env.in_cinclude = 1
396         self.body.analyse_declarations(env)
397         env.in_cinclude = old_cinclude_flag
398     
399     def analyse_expressions(self, env):
400         pass
401     
402     def generate_execution_code(self, code):
403         pass
404
405     def annotate(self, code):
406         self.body.annotate(code)
407         
408
409 class CDeclaratorNode(Node):
410     # Part of a C declaration.
411     #
412     # Processing during analyse_declarations phase:
413     #
414     #   analyse
415     #      Returns (name, type) pair where name is the
416     #      CNameDeclaratorNode of the name being declared 
417     #      and type is the type it is being declared as.
418     #
419     #  calling_convention  string   Calling convention of CFuncDeclaratorNode
420     #                               for which this is a base 
421
422     child_attrs = []
423
424     calling_convention = ""
425
426
427 class CNameDeclaratorNode(CDeclaratorNode):
428     #  name    string             The Pyrex name being declared
429     #  cname   string or None     C name, if specified
430     #  default ExprNode or None   the value assigned on declaration
431     
432     child_attrs = ['default']
433     
434     default = None
435     
436     def analyse(self, base_type, env, nonempty = 0):
437         if nonempty and self.name == '':
438             # May have mistaken the name for the type. 
439             if base_type.is_ptr or base_type.is_array or base_type.is_buffer:
440                 error(self.pos, "Missing argument name")
441             elif base_type.is_void:
442                 error(self.pos, "Use spam() rather than spam(void) to declare a function with no arguments.")
443             else:
444                 self.name = base_type.declaration_code("", for_display=1, pyrex=1)
445                 base_type = py_object_type
446         self.type = base_type
447         return self, base_type
448         
449 class CPtrDeclaratorNode(CDeclaratorNode):
450     # base     CDeclaratorNode
451     
452     child_attrs = ["base"]
453
454     def analyse(self, base_type, env, nonempty = 0):
455         if base_type.is_pyobject:
456             error(self.pos,
457                 "Pointer base type cannot be a Python object")
458         ptr_type = PyrexTypes.c_ptr_type(base_type)
459         return self.base.analyse(ptr_type, env, nonempty = nonempty)
460
461 class CReferenceDeclaratorNode(CDeclaratorNode):
462     # base     CDeclaratorNode
463
464     child_attrs = ["base"]
465
466     def analyse(self, base_type, env, nonempty = 0):
467         if base_type.is_pyobject:
468             error(self.pos,
469                   "Reference base type cannot be a Python object")
470         ref_type = PyrexTypes.c_ref_type(base_type)
471         return self.base.analyse(ref_type, env, nonempty = nonempty)
472
473 class CArrayDeclaratorNode(CDeclaratorNode):
474     # base        CDeclaratorNode
475     # dimension   ExprNode
476
477     child_attrs = ["base", "dimension"]
478     
479     def analyse(self, base_type, env, nonempty = 0):
480         if base_type.is_cpp_class:
481             from ExprNodes import TupleNode
482             if isinstance(self.dimension, TupleNode):
483                 args = self.dimension.args
484             else:
485                 args = self.dimension,
486             values = [v.analyse_as_type(env) for v in args]
487             if None in values:
488                 ix = values.index(None)
489                 error(args[ix].pos, "Template parameter not a type.")
490                 return error_type
491             base_type = base_type.specialize_here(self.pos, values)
492             return self.base.analyse(base_type, env, nonempty = nonempty)
493         if self.dimension:
494             self.dimension.analyse_const_expression(env)
495             if not self.dimension.type.is_int:
496                 error(self.dimension.pos, "Array dimension not integer")
497             size = self.dimension.get_constant_c_result_code()
498             if size is not None:
499                 try:
500                     size = int(size)
501                 except ValueError:
502                     # runtime constant?
503                     pass
504         else:
505             size = None
506         if not base_type.is_complete():
507             error(self.pos,
508                 "Array element type '%s' is incomplete" % base_type)
509         if base_type.is_pyobject:
510             error(self.pos,
511                 "Array element cannot be a Python object")
512         if base_type.is_cfunction:
513             error(self.pos,
514                 "Array element cannot be a function")
515         array_type = PyrexTypes.c_array_type(base_type, size)
516         return self.base.analyse(array_type, env, nonempty = nonempty)
517
518
519 class CFuncDeclaratorNode(CDeclaratorNode):
520     # base             CDeclaratorNode
521     # args             [CArgDeclNode]
522     # has_varargs      boolean
523     # exception_value  ConstNode
524     # exception_check  boolean    True if PyErr_Occurred check needed
525     # nogil            boolean    Can be called without gil
526     # with_gil         boolean    Acquire gil around function body
527     
528     child_attrs = ["base", "args", "exception_value"]
529
530     overridable = 0
531     optional_arg_count = 0
532
533     def analyse(self, return_type, env, nonempty = 0):
534         if nonempty:
535             nonempty -= 1
536         func_type_args = []
537         for i, arg_node in enumerate(self.args):
538             name_declarator, type = arg_node.analyse(env, nonempty = nonempty,
539                                                      is_self_arg = (i == 0 and env.is_c_class_scope))
540             name = name_declarator.name
541             if name_declarator.cname:
542                 error(self.pos, 
543                     "Function argument cannot have C name specification")
544             # Turn *[] argument into **
545             if type.is_array:
546                 type = PyrexTypes.c_ptr_type(type.base_type)
547             # Catch attempted C-style func(void) decl
548             if type.is_void:
549                 error(arg_node.pos, "Use spam() rather than spam(void) to declare a function with no arguments.")
550             func_type_args.append(
551                 PyrexTypes.CFuncTypeArg(name, type, arg_node.pos))
552             if arg_node.default:
553                 self.optional_arg_count += 1
554             elif self.optional_arg_count:
555                 error(self.pos, "Non-default argument follows default argument")
556         
557         if self.optional_arg_count:
558             scope = StructOrUnionScope()
559             arg_count_member = '%sn' % Naming.pyrex_prefix
560             scope.declare_var(arg_count_member, PyrexTypes.c_int_type, self.pos)
561             for arg in func_type_args[len(func_type_args)-self.optional_arg_count:]:
562                 scope.declare_var(arg.name, arg.type, arg.pos, allow_pyobject = 1)
563             struct_cname = env.mangle(Naming.opt_arg_prefix, self.base.name)
564             self.op_args_struct = env.global_scope().declare_struct_or_union(name = struct_cname,
565                                         kind = 'struct',
566                                         scope = scope,
567                                         typedef_flag = 0,
568                                         pos = self.pos,
569                                         cname = struct_cname)
570             self.op_args_struct.defined_in_pxd = 1
571             self.op_args_struct.used = 1
572         
573         exc_val = None
574         exc_check = 0
575         if self.exception_check == '+':
576             env.add_include_file('stdexcept')
577         if return_type.is_pyobject \
578             and (self.exception_value or self.exception_check) \
579             and self.exception_check != '+':
580                 error(self.pos,
581                     "Exception clause not allowed for function returning Python object")
582         else:
583             if self.exception_value:
584                 self.exception_value.analyse_const_expression(env)
585                 if self.exception_check == '+':
586                     self.exception_value.analyse_types(env)
587                     exc_val_type = self.exception_value.type
588                     if not exc_val_type.is_error and \
589                           not exc_val_type.is_pyobject and \
590                           not (exc_val_type.is_cfunction and not exc_val_type.return_type.is_pyobject and len(exc_val_type.args)==0):
591                         error(self.exception_value.pos,
592                             "Exception value must be a Python exception or cdef function with no arguments.")
593                     exc_val = self.exception_value
594                 else:
595                     self.exception_value = self.exception_value.coerce_to(return_type, env)
596                     if self.exception_value.analyse_const_expression(env):
597                         exc_val = self.exception_value.get_constant_c_result_code()
598                         if exc_val is None:
599                             raise InternalError("get_constant_c_result_code not implemented for %s" %
600                                 self.exception_value.__class__.__name__)
601                         if not return_type.assignable_from(self.exception_value.type):
602                             error(self.exception_value.pos,
603                                   "Exception value incompatible with function return type")
604             exc_check = self.exception_check
605         if return_type.is_array:
606             error(self.pos,
607                 "Function cannot return an array")
608         if return_type.is_cfunction:
609             error(self.pos,
610                 "Function cannot return a function")
611         func_type = PyrexTypes.CFuncType(
612             return_type, func_type_args, self.has_varargs, 
613             optional_arg_count = self.optional_arg_count,
614             exception_value = exc_val, exception_check = exc_check,
615             calling_convention = self.base.calling_convention,
616             nogil = self.nogil, with_gil = self.with_gil, is_overridable = self.overridable)
617         if self.optional_arg_count:
618             func_type.op_arg_struct = PyrexTypes.c_ptr_type(self.op_args_struct.type)
619         callspec = env.directives['callspec']
620         if callspec:
621             current = func_type.calling_convention
622             if current and current != callspec:
623                 error(self.pos, "cannot have both '%s' and '%s' "
624                       "calling conventions" % (current, callspec))
625             func_type.calling_convention = callspec
626         return self.base.analyse(func_type, env)
627
628
629 class CArgDeclNode(Node):
630     # Item in a function declaration argument list.
631     #
632     # base_type      CBaseTypeNode
633     # declarator     CDeclaratorNode
634     # not_none       boolean            Tagged with 'not None'
635     # or_none        boolean            Tagged with 'or None'
636     # accept_none    boolean            Resolved boolean for not_none/or_none
637     # default        ExprNode or None
638     # default_value  PyObjectConst      constant for default value
639     # annotation     ExprNode or None   Py3 function arg annotation
640     # is_self_arg    boolean            Is the "self" arg of an extension type method
641     # is_type_arg    boolean            Is the "class" arg of an extension type classmethod
642     # is_kw_only     boolean            Is a keyword-only argument
643
644     child_attrs = ["base_type", "declarator", "default"]
645
646     is_self_arg = 0
647     is_type_arg = 0
648     is_generic = 1
649     type = None
650     name_declarator = None
651     default_value = None
652     annotation = None
653
654     def analyse(self, env, nonempty = 0, is_self_arg = False):
655         if is_self_arg:
656             self.base_type.is_self_arg = self.is_self_arg = True
657         if self.type is None:
658             # The parser may missinterpret names as types...
659             # We fix that here.
660             if isinstance(self.declarator, CNameDeclaratorNode) and self.declarator.name == '':
661                 if nonempty:
662                     self.declarator.name = self.base_type.name
663                     self.base_type.name = None
664                     self.base_type.is_basic_c_type = False
665                 could_be_name = True
666             else:
667                 could_be_name = False
668             base_type = self.base_type.analyse(env, could_be_name = could_be_name)
669             if hasattr(self.base_type, 'arg_name') and self.base_type.arg_name:
670                 self.declarator.name = self.base_type.arg_name
671             # The parser is unable to resolve the ambiguity of [] as part of the 
672             # type (e.g. in buffers) or empty declarator (as with arrays). 
673             # This is only arises for empty multi-dimensional arrays.
674             if (base_type.is_array 
675                     and isinstance(self.base_type, TemplatedTypeNode) 
676                     and isinstance(self.declarator, CArrayDeclaratorNode)):
677                 declarator = self.declarator
678                 while isinstance(declarator.base, CArrayDeclaratorNode):
679                     declarator = declarator.base
680                 declarator.base = self.base_type.array_declarator
681                 base_type = base_type.base_type
682             return self.declarator.analyse(base_type, env, nonempty = nonempty)
683         else:
684             return self.name_declarator, self.type
685
686     def calculate_default_value_code(self, code):
687         if self.default_value is None:
688             if self.default:
689                 if self.default.is_literal:
690                     # will not output any code, just assign the result_code
691                     self.default.generate_evaluation_code(code)
692                     return self.type.cast_code(self.default.result())
693                 self.default_value = code.get_argument_default_const(self.type)
694         return self.default_value
695
696     def annotate(self, code):
697         if self.default:
698             self.default.annotate(code)
699
700
701 class CBaseTypeNode(Node):
702     # Abstract base class for C base type nodes.
703     #
704     # Processing during analyse_declarations phase:
705     #
706     #   analyse
707     #     Returns the type.
708     
709     pass
710     
711     def analyse_as_type(self, env):
712         return self.analyse(env)
713     
714 class CAnalysedBaseTypeNode(Node):
715     # type            type
716     
717     child_attrs = []
718     
719     def analyse(self, env, could_be_name = False):
720         return self.type
721
722 class CSimpleBaseTypeNode(CBaseTypeNode):
723     # name             string
724     # module_path      [string]     Qualifying name components
725     # is_basic_c_type  boolean
726     # signed           boolean
727     # longness         integer
728     # complex          boolean
729     # is_self_arg      boolean      Is self argument of C method
730     # ##is_type_arg      boolean      Is type argument of class method
731
732     child_attrs = []
733     arg_name = None   # in case the argument name was interpreted as a type
734     
735     def analyse(self, env, could_be_name = False):
736         # Return type descriptor.
737         #print "CSimpleBaseTypeNode.analyse: is_self_arg =", self.is_self_arg ###
738         type = None
739         if self.is_basic_c_type:
740             type = PyrexTypes.simple_c_type(self.signed, self.longness, self.name)
741             if not type:
742                 error(self.pos, "Unrecognised type modifier combination")
743         elif self.name == "object" and not self.module_path:
744             type = py_object_type
745         elif self.name is None:
746             if self.is_self_arg and env.is_c_class_scope:
747                 #print "CSimpleBaseTypeNode.analyse: defaulting to parent type" ###
748                 type = env.parent_type
749             ## elif self.is_type_arg and env.is_c_class_scope:
750             ##     type = Builtin.type_type
751             else:
752                 type = py_object_type
753         else:
754             if self.module_path:
755                 scope = env.find_imported_module(self.module_path, self.pos)
756             else:
757                 scope = env
758             if scope:
759                 if scope.is_c_class_scope:
760                     scope = scope.global_scope()
761                 entry = scope.lookup(self.name)
762                 if entry and entry.is_type:
763                     type = entry.type
764                 elif could_be_name:
765                     if self.is_self_arg and env.is_c_class_scope:
766                         type = env.parent_type
767                     ## elif self.is_type_arg and env.is_c_class_scope:
768                     ##     type = Builtin.type_type
769                     else:
770                         type = py_object_type
771                     self.arg_name = self.name
772                 else:
773                     if self.templates:
774                         if not self.name in self.templates:
775                             error(self.pos, "'%s' is not a type identifier" % self.name)
776                         type = PyrexTypes.TemplatePlaceholderType(self.name)
777                     else:
778                         error(self.pos, "'%s' is not a type identifier" % self.name)
779         if self.complex:
780             if not type.is_numeric or type.is_complex:
781                 error(self.pos, "can only complexify c numeric types")
782             type = PyrexTypes.CComplexType(type)
783             type.create_declaration_utility_code(env)
784         if type:
785             return type
786         else:
787             return PyrexTypes.error_type
788
789 class CNestedBaseTypeNode(CBaseTypeNode):
790     # For C++ classes that live inside other C++ classes. 
791
792     # name             string
793     # base_type        CBaseTypeNode
794
795     child_attrs = ['base_type']
796
797     def analyse(self, env, could_be_name = None):
798         base_type = self.base_type.analyse(env)
799         if base_type is PyrexTypes.error_type:
800             return PyrexTypes.error_type
801         if not base_type.is_cpp_class:
802             error(self.pos, "'%s' is not a valid type scope" % base_type)
803             return PyrexTypes.error_type
804         type_entry = base_type.scope.lookup_here(self.name)
805         if not type_entry or not type_entry.is_type:
806             error(self.pos, "'%s.%s' is not a type identifier" % (base_type, self.name))
807             return PyrexTypes.error_type
808         return type_entry.type
809
810 class TemplatedTypeNode(CBaseTypeNode):
811     #  After parsing:
812     #  positional_args  [ExprNode]        List of positional arguments
813     #  keyword_args     DictNode          Keyword arguments
814     #  base_type_node   CBaseTypeNode
815
816     #  After analysis:
817     #  type             PyrexTypes.BufferType or PyrexTypes.CppClassType  ...containing the right options
818
819
820     child_attrs = ["base_type_node", "positional_args",
821                    "keyword_args", "dtype_node"]
822
823     dtype_node = None
824
825     name = None
826     
827     def analyse(self, env, could_be_name = False, base_type = None):
828         if base_type is None:
829             base_type = self.base_type_node.analyse(env)
830         if base_type.is_error: return base_type
831         
832         if base_type.is_cpp_class:
833             # Templated class
834             if self.keyword_args and self.keyword_args.key_value_pairs:
835                 error(self.pos, "c++ templates cannot take keyword arguments");
836                 self.type = PyrexTypes.error_type
837             else:
838                 template_types = []
839                 for template_node in self.positional_args:
840                     type = template_node.analyse_as_type(env)
841                     if type is None:
842                         error(template_node.pos, "unknown type in template argument")
843                         return error_type
844                     template_types.append(type)
845                 self.type = base_type.specialize_here(self.pos, template_types)
846         
847         elif base_type.is_pyobject:
848             # Buffer
849             import Buffer
850
851             options = Buffer.analyse_buffer_options(
852                 self.pos,
853                 env,
854                 self.positional_args,
855                 self.keyword_args,
856                 base_type.buffer_defaults)
857
858             if sys.version_info[0] < 3:
859                 # Py 2.x enforces byte strings as keyword arguments ...
860                 options = dict([ (name.encode('ASCII'), value)
861                                  for name, value in options.iteritems() ])
862
863             self.type = PyrexTypes.BufferType(base_type, **options)
864         
865         else:
866             # Array
867             empty_declarator = CNameDeclaratorNode(self.pos, name="", cname=None)
868             if len(self.positional_args) > 1 or self.keyword_args.key_value_pairs:
869                 error(self.pos, "invalid array declaration")
870                 self.type = PyrexTypes.error_type
871             else:
872                 # It would be nice to merge this class with CArrayDeclaratorNode, 
873                 # but arrays are part of the declaration, not the type...
874                 if not self.positional_args:
875                     dimension = None
876                 else:
877                     dimension = self.positional_args[0]
878                 self.array_declarator = CArrayDeclaratorNode(self.pos, 
879                     base = empty_declarator, 
880                     dimension = dimension)
881                 self.type = self.array_declarator.analyse(base_type, env)[1]
882         
883         return self.type
884
885 class CComplexBaseTypeNode(CBaseTypeNode):
886     # base_type   CBaseTypeNode
887     # declarator  CDeclaratorNode
888     
889     child_attrs = ["base_type", "declarator"]
890
891     def analyse(self, env, could_be_name = False):
892         base = self.base_type.analyse(env, could_be_name)
893         _, type = self.declarator.analyse(base, env)
894         return type
895
896
897 class CVarDefNode(StatNode):
898     #  C variable definition or forward/extern function declaration.
899     #
900     #  visibility    'private' or 'public' or 'extern'
901     #  base_type     CBaseTypeNode
902     #  declarators   [CDeclaratorNode]
903     #  in_pxd        boolean
904     #  api           boolean
905
906     #  decorators    [cython.locals(...)] or None 
907     #  directive_locals { string : NameNode } locals defined by cython.locals(...)
908
909     child_attrs = ["base_type", "declarators"]
910     
911     decorators = None
912     directive_locals = {}
913     
914     def analyse_declarations(self, env, dest_scope = None):
915         if not dest_scope:
916             dest_scope = env
917         self.dest_scope = dest_scope
918         base_type = self.base_type.analyse(env)
919
920         # If the field is an external typedef, we cannot be sure about the type,
921         # so do conversion ourself rather than rely on the CPython mechanism (through
922         # a property; made in AnalyseDeclarationsTransform).
923         if (dest_scope.is_c_class_scope
924             and self.visibility in ('public', 'readonly')):
925             need_property = True
926         else:
927             need_property = False
928         visibility = self.visibility
929             
930         for declarator in self.declarators:
931             name_declarator, type = declarator.analyse(base_type, env)
932             if not type.is_complete():
933                 if not (self.visibility == 'extern' and type.is_array):
934                     error(declarator.pos,
935                         "Variable type '%s' is incomplete" % type)
936             if self.visibility == 'extern' and type.is_pyobject:
937                 error(declarator.pos,
938                     "Python object cannot be declared extern")
939             name = name_declarator.name
940             cname = name_declarator.cname
941             if name == '':
942                 error(declarator.pos, "Missing name in declaration.")
943                 return
944             if type.is_cfunction:
945                 entry = dest_scope.declare_cfunction(name, type, declarator.pos,
946                     cname = cname, visibility = self.visibility, in_pxd = self.in_pxd,
947                     api = self.api)
948                 if entry is not None:
949                     entry.directive_locals = self.directive_locals
950             else:
951                 if self.directive_locals:
952                     s.error("Decorators can only be followed by functions")
953                 if self.in_pxd and self.visibility != 'extern':
954                     error(self.pos, 
955                         "Only 'extern' C variable declaration allowed in .pxd file")
956                 entry = dest_scope.declare_var(name, type, declarator.pos,
957                             cname = cname, visibility = visibility, is_cdef = 1)
958                 entry.needs_property = need_property
959     
960
961 class CStructOrUnionDefNode(StatNode):
962     #  name          string
963     #  cname         string or None
964     #  kind          "struct" or "union"
965     #  typedef_flag  boolean
966     #  visibility    "public" or "private"
967     #  in_pxd        boolean
968     #  attributes    [CVarDefNode] or None
969     #  entry         Entry
970     #  packed        boolean
971     
972     child_attrs = ["attributes"]
973
974     def analyse_declarations(self, env):
975         scope = None
976         if self.visibility == 'extern' and self.packed:
977             error(self.pos, "Cannot declare extern struct as 'packed'")
978         if self.attributes is not None:
979             scope = StructOrUnionScope(self.name)
980         self.entry = env.declare_struct_or_union(
981             self.name, self.kind, scope, self.typedef_flag, self.pos,
982             self.cname, visibility = self.visibility, packed = self.packed)
983         if self.attributes is not None:
984             if self.in_pxd and not env.in_cinclude:
985                 self.entry.defined_in_pxd = 1
986             for attr in self.attributes:
987                 attr.analyse_declarations(env, scope)
988             if self.visibility != 'extern':
989                 need_typedef_indirection = False
990                 for attr in scope.var_entries:
991                     type = attr.type
992                     while type.is_array:
993                         type = type.base_type
994                     if type == self.entry.type:
995                         error(attr.pos, "Struct cannot contain itself as a member.")
996                     if self.typedef_flag:
997                         while type.is_ptr:
998                             type = type.base_type
999                         if type == self.entry.type:
1000                             need_typedef_indirection = True
1001                 if need_typedef_indirection:
1002                     # C can't handle typedef structs that refer to themselves. 
1003                     struct_entry = self.entry
1004                     self.entry = env.declare_typedef(
1005                         self.name, struct_entry.type, self.pos,
1006                         cname = self.cname, visibility='ignore')
1007                     struct_entry.type.typedef_flag = False
1008                     # FIXME: this might be considered a hack ;-)
1009                     struct_entry.cname = struct_entry.type.cname = \
1010                                          '_' + self.entry.type.typedef_cname
1011     
1012     def analyse_expressions(self, env):
1013         pass
1014     
1015     def generate_execution_code(self, code):
1016         pass
1017
1018
1019 class CppClassNode(CStructOrUnionDefNode):
1020
1021     #  name          string
1022     #  cname         string or None
1023     #  visibility    "extern"
1024     #  in_pxd        boolean
1025     #  attributes    [CVarDefNode] or None
1026     #  entry         Entry
1027     #  base_classes  [string]
1028     #  templates     [string] or None
1029
1030     def analyse_declarations(self, env):
1031         scope = None
1032         if self.attributes is not None:
1033             scope = CppClassScope(self.name, env)
1034         base_class_types = []
1035         for base_class_name in self.base_classes:
1036             base_class_entry = env.lookup(base_class_name)
1037             if base_class_entry is None:
1038                 error(self.pos, "'%s' not found" % base_class_name)
1039             elif not base_class_entry.is_type or not base_class_entry.type.is_cpp_class:
1040                 error(self.pos, "'%s' is not a cpp class type" % base_class_name)
1041             else:
1042                 base_class_types.append(base_class_entry.type)
1043         if self.templates is None:
1044             template_types = None
1045         else:
1046             template_types = [PyrexTypes.TemplatePlaceholderType(template_name) for template_name in self.templates]
1047         self.entry = env.declare_cpp_class(
1048             self.name, scope, self.pos,
1049             self.cname, base_class_types, visibility = self.visibility, templates = template_types)
1050         self.entry.is_cpp_class = 1
1051         if self.attributes is not None:
1052             if self.in_pxd and not env.in_cinclude:
1053                 self.entry.defined_in_pxd = 1
1054             for attr in self.attributes:
1055                 attr.analyse_declarations(scope)
1056
1057 class CEnumDefNode(StatNode):
1058     #  name           string or None
1059     #  cname          string or None
1060     #  items          [CEnumDefItemNode]
1061     #  typedef_flag   boolean
1062     #  visibility     "public" or "private"
1063     #  in_pxd         boolean
1064     #  entry          Entry
1065     
1066     child_attrs = ["items"]
1067     
1068     def analyse_declarations(self, env):
1069         self.entry = env.declare_enum(self.name, self.pos,
1070             cname = self.cname, typedef_flag = self.typedef_flag,
1071             visibility = self.visibility)
1072         if self.items is not None:
1073             if self.in_pxd and not env.in_cinclude:
1074                 self.entry.defined_in_pxd = 1
1075             for item in self.items:
1076                 item.analyse_declarations(env, self.entry)
1077
1078     def analyse_expressions(self, env):
1079         pass
1080
1081     def generate_execution_code(self, code):
1082         if self.visibility == 'public':
1083             temp = code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=True)
1084             for item in self.entry.enum_values:
1085                 code.putln("%s = PyInt_FromLong(%s); %s" % (
1086                         temp,
1087                         item.cname,
1088                         code.error_goto_if_null(temp, item.pos)))
1089                 code.put_gotref(temp)
1090                 code.putln('if (__Pyx_SetAttrString(%s, "%s", %s) < 0) %s' % (
1091                         Naming.module_cname, 
1092                         item.name, 
1093                         temp,
1094                         code.error_goto(item.pos)))
1095                 code.put_decref_clear(temp, PyrexTypes.py_object_type)
1096             code.funcstate.release_temp(temp)
1097
1098
1099 class CEnumDefItemNode(StatNode):
1100     #  name     string
1101     #  cname    string or None
1102     #  value    ExprNode or None
1103     
1104     child_attrs = ["value"]
1105
1106     def analyse_declarations(self, env, enum_entry):
1107         if self.value:
1108             self.value.analyse_const_expression(env)
1109             if not self.value.type.is_int:
1110                 self.value = self.value.coerce_to(PyrexTypes.c_int_type, env)
1111                 self.value.analyse_const_expression(env)
1112         entry = env.declare_const(self.name, enum_entry.type, 
1113             self.value, self.pos, cname = self.cname,
1114             visibility = enum_entry.visibility)
1115         enum_entry.enum_values.append(entry)
1116
1117
1118 class CTypeDefNode(StatNode):
1119     #  base_type    CBaseTypeNode
1120     #  declarator   CDeclaratorNode
1121     #  visibility   "public" or "private"
1122     #  in_pxd       boolean
1123
1124     child_attrs = ["base_type", "declarator"]
1125     
1126     def analyse_declarations(self, env):
1127         base = self.base_type.analyse(env)
1128         name_declarator, type = self.declarator.analyse(base, env)
1129         name = name_declarator.name
1130         cname = name_declarator.cname
1131         entry = env.declare_typedef(name, type, self.pos,
1132             cname = cname, visibility = self.visibility)
1133         if self.in_pxd and not env.in_cinclude:
1134             entry.defined_in_pxd = 1
1135     
1136     def analyse_expressions(self, env):
1137         pass
1138     def generate_execution_code(self, code):
1139         pass
1140
1141
1142 class FuncDefNode(StatNode, BlockNode):
1143     #  Base class for function definition nodes.
1144     #
1145     #  return_type     PyrexType
1146     #  #filename        string        C name of filename string const
1147     #  entry           Symtab.Entry
1148     #  needs_closure   boolean        Whether or not this function has inner functions/classes/yield
1149     #  directive_locals { string : NameNode } locals defined by cython.locals(...)
1150     
1151     py_func = None
1152     assmt = None
1153     needs_closure = False
1154     modifiers = []
1155     
1156     def analyse_default_values(self, env):
1157         genv = env.global_scope()
1158         default_seen = 0
1159         for arg in self.args:
1160             if arg.default:
1161                 default_seen = 1
1162                 if arg.is_generic:
1163                     arg.default.analyse_types(env)
1164                     arg.default = arg.default.coerce_to(arg.type, genv)
1165                 else:
1166                     error(arg.pos,
1167                         "This argument cannot have a default value")
1168                     arg.default = None
1169             elif arg.kw_only:
1170                 default_seen = 1
1171             elif default_seen:
1172                 error(arg.pos, "Non-default argument following default argument")
1173
1174     def need_gil_acquisition(self, lenv):
1175         return 0
1176         
1177     def create_local_scope(self, env):
1178         genv = env
1179         while genv.is_py_class_scope or genv.is_c_class_scope:
1180             genv = env.outer_scope
1181         if self.needs_closure:
1182             lenv = ClosureScope(name=self.entry.name,
1183                                 outer_scope = genv,
1184                                 scope_name=self.entry.cname)
1185         else:
1186             lenv = LocalScope(name=self.entry.name,
1187                               outer_scope=genv,
1188                               parent_scope=env)
1189         lenv.return_type = self.return_type
1190         type = self.entry.type
1191         if type.is_cfunction:
1192             lenv.nogil = type.nogil and not type.with_gil
1193         self.local_scope = lenv
1194         lenv.directives = env.directives
1195         return lenv
1196                 
1197     def generate_function_definitions(self, env, code):
1198         import Buffer
1199
1200         lenv = self.local_scope
1201         if lenv.is_closure_scope:
1202             outer_scope_cname = "%s->%s" % (Naming.cur_scope_cname,
1203                                             Naming.outer_scope_cname)
1204         else:
1205             outer_scope_cname = Naming.outer_scope_cname
1206         lenv.mangle_closure_cnames(outer_scope_cname)
1207         # Generate closure function definitions
1208         self.body.generate_function_definitions(lenv, code)
1209         # generate lambda function definitions
1210         for node in lenv.lambda_defs:
1211             node.generate_function_definitions(lenv, code)
1212
1213         is_getbuffer_slot = (self.entry.name == "__getbuffer__" and
1214                              self.entry.scope.is_c_class_scope)
1215         is_releasebuffer_slot = (self.entry.name == "__releasebuffer__" and
1216                                  self.entry.scope.is_c_class_scope)
1217         is_buffer_slot = is_getbuffer_slot or is_releasebuffer_slot
1218         if is_buffer_slot:
1219             if 'cython_unused' not in self.modifiers:
1220                 self.modifiers = self.modifiers + ['cython_unused']
1221
1222         preprocessor_guard = None
1223         if self.entry.is_special and not is_buffer_slot:
1224             slot = TypeSlots.method_name_to_slot.get(self.entry.name)
1225             if slot:
1226                 preprocessor_guard = slot.preprocessor_guard_code()
1227                 if (self.entry.name == '__long__' and
1228                     not self.entry.scope.lookup_here('__int__')):
1229                     preprocessor_guard = None
1230         
1231         profile = code.globalstate.directives['profile']
1232         if profile:
1233             if lenv.nogil:
1234                 error(self.pos, "Cannot profile nogil function.")
1235             code.globalstate.use_utility_code(profile_utility_code)
1236
1237         # Generate C code for header and body of function
1238         code.enter_cfunc_scope()
1239         code.return_from_error_cleanup_label = code.new_label()
1240             
1241         # ----- Top-level constants used by this function
1242         code.mark_pos(self.pos)
1243         self.generate_cached_builtins_decls(lenv, code)
1244         # ----- Function header
1245         code.putln("")
1246
1247         if preprocessor_guard:
1248             code.putln(preprocessor_guard)
1249
1250         with_pymethdef = self.needs_assignment_synthesis(env, code)
1251         if self.py_func:
1252             self.py_func.generate_function_header(code, 
1253                 with_pymethdef = with_pymethdef,
1254                 proto_only=True)
1255         self.generate_function_header(code,
1256             with_pymethdef = with_pymethdef)
1257         # ----- Local variable declarations
1258         if lenv.is_closure_scope:
1259             code.put(lenv.scope_class.type.declaration_code(Naming.cur_scope_cname))
1260             code.putln(";")
1261         elif env.is_closure_scope:
1262             code.put(env.scope_class.type.declaration_code(Naming.outer_scope_cname))
1263             code.putln(";")
1264         self.generate_argument_declarations(lenv, code)
1265         for entry in lenv.var_entries:
1266             if not entry.in_closure:
1267                 code.put_var_declaration(entry)
1268         init = ""
1269         if not self.return_type.is_void:
1270             if self.return_type.is_pyobject:
1271                 init = " = NULL"
1272             code.putln(
1273                 "%s%s;" % 
1274                     (self.return_type.declaration_code(Naming.retval_cname),
1275                      init))
1276         tempvardecl_code = code.insertion_point()
1277         self.generate_keyword_list(code)
1278         if profile:
1279             code.put_trace_declarations()
1280         # ----- Extern library function declarations
1281         lenv.generate_library_function_declarations(code)
1282         # ----- GIL acquisition
1283         acquire_gil = self.acquire_gil
1284         if acquire_gil:
1285             env.use_utility_code(force_init_threads_utility_code)
1286             code.putln("#ifdef WITH_THREAD")
1287             code.putln("PyGILState_STATE _save = PyGILState_Ensure();")
1288             code.putln("#endif")
1289         # ----- set up refnanny
1290         if not lenv.nogil:
1291             code.put_setup_refcount_context(self.entry.name)
1292         # ----- Automatic lead-ins for certain special functions
1293         if is_getbuffer_slot:
1294             self.getbuffer_init(code)
1295         # ----- Create closure scope object
1296         if self.needs_closure:
1297             code.putln("%s = (%s)%s->tp_new(%s, %s, NULL);" % (
1298                 Naming.cur_scope_cname,
1299                 lenv.scope_class.type.declaration_code(''),
1300                 lenv.scope_class.type.typeptr_cname, 
1301                 lenv.scope_class.type.typeptr_cname,
1302                 Naming.empty_tuple))
1303             code.putln("if (unlikely(!%s)) {" % Naming.cur_scope_cname)
1304             if is_getbuffer_slot:
1305                 self.getbuffer_error_cleanup(code)
1306             if not lenv.nogil:
1307                 code.put_finish_refcount_context()
1308             # FIXME: what if the error return value is a Python value?
1309             code.putln("return %s;" % self.error_value())
1310             code.putln("}")
1311             code.put_gotref(Naming.cur_scope_cname)
1312             # Note that it is unsafe to decref the scope at this point.
1313         if env.is_closure_scope:
1314             code.putln("%s = (%s)%s;" % (
1315                             outer_scope_cname,
1316                             env.scope_class.type.declaration_code(''),
1317                             Naming.self_cname))
1318             if self.needs_closure:
1319                 # inner closures own a reference to their outer parent
1320                 code.put_incref(outer_scope_cname, env.scope_class.type)
1321                 code.put_giveref(outer_scope_cname)
1322         # ----- Trace function call
1323         if profile:
1324             # this looks a bit late, but if we don't get here due to a
1325             # fatal error before hand, it's not really worth tracing
1326             code.put_trace_call(self.entry.name, self.pos)
1327         # ----- Fetch arguments
1328         self.generate_argument_parsing_code(env, code)
1329         # If an argument is assigned to in the body, we must 
1330         # incref it to properly keep track of refcounts.
1331         for entry in lenv.arg_entries:
1332             if entry.type.is_pyobject:
1333                 if entry.assignments and not entry.in_closure:
1334                     code.put_var_incref(entry)
1335         # ----- Initialise local variables 
1336         for entry in lenv.var_entries:
1337             if entry.type.is_pyobject and entry.init_to_none and entry.used:
1338                 code.put_init_var_to_py_none(entry)
1339         # ----- Initialise local buffer auxiliary variables
1340         for entry in lenv.var_entries + lenv.arg_entries:
1341             if entry.type.is_buffer and entry.buffer_aux.buffer_info_var.used:
1342                 code.putln("%s.buf = NULL;" %
1343                            entry.buffer_aux.buffer_info_var.cname)
1344         # ----- Check and convert arguments
1345         self.generate_argument_type_tests(code)
1346         # ----- Acquire buffer arguments
1347         for entry in lenv.arg_entries:
1348             if entry.type.is_buffer:
1349                 Buffer.put_acquire_arg_buffer(entry, code, self.pos)
1350
1351         # -------------------------
1352         # ----- Function body -----
1353         # -------------------------
1354         self.body.generate_execution_code(code)
1355
1356         # ----- Default return value
1357         code.putln("")
1358         if self.return_type.is_pyobject:
1359             #if self.return_type.is_extension_type:
1360             #    lhs = "(PyObject *)%s" % Naming.retval_cname
1361             #else:
1362             lhs = Naming.retval_cname
1363             code.put_init_to_py_none(lhs, self.return_type)
1364         else:
1365             val = self.return_type.default_value
1366             if val:
1367                 code.putln("%s = %s;" % (Naming.retval_cname, val))
1368         # ----- Error cleanup
1369         if code.error_label in code.labels_used:
1370             code.put_goto(code.return_label)
1371             code.put_label(code.error_label)
1372             for cname, type in code.funcstate.all_managed_temps():
1373                 code.put_xdecref(cname, type)
1374
1375             # Clean up buffers -- this calls a Python function
1376             # so need to save and restore error state
1377             buffers_present = len(lenv.buffer_entries) > 0
1378             if buffers_present:
1379                 code.globalstate.use_utility_code(restore_exception_utility_code)
1380                 code.putln("{ PyObject *__pyx_type, *__pyx_value, *__pyx_tb;")
1381                 code.putln("__Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb);")
1382                 for entry in lenv.buffer_entries:                    
1383                     Buffer.put_release_buffer_code(code, entry)
1384                     #code.putln("%s = 0;" % entry.cname)
1385                 code.putln("__Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);}")
1386
1387             err_val = self.error_value()
1388             exc_check = self.caller_will_check_exceptions()
1389             if err_val is not None or exc_check:
1390                 # TODO: Fix exception tracing (though currently unused by cProfile). 
1391                 # code.globalstate.use_utility_code(get_exception_tuple_utility_code)
1392                 # code.put_trace_exception()
1393                 code.putln('__Pyx_AddTraceback("%s");' % self.entry.qualified_name)
1394             else:
1395                 warning(self.entry.pos, "Unraisable exception in function '%s'." \
1396                             % self.entry.qualified_name, 0)
1397                 code.putln(
1398                     '__Pyx_WriteUnraisable("%s");' % 
1399                         self.entry.qualified_name)
1400                 env.use_utility_code(unraisable_exception_utility_code)
1401                 env.use_utility_code(restore_exception_utility_code)
1402             default_retval = self.return_type.default_value
1403             if err_val is None and default_retval:
1404                 err_val = default_retval
1405             if err_val is not None:
1406                 code.putln("%s = %s;" % (Naming.retval_cname, err_val))
1407
1408             if is_getbuffer_slot:
1409                 self.getbuffer_error_cleanup(code)
1410
1411             # If we are using the non-error cleanup section we should
1412             # jump past it if we have an error. The if-test below determine
1413             # whether this section is used.
1414             if buffers_present or is_getbuffer_slot:
1415                 code.put_goto(code.return_from_error_cleanup_label)
1416
1417
1418         # ----- Non-error return cleanup
1419         code.put_label(code.return_label)
1420         for entry in lenv.buffer_entries:
1421             if entry.used:
1422                 Buffer.put_release_buffer_code(code, entry)
1423         if is_getbuffer_slot:
1424             self.getbuffer_normal_cleanup(code)
1425         # ----- Return cleanup for both error and no-error return
1426         code.put_label(code.return_from_error_cleanup_label)
1427         if not Options.init_local_none:
1428             for entry in lenv.var_entries:
1429                 if lenv.control_flow.get_state((entry.name, 'initialized')) is not True:
1430                     entry.xdecref_cleanup = 1
1431         
1432         for entry in lenv.var_entries:
1433             if entry.type.is_pyobject:
1434                 if entry.used and not entry.in_closure:
1435                     code.put_var_decref(entry)
1436                 elif entry.in_closure and self.needs_closure:
1437                     code.put_giveref(entry.cname)
1438         # Decref any increfed args
1439         for entry in lenv.arg_entries:
1440             if entry.type.is_pyobject:
1441                 if entry.in_closure:
1442                     code.put_var_giveref(entry)
1443                 elif entry.assignments:
1444                     code.put_var_decref(entry)
1445         if self.needs_closure:
1446             code.put_decref(Naming.cur_scope_cname, lenv.scope_class.type)
1447                 
1448         # ----- Return
1449         # This code is duplicated in ModuleNode.generate_module_init_func
1450         if not lenv.nogil:
1451             default_retval = self.return_type.default_value
1452             err_val = self.error_value()
1453             if err_val is None and default_retval:
1454                 err_val = default_retval
1455             if self.return_type.is_pyobject:
1456                 code.put_xgiveref(self.return_type.as_pyobject(Naming.retval_cname))
1457
1458         if self.entry.is_special and self.entry.name == "__hash__":
1459             # Returning -1 for __hash__ is supposed to signal an error
1460             # We do as Python instances and coerce -1 into -2. 
1461             code.putln("if (unlikely(%s == -1) && !PyErr_Occurred()) %s = -2;" % (
1462                     Naming.retval_cname, Naming.retval_cname))
1463
1464         if profile:
1465             if self.return_type.is_pyobject:
1466                 code.put_trace_return(Naming.retval_cname)
1467             else:
1468                 code.put_trace_return("Py_None")
1469         if not lenv.nogil:
1470             code.put_finish_refcount_context()
1471         
1472         if acquire_gil:
1473             code.putln("#ifdef WITH_THREAD")
1474             code.putln("PyGILState_Release(_save);")
1475             code.putln("#endif")
1476
1477         if not self.return_type.is_void:
1478             code.putln("return %s;" % Naming.retval_cname)
1479             
1480         code.putln("}")
1481
1482         if preprocessor_guard:
1483             code.putln("#endif /*!(%s)*/" % preprocessor_guard)
1484
1485         # ----- Go back and insert temp variable declarations
1486         tempvardecl_code.put_temp_declarations(code.funcstate)
1487         # ----- Python version
1488         code.exit_cfunc_scope()
1489         if self.py_func:
1490             self.py_func.generate_function_definitions(env, code)
1491         self.generate_wrapper_functions(code)
1492
1493     def declare_argument(self, env, arg):
1494         if arg.type.is_void:
1495             error(arg.pos, "Invalid use of 'void'")
1496         elif not arg.type.is_complete() and not arg.type.is_array:
1497             error(arg.pos,
1498                 "Argument type '%s' is incomplete" % arg.type)
1499         return env.declare_arg(arg.name, arg.type, arg.pos)
1500     
1501     def generate_arg_type_test(self, arg, code):
1502         # Generate type test for one argument.
1503         if arg.type.typeobj_is_available():
1504             code.globalstate.use_utility_code(arg_type_test_utility_code)
1505             typeptr_cname = arg.type.typeptr_cname
1506             arg_code = "((PyObject *)%s)" % arg.entry.cname
1507             code.putln(
1508                 'if (unlikely(!__Pyx_ArgTypeTest(%s, %s, %d, "%s", %s))) %s' % (
1509                     arg_code, 
1510                     typeptr_cname,
1511                     arg.accept_none,
1512                     arg.name,
1513                     arg.type.is_builtin_type,
1514                     code.error_goto(arg.pos)))
1515         else:
1516             error(arg.pos, "Cannot test type of extern C class "
1517                 "without type object name specification")
1518
1519     def generate_arg_none_check(self, arg, code):
1520         # Generate None check for one argument.
1521         code.globalstate.use_utility_code(arg_type_test_utility_code)
1522         code.putln('if (unlikely(((PyObject *)%s) == Py_None)) {' % arg.entry.cname)
1523         code.putln('''PyErr_Format(PyExc_TypeError, "Argument '%s' must not be None"); %s''' % (
1524             arg.name,
1525             code.error_goto(arg.pos)))
1526         code.putln('}')
1527         
1528     def generate_wrapper_functions(self, code):
1529         pass
1530
1531     def generate_execution_code(self, code):
1532         # Evaluate and store argument default values
1533         for arg in self.args:
1534             default = arg.default
1535             if default:
1536                 if not default.is_literal:
1537                     default.generate_evaluation_code(code)
1538                     default.make_owned_reference(code)
1539                     result = default.result_as(arg.type)
1540                     code.putln(
1541                         "%s = %s;" % (
1542                             arg.calculate_default_value_code(code),
1543                             result))
1544                     if arg.type.is_pyobject:
1545                         code.put_giveref(default.result())
1546                     default.generate_post_assignment_code(code)
1547                     default.free_temps(code)
1548         # For Python class methods, create and store function object
1549         if self.assmt:
1550             self.assmt.generate_execution_code(code)
1551
1552     #
1553     # Special code for the __getbuffer__ function
1554     #
1555     def getbuffer_init(self, code):
1556         info = self.local_scope.arg_entries[1].cname
1557         # Python 3.0 betas have a bug in memoryview which makes it call
1558         # getbuffer with a NULL parameter. For now we work around this;
1559         # the following line should be removed when this bug is fixed.
1560         code.putln("if (%s == NULL) return 0;" % info) 
1561         code.putln("%s->obj = Py_None; __Pyx_INCREF(Py_None);" % info)
1562         code.put_giveref("%s->obj" % info) # Do not refnanny object within structs
1563
1564     def getbuffer_error_cleanup(self, code):
1565         info = self.local_scope.arg_entries[1].cname
1566         code.put_gotref("%s->obj" % info)
1567         code.putln("__Pyx_DECREF(%s->obj); %s->obj = NULL;" %
1568                    (info, info))
1569
1570     def getbuffer_normal_cleanup(self, code):
1571         info = self.local_scope.arg_entries[1].cname
1572         code.putln("if (%s->obj == Py_None) {" % info)
1573         code.put_gotref("Py_None")
1574         code.putln("__Pyx_DECREF(Py_None); %s->obj = NULL;" % info)
1575         code.putln("}")
1576
1577 class CFuncDefNode(FuncDefNode):
1578     #  C function definition.
1579     #
1580     #  modifiers     ['inline']
1581     #  visibility    'private' or 'public' or 'extern'
1582     #  base_type     CBaseTypeNode
1583     #  declarator    CDeclaratorNode
1584     #  body          StatListNode
1585     #  api           boolean
1586     #  decorators    [DecoratorNode]        list of decorators
1587     #
1588     #  with_gil      boolean    Acquire GIL around body
1589     #  type          CFuncType
1590     #  py_func       wrapper for calling from Python
1591     #  overridable   whether or not this is a cpdef function
1592     #  inline_in_pxd whether this is an inline function in a pxd file
1593     
1594     child_attrs = ["base_type", "declarator", "body", "py_func"]
1595
1596     inline_in_pxd = False
1597     decorators = None
1598     directive_locals = {}
1599
1600     def unqualified_name(self):
1601         return self.entry.name
1602         
1603     def analyse_declarations(self, env):
1604         self.directive_locals.update(env.directives['locals'])
1605         base_type = self.base_type.analyse(env)
1606         # The 2 here is because we need both function and argument names.
1607         name_declarator, type = self.declarator.analyse(base_type, env, nonempty = 2 * (self.body is not None))
1608         if not type.is_cfunction:
1609             error(self.pos, 
1610                 "Suite attached to non-function declaration")
1611         # Remember the actual type according to the function header
1612         # written here, because the type in the symbol table entry
1613         # may be different if we're overriding a C method inherited
1614         # from the base type of an extension type.
1615         self.type = type
1616         type.is_overridable = self.overridable
1617         declarator = self.declarator
1618         while not hasattr(declarator, 'args'):
1619             declarator = declarator.base
1620         self.args = declarator.args
1621         for formal_arg, type_arg in zip(self.args, type.args):
1622             formal_arg.type = type_arg.type
1623             formal_arg.name = type_arg.name
1624             formal_arg.cname = type_arg.cname
1625         name = name_declarator.name
1626         cname = name_declarator.cname
1627         self.entry = env.declare_cfunction(
1628             name, type, self.pos, 
1629             cname = cname, visibility = self.visibility,
1630             defining = self.body is not None,
1631             api = self.api, modifiers = self.modifiers)
1632         self.entry.inline_func_in_pxd = self.inline_in_pxd
1633         self.return_type = type.return_type
1634         
1635         if self.overridable and not env.is_module_scope:
1636             if len(self.args) < 1 or not self.args[0].type.is_pyobject:
1637                 # An error will be produced in the cdef function
1638                 self.overridable = False
1639             
1640         if self.overridable:
1641             import ExprNodes
1642             py_func_body = self.call_self_node(is_module_scope = env.is_module_scope)
1643             self.py_func = DefNode(pos = self.pos, 
1644                                    name = self.entry.name,
1645                                    args = self.args,
1646                                    star_arg = None,
1647                                    starstar_arg = None,
1648                                    doc = self.doc,
1649                                    body = py_func_body,
1650                                    is_wrapper = 1)
1651             self.py_func.is_module_scope = env.is_module_scope
1652             self.py_func.analyse_declarations(env)
1653             self.entry.as_variable = self.py_func.entry
1654             # Reset scope entry the above cfunction
1655             env.entries[name] = self.entry
1656             if not env.is_module_scope or Options.lookup_module_cpdef:
1657                 self.override = OverrideCheckNode(self.pos, py_func = self.py_func)
1658                 self.body = StatListNode(self.pos, stats=[self.override, self.body])
1659         self.create_local_scope(env)
1660     
1661     def call_self_node(self, omit_optional_args=0, is_module_scope=0):
1662         import ExprNodes
1663         args = self.type.args
1664         if omit_optional_args:
1665             args = args[:len(args) - self.type.optional_arg_count]
1666         arg_names = [arg.name for arg in args]
1667         if is_module_scope:
1668             cfunc = ExprNodes.NameNode(self.pos, name=self.entry.name)
1669         else:
1670             self_arg = ExprNodes.NameNode(self.pos, name=arg_names[0])
1671             cfunc = ExprNodes.AttributeNode(self.pos, obj=self_arg, attribute=self.entry.name)
1672         skip_dispatch = not is_module_scope or Options.lookup_module_cpdef
1673         c_call = ExprNodes.SimpleCallNode(self.pos, function=cfunc, args=[ExprNodes.NameNode(self.pos, name=n) for n in arg_names[1-is_module_scope:]], wrapper_call=skip_dispatch)
1674         return ReturnStatNode(pos=self.pos, return_type=PyrexTypes.py_object_type, value=c_call)
1675     
1676     def declare_arguments(self, env):
1677         for arg in self.type.args:
1678             if not arg.name:
1679                 error(arg.pos, "Missing argument name")
1680             self.declare_argument(env, arg)
1681
1682     def need_gil_acquisition(self, lenv):
1683         return self.type.with_gil
1684
1685     def nogil_check(self, env):
1686         type = self.type
1687         with_gil = type.with_gil
1688         if type.nogil and not with_gil:
1689             if type.return_type.is_pyobject:
1690                 error(self.pos,
1691                       "Function with Python return type cannot be declared nogil")
1692             for entry in self.local_scope.var_entries:
1693                 if entry.type.is_pyobject:
1694                     error(self.pos, "Function declared nogil has Python locals or temporaries")
1695
1696     def analyse_expressions(self, env):
1697         self.local_scope.directives = env.directives
1698         if self.py_func is not None:
1699             # this will also analyse the default values
1700             self.py_func.analyse_expressions(env)
1701         else:
1702             self.analyse_default_values(env)
1703         self.acquire_gil = self.need_gil_acquisition(self.local_scope)
1704
1705     def needs_assignment_synthesis(self, env, code=None):
1706         return False
1707
1708     def generate_function_header(self, code, with_pymethdef, with_opt_args = 1, with_dispatch = 1, cname = None):
1709         arg_decls = []
1710         type = self.type
1711         visibility = self.entry.visibility
1712         for arg in type.args[:len(type.args)-type.optional_arg_count]:
1713             arg_decls.append(arg.declaration_code())
1714         if with_dispatch and self.overridable:
1715             arg_decls.append(PyrexTypes.c_int_type.declaration_code(Naming.skip_dispatch_cname))
1716         if type.optional_arg_count and with_opt_args:
1717             arg_decls.append(type.op_arg_struct.declaration_code(Naming.optional_args_cname))
1718         if type.has_varargs:
1719             arg_decls.append("...")
1720         if not arg_decls:
1721             arg_decls = ["void"]
1722         if cname is None:
1723             cname = self.entry.func_cname
1724         entity = type.function_header_code(cname, ', '.join(arg_decls))
1725         if visibility == 'public':
1726             dll_linkage = "DL_EXPORT"
1727         else:
1728             dll_linkage = None
1729         header = self.return_type.declaration_code(entity,
1730             dll_linkage = dll_linkage)
1731         if visibility == 'extern':
1732             storage_class = "%s " % Naming.extern_c_macro
1733         elif visibility == 'public':
1734             storage_class = ""
1735         else:
1736             storage_class = "static "
1737         if 'inline' in self.modifiers:
1738             self.modifiers[self.modifiers.index('inline')] = 'cython_inline'
1739         code.putln("%s%s %s {" % (
1740             storage_class,
1741             ' '.join(self.modifiers).upper(), # macro forms 
1742             header))
1743
1744     def generate_argument_declarations(self, env, code):
1745         for arg in self.args:
1746             if arg.default:
1747                 result = arg.calculate_default_value_code(code)
1748                 code.putln('%s = %s;' % (
1749                     arg.type.declaration_code(arg.cname), result))
1750
1751     def generate_keyword_list(self, code):
1752         pass
1753         
1754     def generate_argument_parsing_code(self, env, code):
1755         i = 0
1756         if self.type.optional_arg_count:
1757             code.putln('if (%s) {' % Naming.optional_args_cname)
1758             for arg in self.args:
1759                 if arg.default:
1760                     code.putln('if (%s->%sn > %s) {' % (Naming.optional_args_cname, Naming.pyrex_prefix, i))
1761                     declarator = arg.declarator
1762                     while not hasattr(declarator, 'name'):
1763                         declarator = declarator.base
1764                     code.putln('%s = %s->%s;' % (arg.cname, Naming.optional_args_cname, self.type.opt_arg_cname(declarator.name)))
1765                     i += 1
1766             for _ in range(self.type.optional_arg_count):
1767                 code.putln('}')
1768             code.putln('}')
1769     
1770     def generate_argument_conversion_code(self, code):
1771         pass
1772     
1773     def generate_argument_type_tests(self, code):
1774         # Generate type tests for args whose type in a parent
1775         # class is a supertype of the declared type.
1776         for arg in self.type.args:
1777             if arg.needs_type_test:
1778                 self.generate_arg_type_test(arg, code)
1779             elif arg.type.is_pyobject and not arg.accept_none:
1780                 self.generate_arg_none_check(arg, code)
1781
1782     def error_value(self):
1783         if self.return_type.is_pyobject:
1784             return "0"
1785         else:
1786             #return None
1787             return self.entry.type.exception_value
1788             
1789     def caller_will_check_exceptions(self):
1790         return self.entry.type.exception_check
1791         
1792     def generate_wrapper_functions(self, code):
1793         # If the C signature of a function has changed, we need to generate
1794         # wrappers to put in the slots here. 
1795         k = 0
1796         entry = self.entry
1797         func_type = entry.type
1798         while entry.prev_entry is not None:
1799             k += 1
1800             entry = entry.prev_entry
1801             entry.func_cname = "%s%swrap_%s" % (self.entry.func_cname, Naming.pyrex_prefix, k)
1802             code.putln()
1803             self.generate_function_header(code, 
1804                                           0,
1805                                           with_dispatch = entry.type.is_overridable, 
1806                                           with_opt_args = entry.type.optional_arg_count, 
1807                                           cname = entry.func_cname)
1808             if not self.return_type.is_void:
1809                 code.put('return ')
1810             args = self.type.args
1811             arglist = [arg.cname for arg in args[:len(args)-self.type.optional_arg_count]]
1812             if entry.type.is_overridable:
1813                 arglist.append(Naming.skip_dispatch_cname)
1814             elif func_type.is_overridable:
1815                 arglist.append('0')
1816             if entry.type.optional_arg_count:
1817                 arglist.append(Naming.optional_args_cname)
1818             elif func_type.optional_arg_count:
1819                 arglist.append('NULL')
1820             code.putln('%s(%s);' % (self.entry.func_cname, ', '.join(arglist)))
1821             code.putln('}')
1822         
1823
1824 class PyArgDeclNode(Node):
1825     # Argument which must be a Python object (used
1826     # for * and ** arguments).
1827     #
1828     # name        string
1829     # entry       Symtab.Entry
1830     # annotation  ExprNode or None   Py3 argument annotation
1831     child_attrs = []
1832
1833     def generate_function_definitions(self, env, code):
1834         self.entry.generate_function_definitions(env, code)
1835
1836 class DecoratorNode(Node):
1837     # A decorator
1838     #
1839     # decorator    NameNode or CallNode or AttributeNode
1840     child_attrs = ['decorator']
1841
1842
1843 class DefNode(FuncDefNode):
1844     # A Python function definition.
1845     #
1846     # name          string                 the Python name of the function
1847     # lambda_name   string                 the internal name of a lambda 'function'
1848     # decorators    [DecoratorNode]        list of decorators
1849     # args          [CArgDeclNode]         formal arguments
1850     # star_arg      PyArgDeclNode or None  * argument
1851     # starstar_arg  PyArgDeclNode or None  ** argument
1852     # doc           EncodedString or None
1853     # body          StatListNode
1854     # return_type_annotation
1855     #               ExprNode or None       the Py3 return type annotation
1856     #
1857     #  The following subnode is constructed internally
1858     #  when the def statement is inside a Python class definition.
1859     #
1860     #  assmt   AssignmentNode   Function construction/assignment
1861     
1862     child_attrs = ["args", "star_arg", "starstar_arg", "body", "decorators"]
1863
1864     lambda_name = None
1865     assmt = None
1866     num_kwonly_args = 0
1867     num_required_kw_args = 0
1868     reqd_kw_flags_cname = "0"
1869     is_wrapper = 0
1870     decorators = None
1871     return_type_annotation = None
1872     entry = None
1873     acquire_gil = 0
1874     self_in_stararg = 0
1875
1876     def __init__(self, pos, **kwds):
1877         FuncDefNode.__init__(self, pos, **kwds)
1878         k = rk = r = 0
1879         for arg in self.args:
1880             if arg.kw_only:
1881                 k += 1
1882                 if not arg.default:
1883                     rk += 1
1884             if not arg.default:
1885                 r += 1
1886         self.num_kwonly_args = k
1887         self.num_required_kw_args = rk
1888         self.num_required_args = r
1889         
1890     def as_cfunction(self, cfunc=None, scope=None):
1891         if self.star_arg:
1892             error(self.star_arg.pos, "cdef function cannot have star argument")
1893         if self.starstar_arg:
1894             error(self.starstar_arg.pos, "cdef function cannot have starstar argument")
1895         if cfunc is None:
1896             cfunc_args = []
1897             for formal_arg in self.args:
1898                 name_declarator, type = formal_arg.analyse(scope, nonempty=1)
1899                 cfunc_args.append(PyrexTypes.CFuncTypeArg(name = name_declarator.name,
1900                                                           cname = None,
1901                                                           type = py_object_type,
1902                                                           pos = formal_arg.pos))
1903             cfunc_type = PyrexTypes.CFuncType(return_type = py_object_type,
1904                                               args = cfunc_args,
1905                                               has_varargs = False,
1906                                               exception_value = None,
1907                                               exception_check = False,
1908                                               nogil = False,
1909                                               with_gil = False,
1910                                               is_overridable = True)
1911             cfunc = CVarDefNode(self.pos, type=cfunc_type)
1912         else:
1913             if scope is None:
1914                 scope = cfunc.scope
1915             cfunc_type = cfunc.type
1916             if len(self.args) != len(cfunc_type.args) or cfunc_type.has_varargs:
1917                 error(self.pos, "wrong number of arguments")
1918                 error(cfunc.pos, "previous declaration here")
1919             for i, (formal_arg, type_arg) in enumerate(zip(self.args, cfunc_type.args)):
1920                 name_declarator, type = formal_arg.analyse(scope, nonempty=1,
1921                                                            is_self_arg = (i == 0 and scope.is_c_class_scope))
1922                 if type is None or type is PyrexTypes.py_object_type:
1923                     formal_arg.type = type_arg.type
1924                     formal_arg.name_declarator = name_declarator
1925         import ExprNodes
1926         if cfunc_type.exception_value is None:
1927             exception_value = None
1928         else:
1929             exception_value = ExprNodes.ConstNode(self.pos, value=cfunc_type.exception_value, type=cfunc_type.return_type)
1930         declarator = CFuncDeclaratorNode(self.pos, 
1931                                          base = CNameDeclaratorNode(self.pos, name=self.name, cname=None),
1932                                          args = self.args,
1933                                          has_varargs = False,
1934                                          exception_check = cfunc_type.exception_check,
1935                                          exception_value = exception_value,
1936                                          with_gil = cfunc_type.with_gil,
1937                                          nogil = cfunc_type.nogil)
1938         return CFuncDefNode(self.pos, 
1939                             modifiers = [],
1940                             base_type = CAnalysedBaseTypeNode(self.pos, type=cfunc_type.return_type),
1941                             declarator = declarator,
1942                             body = self.body,
1943                             doc = self.doc,
1944                             overridable = cfunc_type.is_overridable,
1945                             type = cfunc_type,
1946                             with_gil = cfunc_type.with_gil,
1947                             nogil = cfunc_type.nogil,
1948                             visibility = 'private',
1949                             api = False,
1950                             directive_locals = getattr(cfunc, 'directive_locals', {}))
1951     
1952     def analyse_declarations(self, env):
1953         self.is_classmethod = self.is_staticmethod = False
1954         if self.decorators:
1955             for decorator in self.decorators:
1956                 func = decorator.decorator
1957                 if func.is_name:
1958                     self.is_classmethod |= func.name == 'classmethod'
1959                     self.is_staticmethod |= func.name == 'staticmethod'
1960
1961         if self.is_classmethod and env.lookup_here('classmethod'):
1962             # classmethod() was overridden - not much we can do here ...
1963             self.is_classmethod = False
1964         if self.is_staticmethod and env.lookup_here('staticmethod'):
1965             # staticmethod() was overridden - not much we can do here ...
1966             self.is_staticmethod = False
1967
1968         if self.name == '__new__':
1969             self.is_staticmethod = 1
1970
1971         self.analyse_argument_types(env)
1972         if self.name == '<lambda>':
1973             self.declare_lambda_function(env)
1974         else:
1975             self.declare_pyfunction(env)
1976         self.analyse_signature(env)
1977         self.return_type = self.entry.signature.return_type()
1978         self.create_local_scope(env)
1979
1980     def analyse_argument_types(self, env):
1981         directive_locals = self.directive_locals = env.directives['locals']
1982         allow_none_for_extension_args = env.directives['allow_none_for_extension_args']
1983         for arg in self.args:
1984             if hasattr(arg, 'name'):
1985                 type = arg.type
1986                 name_declarator = None
1987             else:
1988                 base_type = arg.base_type.analyse(env)
1989                 name_declarator, type = \
1990                     arg.declarator.analyse(base_type, env)
1991                 arg.name = name_declarator.name
1992             if arg.name in directive_locals:
1993                 type_node = directive_locals[arg.name]
1994                 other_type = type_node.analyse_as_type(env)
1995                 if other_type is None:
1996                     error(type_node.pos, "Not a type")
1997                 elif (type is not PyrexTypes.py_object_type 
1998                         and not type.same_as(other_type)):
1999                     error(arg.base_type.pos, "Signature does not agree with previous declaration")
2000                     error(type_node.pos, "Previous declaration here")
2001                 else:
2002                     type = other_type
2003             if name_declarator and name_declarator.cname:
2004                 error(self.pos,
2005                     "Python function argument cannot have C name specification")
2006             arg.type = type.as_argument_type()
2007             arg.hdr_type = None
2008             arg.needs_conversion = 0
2009             arg.needs_type_test = 0
2010             arg.is_generic = 1
2011             if arg.type.is_pyobject:
2012                 if arg.or_none:
2013                     arg.accept_none = True
2014                 elif arg.not_none:
2015                     arg.accept_none = False
2016                 elif arg.type.is_extension_type or arg.type.is_builtin_type:
2017                     if arg.default and arg.default.constant_result is None:
2018                         # special case: def func(MyType obj = None)
2019                         arg.accept_none = True
2020                     else:
2021                         # default depends on compiler directive
2022                         arg.accept_none = allow_none_for_extension_args
2023                 else:
2024                     # probably just a plain 'object'
2025                     arg.accept_none = True
2026             else:
2027                 arg.accept_none = True # won't be used, but must be there
2028                 if arg.not_none:
2029                     error(arg.pos, "Only Python type arguments can have 'not None'")
2030                 if arg.or_none:
2031                     error(arg.pos, "Only Python type arguments can have 'or None'")
2032
2033     def analyse_signature(self, env):
2034         if self.entry.is_special:
2035             self.entry.trivial_signature = len(self.args) == 1 and not (self.star_arg or self.starstar_arg)
2036         elif not env.directives['always_allow_keywords'] and not (self.star_arg or self.starstar_arg):
2037             # Use the simpler calling signature for zero- and one-argument functions.
2038             if self.entry.signature is TypeSlots.pyfunction_signature:
2039                 if len(self.args) == 0:
2040                     self.entry.signature = TypeSlots.pyfunction_noargs
2041                 elif len(self.args) == 1:
2042                     if self.args[0].default is None and not self.args[0].kw_only:
2043                         self.entry.signature = TypeSlots.pyfunction_onearg
2044             elif self.entry.signature is TypeSlots.pymethod_signature:
2045                 if len(self.args) == 1:
2046                     self.entry.signature = TypeSlots.unaryfunc
2047                 elif len(self.args) == 2:
2048                     if self.args[1].default is None and not self.args[1].kw_only:
2049                         self.entry.signature = TypeSlots.ibinaryfunc
2050
2051         sig = self.entry.signature
2052         nfixed = sig.num_fixed_args()
2053         if sig is TypeSlots.pymethod_signature and nfixed == 1 \
2054                and len(self.args) == 0 and self.star_arg:
2055             # this is the only case where a diverging number of
2056             # arguments is not an error - when we have no explicit
2057             # 'self' parameter as in method(*args)
2058             sig = self.entry.signature = TypeSlots.pyfunction_signature # self is not 'really' used
2059             self.self_in_stararg = 1
2060             nfixed = 0
2061
2062         for i in range(min(nfixed, len(self.args))):
2063             arg = self.args[i]
2064             arg.is_generic = 0
2065             if sig.is_self_arg(i) and not self.is_staticmethod:
2066                 if self.is_classmethod:
2067                     arg.is_type_arg = 1
2068                     arg.hdr_type = arg.type = Builtin.type_type
2069                 else:
2070                     arg.is_self_arg = 1
2071                     arg.hdr_type = arg.type = env.parent_type
2072                 arg.needs_conversion = 0
2073             else:
2074                 arg.hdr_type = sig.fixed_arg_type(i)
2075                 if not arg.type.same_as(arg.hdr_type):
2076                     if arg.hdr_type.is_pyobject and arg.type.is_pyobject:
2077                         arg.needs_type_test = 1
2078                     else:
2079                         arg.needs_conversion = 1
2080             if arg.needs_conversion:
2081                 arg.hdr_cname = Naming.arg_prefix + arg.name
2082             else:
2083                 arg.hdr_cname = Naming.var_prefix + arg.name
2084
2085         if nfixed > len(self.args):
2086             self.bad_signature()
2087             return
2088         elif nfixed < len(self.args):
2089             if not sig.has_generic_args:
2090                 self.bad_signature()
2091             for arg in self.args:
2092                 if arg.is_generic and \
2093                         (arg.type.is_extension_type or arg.type.is_builtin_type):
2094                     arg.needs_type_test = 1
2095
2096     def bad_signature(self):
2097         sig = self.entry.signature
2098         expected_str = "%d" % sig.num_fixed_args()
2099         if sig.has_generic_args:
2100             expected_str = expected_str + " or more"
2101         name = self.name
2102         if name.startswith("__") and name.endswith("__"):
2103             desc = "Special method"
2104         else:
2105             desc = "Method"
2106         error(self.pos,
2107             "%s %s has wrong number of arguments "
2108             "(%d declared, %s expected)" % (
2109                 desc, self.name, len(self.args), expected_str))
2110
2111     def signature_has_nongeneric_args(self):
2112         argcount = len(self.args)
2113         if argcount == 0 or (
2114                 argcount == 1 and (self.args[0].is_self_arg or
2115                                    self.args[0].is_type_arg)):
2116             return 0
2117         return 1
2118
2119     def signature_has_generic_args(self):
2120         return self.entry.signature.has_generic_args
2121     
2122     def declare_pyfunction(self, env):
2123         #print "DefNode.declare_pyfunction:", self.name, "in", env ###
2124         name = self.name
2125         entry = env.lookup_here(name)
2126         if entry and entry.type.is_cfunction and not self.is_wrapper:
2127             warning(self.pos, "Overriding cdef method with def method.", 5)
2128         entry = env.declare_pyfunction(name, self.pos)
2129         self.entry = entry
2130         prefix = env.scope_prefix
2131         entry.func_cname = \
2132             Naming.pyfunc_prefix + prefix + name
2133         entry.pymethdef_cname = \
2134             Naming.pymethdef_prefix + prefix + name
2135         if Options.docstrings:
2136             entry.doc = embed_position(self.pos, self.doc)
2137             entry.doc_cname = \
2138                 Naming.funcdoc_prefix + prefix + name
2139             if entry.is_special:
2140                 if entry.name in TypeSlots.invisible or not entry.doc or (entry.name in '__getattr__' and env.directives['fast_getattr']):
2141                     entry.wrapperbase_cname = None
2142                 else:
2143                     entry.wrapperbase_cname = Naming.wrapperbase_prefix + prefix + name
2144         else:
2145             entry.doc = None
2146
2147     def declare_lambda_function(self, env):
2148         name = self.name
2149         prefix = env.scope_prefix
2150         func_cname = \
2151             Naming.lambda_func_prefix + u'funcdef' + prefix + self.lambda_name
2152         entry = env.declare_lambda_function(func_cname, self.pos)
2153         entry.pymethdef_cname = \
2154             Naming.lambda_func_prefix + u'methdef' + prefix + self.lambda_name
2155         entry.qualified_name = env.qualify_name(self.lambda_name)
2156         entry.doc = None
2157         self.entry = entry
2158
2159     def declare_arguments(self, env):
2160         for arg in self.args:
2161             if not arg.name:
2162                 error(arg.pos, "Missing argument name")
2163             else:
2164                 env.control_flow.set_state((), (arg.name, 'source'), 'arg')
2165                 env.control_flow.set_state((), (arg.name, 'initialized'), True)
2166             if arg.needs_conversion:
2167                 arg.entry = env.declare_var(arg.name, arg.type, arg.pos)
2168                 if arg.type.is_pyobject:
2169                     arg.entry.init = "0"
2170                 arg.entry.init_to_none = 0
2171             else:
2172                 arg.entry = self.declare_argument(env, arg)
2173             arg.entry.used = 1
2174             arg.entry.is_self_arg = arg.is_self_arg
2175             if arg.hdr_type:
2176                 if arg.is_self_arg or arg.is_type_arg or \
2177                     (arg.type.is_extension_type and not arg.hdr_type.is_extension_type):
2178                         arg.entry.is_declared_generic = 1
2179         self.declare_python_arg(env, self.star_arg)
2180         self.declare_python_arg(env, self.starstar_arg)
2181
2182     def declare_python_arg(self, env, arg):
2183         if arg:
2184             if env.directives['infer_types'] != False:
2185                 type = PyrexTypes.unspecified_type
2186             else:
2187                 type = py_object_type
2188             entry = env.declare_var(arg.name, type, arg.pos)
2189             entry.used = 1
2190             entry.init = "0"
2191             entry.init_to_none = 0
2192             entry.xdecref_cleanup = 1
2193             arg.entry = entry
2194             env.control_flow.set_state((), (arg.name, 'initialized'), True)
2195             
2196     def analyse_expressions(self, env):
2197         self.local_scope.directives = env.directives
2198         self.analyse_default_values(env)
2199         if self.needs_assignment_synthesis(env):
2200             # Shouldn't we be doing this at the module level too?
2201             self.synthesize_assignment_node(env)
2202
2203     def needs_assignment_synthesis(self, env, code=None):
2204         # Should enable for module level as well, that will require more testing...
2205         if env.is_module_scope:
2206             if code is None:
2207                 return env.directives['binding']
2208             else:
2209                 return code.globalstate.directives['binding']
2210         return env.is_py_class_scope or env.is_closure_scope
2211
2212     def synthesize_assignment_node(self, env):
2213         import ExprNodes
2214         if env.is_py_class_scope:
2215             rhs = ExprNodes.PyCFunctionNode(self.pos,
2216                         pymethdef_cname = self.entry.pymethdef_cname)
2217             if not self.is_staticmethod and not self.is_classmethod:
2218                 rhs.binding = True
2219
2220         elif env.is_closure_scope:
2221             rhs = ExprNodes.InnerFunctionNode(
2222                 self.pos, pymethdef_cname = self.entry.pymethdef_cname)
2223         else:
2224             rhs = ExprNodes.PyCFunctionNode(
2225                 self.pos, pymethdef_cname = self.entry.pymethdef_cname, binding = env.directives['binding'])
2226         self.assmt = SingleAssignmentNode(self.pos,
2227             lhs = ExprNodes.NameNode(self.pos, name = self.name),
2228             rhs = rhs)
2229         self.assmt.analyse_declarations(env)
2230         self.assmt.analyse_expressions(env)
2231             
2232     def generate_function_header(self, code, with_pymethdef, proto_only=0):
2233         arg_code_list = []
2234         sig = self.entry.signature
2235         if sig.has_dummy_arg or self.self_in_stararg:
2236             arg_code_list.append(
2237                 "PyObject *%s" % Naming.self_cname)
2238         for arg in self.args:
2239             if not arg.is_generic:
2240                 if arg.is_self_arg or arg.is_type_arg:
2241                     arg_code_list.append("PyObject *%s" % arg.hdr_cname)
2242                 else:
2243                     arg_code_list.append(
2244                         arg.hdr_type.declaration_code(arg.hdr_cname))
2245         if not self.entry.is_special and sig.method_flags() == [TypeSlots.method_noargs]:
2246             arg_code_list.append("CYTHON_UNUSED PyObject *unused")
2247         if sig.has_generic_args:
2248             arg_code_list.append(
2249                 "PyObject *%s, PyObject *%s"
2250                     % (Naming.args_cname, Naming.kwds_cname))
2251         arg_code = ", ".join(arg_code_list)
2252         dc = self.return_type.declaration_code(self.entry.func_cname)
2253         mf = " ".join(self.modifiers).upper()
2254         if mf: mf += " "
2255         header = "static %s%s(%s)" % (mf, dc, arg_code)
2256         code.putln("%s; /*proto*/" % header)
2257         if proto_only:
2258             return
2259         if (Options.docstrings and self.entry.doc and
2260                 not self.entry.scope.is_property_scope and
2261                 (not self.entry.is_special or self.entry.wrapperbase_cname)):
2262             docstr = self.entry.doc
2263             if docstr.is_unicode:
2264                 docstr = docstr.utf8encode()
2265             code.putln(
2266                 'static char %s[] = "%s";' % (
2267                     self.entry.doc_cname,
2268                     split_string_literal(escape_byte_string(docstr))))
2269             if self.entry.is_special:
2270                 code.putln(
2271                     "struct wrapperbase %s;" % self.entry.wrapperbase_cname)
2272         if with_pymethdef:
2273             code.put(
2274                 "static PyMethodDef %s = " % 
2275                     self.entry.pymethdef_cname)
2276             code.put_pymethoddef(self.entry, ";", allow_skip=False)
2277         code.putln("%s {" % header)
2278
2279     def generate_argument_declarations(self, env, code):
2280         for arg in self.args:
2281             if arg.is_generic: # or arg.needs_conversion:
2282                 if arg.needs_conversion:
2283                     code.putln("PyObject *%s = 0;" % arg.hdr_cname)
2284                 elif not arg.entry.in_closure:
2285                     code.put_var_declaration(arg.entry)
2286
2287     def generate_keyword_list(self, code):
2288         if self.signature_has_generic_args() and \
2289                 self.signature_has_nongeneric_args():
2290             code.put(
2291                 "static PyObject **%s[] = {" %
2292                     Naming.pykwdlist_cname)
2293             for arg in self.args:
2294                 if arg.is_generic:
2295                     pystring_cname = code.intern_identifier(arg.name)
2296                     code.put('&%s,' % pystring_cname)
2297             code.putln("0};")
2298
2299     def generate_argument_parsing_code(self, env, code):
2300         # Generate PyArg_ParseTuple call for generic
2301         # arguments, if any.
2302         if self.entry.signature.has_dummy_arg and not self.self_in_stararg:
2303             # get rid of unused argument warning
2304             code.putln("%s = %s;" % (Naming.self_cname, Naming.self_cname))
2305
2306         old_error_label = code.new_error_label()
2307         our_error_label = code.error_label
2308         end_label = code.new_label("argument_unpacking_done")
2309
2310         has_kwonly_args = self.num_kwonly_args > 0
2311         has_star_or_kw_args = self.star_arg is not None \
2312             or self.starstar_arg is not None or has_kwonly_args
2313
2314         for arg in self.args:
2315             if not arg.type.is_pyobject:
2316                 done = arg.type.create_from_py_utility_code(env)
2317                 if not done: pass # will fail later
2318
2319         if not self.signature_has_generic_args():
2320             if has_star_or_kw_args:
2321                 error(self.pos, "This method cannot have * or keyword arguments")
2322             self.generate_argument_conversion_code(code)
2323
2324         elif not self.signature_has_nongeneric_args():
2325             # func(*args) or func(**kw) or func(*args, **kw)
2326             self.generate_stararg_copy_code(code)
2327
2328         else:
2329             positional_args = []
2330             kw_only_args = []
2331             for arg in self.args:
2332                 arg_entry = arg.entry
2333                 if arg.is_generic:
2334                     if arg.default:
2335                         if not arg.is_self_arg and not arg.is_type_arg:
2336                             if arg.kw_only:
2337                                 kw_only_args.append(arg)
2338                             else:
2339                                 positional_args.append(arg)
2340                     elif arg.kw_only:
2341                         kw_only_args.append(arg)
2342                     elif not arg.is_self_arg and not arg.is_type_arg:
2343                         positional_args.append(arg)
2344
2345             self.generate_tuple_and_keyword_parsing_code(
2346                 positional_args, kw_only_args, end_label, code)
2347
2348         code.error_label = old_error_label
2349         if code.label_used(our_error_label):
2350             if not code.label_used(end_label):
2351                 code.put_goto(end_label)
2352             code.put_label(our_error_label)
2353             if has_star_or_kw_args:
2354                 self.generate_arg_decref(self.star_arg, code)
2355                 if self.starstar_arg:
2356                     if self.starstar_arg.entry.xdecref_cleanup:
2357                         code.put_var_xdecref(self.starstar_arg.entry)
2358                     else:
2359                         code.put_var_decref(self.starstar_arg.entry)
2360             code.putln('__Pyx_AddTraceback("%s");' % self.entry.qualified_name)
2361             # The arguments are put into the closure one after the
2362             # other, so when type errors are found, all references in
2363             # the closure instance must be properly ref-counted to
2364             # facilitate generic closure instance deallocation.  In
2365             # the case of an argument type error, it's best to just
2366             # DECREF+clear the already handled references, as this
2367             # frees their references as early as possible.
2368             for arg in self.args:
2369                 if arg.type.is_pyobject and arg.entry.in_closure:
2370                     code.put_var_xdecref_clear(arg.entry)
2371             if self.needs_closure:
2372                 code.put_decref(Naming.cur_scope_cname, self.local_scope.scope_class.type)
2373             code.put_finish_refcount_context()
2374             code.putln("return %s;" % self.error_value())
2375         if code.label_used(end_label):
2376             code.put_label(end_label)
2377
2378     def generate_arg_assignment(self, arg, item, code):
2379         if arg.type.is_pyobject:
2380             if arg.is_generic:
2381                 item = PyrexTypes.typecast(arg.type, PyrexTypes.py_object_type, item)
2382             entry = arg.entry
2383             code.putln("%s = %s;" % (entry.cname, item))
2384             if entry.in_closure:
2385                 code.put_var_incref(entry)
2386         else:
2387             func = arg.type.from_py_function
2388             if func:
2389                 code.putln("%s = %s(%s); %s" % (
2390                     arg.entry.cname,
2391                     func,
2392                     item,
2393                     code.error_goto_if(arg.type.error_condition(arg.entry.cname), arg.pos)))
2394             else:
2395                 error(arg.pos, "Cannot convert Python object argument to type '%s'" % arg.type)
2396     
2397     def generate_arg_xdecref(self, arg, code):
2398         if arg:
2399             code.put_var_xdecref(arg.entry)
2400     
2401     def generate_arg_decref(self, arg, code):
2402         if arg:
2403             code.put_var_decref(arg.entry)
2404
2405     def generate_stararg_copy_code(self, code):
2406         if not self.star_arg:
2407             code.globalstate.use_utility_code(raise_argtuple_invalid_utility_code)
2408             code.putln("if (unlikely(PyTuple_GET_SIZE(%s) > 0)) {" %
2409                        Naming.args_cname)
2410             code.put('__Pyx_RaiseArgtupleInvalid("%s", 1, 0, 0, PyTuple_GET_SIZE(%s)); return %s;' % (
2411                     self.name, Naming.args_cname, self.error_value()))
2412             code.putln("}")
2413
2414         code.globalstate.use_utility_code(keyword_string_check_utility_code)
2415
2416         if self.starstar_arg:
2417             if self.star_arg:
2418                 kwarg_check = "unlikely(%s)" % Naming.kwds_cname
2419             else:
2420                 kwarg_check = "%s" % Naming.kwds_cname
2421         else:
2422             kwarg_check = "unlikely(%s) && unlikely(PyDict_Size(%s) > 0)" % (
2423                 Naming.kwds_cname, Naming.kwds_cname)
2424         code.putln(
2425             "if (%s && unlikely(!__Pyx_CheckKeywordStrings(%s, \"%s\", %d))) return %s;" % (
2426                 kwarg_check, Naming.kwds_cname, self.name,
2427                 bool(self.starstar_arg), self.error_value()))
2428
2429         if self.starstar_arg:
2430             code.putln("%s = (%s) ? PyDict_Copy(%s) : PyDict_New();" % (
2431                     self.starstar_arg.entry.cname,
2432                     Naming.kwds_cname,
2433                     Naming.kwds_cname))
2434             code.putln("if (unlikely(!%s)) return %s;" % (
2435                     self.starstar_arg.entry.cname, self.error_value()))
2436             self.starstar_arg.entry.xdecref_cleanup = 0
2437             code.put_gotref(self.starstar_arg.entry.cname)
2438
2439         if self.self_in_stararg:
2440             # need to create a new tuple with 'self' inserted as first item
2441             code.put("%s = PyTuple_New(PyTuple_GET_SIZE(%s)+1); if (unlikely(!%s)) " % (
2442                     self.star_arg.entry.cname,
2443                     Naming.args_cname,
2444                     self.star_arg.entry.cname))
2445             if self.starstar_arg:
2446                 code.putln("{")
2447                 code.put_decref_clear(self.starstar_arg.entry.cname, py_object_type)
2448                 code.putln("return %s;" % self.error_value())
2449                 code.putln("}")
2450             else:
2451                 code.putln("return %s;" % self.error_value())
2452             code.put_gotref(self.star_arg.entry.cname)
2453             code.put_incref(Naming.self_cname, py_object_type)
2454             code.put_giveref(Naming.self_cname)
2455             code.putln("PyTuple_SET_ITEM(%s, 0, %s);" % (
2456                 self.star_arg.entry.cname, Naming.self_cname))
2457             temp = code.funcstate.allocate_temp(PyrexTypes.c_py_ssize_t_type, manage_ref=False)
2458             code.putln("for (%s=0; %s < PyTuple_GET_SIZE(%s); %s++) {" % (
2459                 temp, temp, Naming.args_cname, temp))
2460             code.putln("PyObject* item = PyTuple_GET_ITEM(%s, %s);" % (
2461                 Naming.args_cname, temp))
2462             code.put_incref("item", py_object_type)
2463             code.put_giveref("item")
2464             code.putln("PyTuple_SET_ITEM(%s, %s+1, item);" % (
2465                 self.star_arg.entry.cname, temp))
2466             code.putln("}")
2467             code.funcstate.release_temp(temp)
2468             self.star_arg.entry.xdecref_cleanup = 0
2469         elif self.star_arg:
2470             code.put_incref(Naming.args_cname, py_object_type)
2471             code.putln("%s = %s;" % (
2472                     self.star_arg.entry.cname,
2473                     Naming.args_cname))
2474             self.star_arg.entry.xdecref_cleanup = 0
2475
2476     def generate_tuple_and_keyword_parsing_code(self, positional_args,
2477                                                 kw_only_args, success_label, code):
2478         argtuple_error_label = code.new_label("argtuple_error")
2479
2480         min_positional_args = self.num_required_args - self.num_required_kw_args
2481         if len(self.args) > 0 and (self.args[0].is_self_arg or self.args[0].is_type_arg):
2482             min_positional_args -= 1
2483         max_positional_args = len(positional_args)
2484         has_fixed_positional_count = not self.star_arg and \
2485             min_positional_args == max_positional_args
2486
2487         code.globalstate.use_utility_code(raise_double_keywords_utility_code)
2488         code.globalstate.use_utility_code(raise_argtuple_invalid_utility_code)
2489         if self.num_required_kw_args:
2490             code.globalstate.use_utility_code(raise_keyword_required_utility_code)
2491
2492         if self.starstar_arg or self.star_arg:
2493             self.generate_stararg_init_code(max_positional_args, code)
2494
2495         # --- optimised code when we receive keyword arguments
2496         if self.num_required_kw_args:
2497             likely_hint = "likely"
2498         else:
2499             likely_hint = "unlikely"
2500         code.putln("if (%s(%s)) {" % (likely_hint, Naming.kwds_cname))
2501         self.generate_keyword_unpacking_code(
2502             min_positional_args, max_positional_args,
2503             has_fixed_positional_count,
2504             positional_args, kw_only_args, argtuple_error_label, code)
2505
2506         # --- optimised code when we do not receive any keyword arguments
2507         if (self.num_required_kw_args and min_positional_args > 0) or min_positional_args == max_positional_args:
2508             # Python raises arg tuple related errors first, so we must
2509             # check the length here
2510             if min_positional_args == max_positional_args and not self.star_arg:
2511                 compare = '!='
2512             else:
2513                 compare = '<'
2514             code.putln('} else if (PyTuple_GET_SIZE(%s) %s %d) {' % (
2515                     Naming.args_cname, compare, min_positional_args))
2516             code.put_goto(argtuple_error_label)
2517
2518         if self.num_required_kw_args:
2519             # pure error case: keywords required but not passed
2520             if max_positional_args > min_positional_args and not self.star_arg:
2521                 code.putln('} else if (PyTuple_GET_SIZE(%s) > %d) {' % (
2522                         Naming.args_cname, max_positional_args))
2523                 code.put_goto(argtuple_error_label)
2524             code.putln('} else {')
2525             for i, arg in enumerate(kw_only_args):
2526                 if not arg.default:
2527                     pystring_cname = code.intern_identifier(arg.name)
2528                     # required keyword-only argument missing
2529                     code.put('__Pyx_RaiseKeywordRequired("%s", %s); ' % (
2530                             self.name,
2531                             pystring_cname))
2532                     code.putln(code.error_goto(self.pos))
2533                     break
2534
2535         elif min_positional_args == max_positional_args:
2536             # parse the exact number of positional arguments from the
2537             # args tuple
2538             code.putln('} else {')
2539             for i, arg in enumerate(positional_args):
2540                 item = "PyTuple_GET_ITEM(%s, %d)" % (Naming.args_cname, i)
2541                 self.generate_arg_assignment(arg, item, code)
2542             self.generate_arg_default_assignments(code)
2543
2544         else:
2545             # parse the positional arguments from the variable length
2546             # args tuple
2547             code.putln('} else {')
2548             self.generate_arg_default_assignments(code)
2549             code.putln('switch (PyTuple_GET_SIZE(%s)) {' % Naming.args_cname)
2550             if self.star_arg:
2551                 code.putln('default:')
2552             reversed_args = list(enumerate(positional_args))[::-1]
2553             for i, arg in reversed_args:
2554                 if i >= min_positional_args-1:
2555                     if min_positional_args > 1:
2556                         code.putln('case %2d:' % (i+1)) # pure code beautification
2557                     else:
2558                         code.put('case %2d: ' % (i+1))
2559                 item = "PyTuple_GET_ITEM(%s, %d)" % (Naming.args_cname, i)
2560                 self.generate_arg_assignment(arg, item, code)
2561             if min_positional_args == 0:
2562                 code.put('case  0: ')
2563             code.putln('break;')
2564             if self.star_arg:
2565                 if min_positional_args:
2566                     for i in range(min_positional_args-1, -1, -1):
2567                         code.putln('case %2d:' % i)
2568                     code.put_goto(argtuple_error_label)
2569             else:
2570                 code.put('default: ')
2571                 code.put_goto(argtuple_error_label)
2572             code.putln('}')
2573
2574         code.putln('}')
2575
2576         if code.label_used(argtuple_error_label):
2577             code.put_goto(success_label)
2578             code.put_label(argtuple_error_label)
2579             code.put('__Pyx_RaiseArgtupleInvalid("%s", %d, %d, %d, PyTuple_GET_SIZE(%s)); ' % (
2580                     self.name, has_fixed_positional_count,
2581                     min_positional_args, max_positional_args,
2582                     Naming.args_cname))
2583             code.putln(code.error_goto(self.pos))
2584
2585     def generate_arg_default_assignments(self, code):
2586         for arg in self.args:
2587             if arg.is_generic and arg.default:
2588                 code.putln(
2589                     "%s = %s;" % (
2590                         arg.entry.cname,
2591                         arg.calculate_default_value_code(code)))
2592
2593     def generate_stararg_init_code(self, max_positional_args, code):
2594         if self.starstar_arg:
2595             self.starstar_arg.entry.xdecref_cleanup = 0
2596             code.putln('%s = PyDict_New(); if (unlikely(!%s)) return %s;' % (
2597                     self.starstar_arg.entry.cname,
2598                     self.starstar_arg.entry.cname,
2599                     self.error_value()))
2600             code.put_gotref(self.starstar_arg.entry.cname)
2601         if self.star_arg:
2602             self.star_arg.entry.xdecref_cleanup = 0
2603             code.putln('if (PyTuple_GET_SIZE(%s) > %d) {' % (
2604                     Naming.args_cname,
2605                     max_positional_args))
2606             code.put('%s = PyTuple_GetSlice(%s, %d, PyTuple_GET_SIZE(%s)); ' % (
2607                     self.star_arg.entry.cname, Naming.args_cname,
2608                     max_positional_args, Naming.args_cname))
2609             code.put_gotref(self.star_arg.entry.cname)
2610             if self.starstar_arg:
2611                 code.putln("")
2612                 code.putln("if (unlikely(!%s)) {" % self.star_arg.entry.cname)
2613                 code.put_decref(self.starstar_arg.entry.cname, py_object_type)
2614                 code.putln('return %s;' % self.error_value())
2615                 code.putln('}')
2616             else:
2617                 code.putln("if (unlikely(!%s)) return %s;" % (
2618                         self.star_arg.entry.cname, self.error_value()))
2619             code.putln('} else {')
2620             code.put("%s = %s; " % (self.star_arg.entry.cname, Naming.empty_tuple))
2621             code.put_incref(Naming.empty_tuple, py_object_type)
2622             code.putln('}')
2623
2624     def generate_keyword_unpacking_code(self, min_positional_args, max_positional_args,
2625                                         has_fixed_positional_count, positional_args,
2626                                         kw_only_args, argtuple_error_label, code):
2627         all_args = tuple(positional_args) + tuple(kw_only_args)
2628         max_args = len(all_args)
2629
2630         code.putln("Py_ssize_t kw_args = PyDict_Size(%s);" %
2631                    Naming.kwds_cname)
2632         # the 'values' array collects borrowed references to arguments
2633         # before doing any type coercion etc.
2634         code.putln("PyObject* values[%d] = {%s};" % (
2635             max_args, ','.join('0'*max_args)))
2636
2637         # assign borrowed Python default values to the values array,
2638         # so that they can be overwritten by received arguments below
2639         for i, arg in enumerate(all_args):
2640             if arg.default and arg.type.is_pyobject:
2641                 default_value = arg.calculate_default_value_code(code)
2642                 code.putln('values[%d] = %s;' % (i, arg.type.as_pyobject(default_value)))
2643
2644         # parse the args tuple and check that it's not too long
2645         code.putln('switch (PyTuple_GET_SIZE(%s)) {' % Naming.args_cname)
2646         if self.star_arg:
2647             code.putln('default:')
2648         for i in range(max_positional_args-1, -1, -1):
2649             code.put('case %2d: ' % (i+1))
2650             code.putln("values[%d] = PyTuple_GET_ITEM(%s, %d);" % (
2651                     i, Naming.args_cname, i))
2652         code.putln('case  0: break;')
2653         if not self.star_arg:
2654             code.put('default: ') # more arguments than allowed
2655             code.put_goto(argtuple_error_label)
2656         code.putln('}')
2657
2658         # now fill up the positional/required arguments with values
2659         # from the kw dict
2660         if self.num_required_args or max_positional_args > 0:
2661             last_required_arg = -1
2662             for i, arg in enumerate(all_args):
2663                 if not arg.default:
2664                     last_required_arg = i
2665             if last_required_arg < max_positional_args:
2666                 last_required_arg = max_positional_args-1
2667             num_required_args = self.num_required_args
2668             if max_positional_args > 0:
2669                 code.putln('switch (PyTuple_GET_SIZE(%s)) {' % Naming.args_cname)
2670             for i, arg in enumerate(all_args[:last_required_arg+1]):
2671                 if max_positional_args > 0 and i <= max_positional_args:
2672                     if self.star_arg and i == max_positional_args:
2673                         code.putln('default:')
2674                     else:
2675                         code.putln('case %2d:' % i)
2676                 pystring_cname = code.intern_identifier(arg.name)
2677                 if arg.default:
2678                     if arg.kw_only:
2679                         # handled separately below
2680                         continue
2681                     code.putln('if (kw_args > 0) {')
2682                     code.putln('PyObject* value = PyDict_GetItem(%s, %s);' % (
2683                         Naming.kwds_cname, pystring_cname))
2684                     code.putln('if (value) { values[%d] = value; kw_args--; }' % i)
2685                     code.putln('}')
2686                 else:
2687                     num_required_args -= 1
2688                     code.putln('values[%d] = PyDict_GetItem(%s, %s);' % (
2689                         i, Naming.kwds_cname, pystring_cname))
2690                     code.putln('if (likely(values[%d])) kw_args--;' % i);
2691                     if i < min_positional_args:
2692                         if i == 0:
2693                             # special case: we know arg 0 is missing
2694                             code.put('else ')
2695                             code.put_goto(argtuple_error_label)
2696                         else:
2697                             # print the correct number of values (args or
2698                             # kwargs) that were passed into positional
2699                             # arguments up to this point
2700                             code.putln('else {')
2701                             code.put('__Pyx_RaiseArgtupleInvalid("%s", %d, %d, %d, %d); ' % (
2702                                     self.name, has_fixed_positional_count,
2703                                     min_positional_args, max_positional_args, i))
2704                             code.putln(code.error_goto(self.pos))
2705                             code.putln('}')
2706                     elif arg.kw_only:
2707                         code.putln('else {')
2708                         code.put('__Pyx_RaiseKeywordRequired("%s", %s); ' %(
2709                                 self.name, pystring_cname))
2710                         code.putln(code.error_goto(self.pos))
2711                         code.putln('}')
2712             if max_positional_args > 0:
2713                 code.putln('}')
2714
2715         if kw_only_args and not self.starstar_arg:
2716             # unpack optional keyword-only arguments
2717             # checking for interned strings in a dict is faster than iterating
2718             # but it's too likely that we must iterate if we expect **kwargs
2719             optional_args = []
2720             for i, arg in enumerate(all_args[max_positional_args:]):
2721                 if not arg.kw_only or not arg.default:
2722                     continue
2723                 optional_args.append((i+max_positional_args, arg))
2724             if optional_args:
2725                 # this mimics an unrolled loop so that we can "break" out of it
2726                 code.putln('while (kw_args > 0) {')
2727                 code.putln('PyObject* value;')
2728                 for i, arg in optional_args:
2729                     pystring_cname = code.intern_identifier(arg.name)
2730                     code.putln(
2731                         'value = PyDict_GetItem(%s, %s);' % (
2732                         Naming.kwds_cname, pystring_cname))
2733                     code.putln(
2734                         'if (value) { values[%d] = value; if (!(--kw_args)) break; }' % i)
2735                 code.putln('break;')
2736                 code.putln('}')
2737
2738         code.putln('if (unlikely(kw_args > 0)) {')
2739         # non-positional/-required kw args left in dict: default args,
2740         # kw-only args, **kwargs or error
2741         #
2742         # This is sort of a catch-all: except for checking required
2743         # arguments, this will always do the right thing for unpacking
2744         # keyword arguments, so that we can concentrate on optimising
2745         # common cases above.
2746         if max_positional_args == 0:
2747             pos_arg_count = "0"
2748         elif self.star_arg:
2749             code.putln("const Py_ssize_t used_pos_args = (PyTuple_GET_SIZE(%s) < %d) ? PyTuple_GET_SIZE(%s) : %d;" % (
2750                     Naming.args_cname, max_positional_args,
2751                     Naming.args_cname, max_positional_args))
2752             pos_arg_count = "used_pos_args"
2753         else:
2754             pos_arg_count = "PyTuple_GET_SIZE(%s)" % Naming.args_cname
2755         code.globalstate.use_utility_code(parse_keywords_utility_code)
2756         code.put(
2757             'if (unlikely(__Pyx_ParseOptionalKeywords(%s, %s, %s, values, %s, "%s") < 0)) ' % (
2758                 Naming.kwds_cname,
2759                 Naming.pykwdlist_cname,
2760                 self.starstar_arg and self.starstar_arg.entry.cname or '0',
2761                 pos_arg_count,
2762                 self.name))
2763         code.putln(code.error_goto(self.pos))
2764         code.putln('}')
2765
2766         # convert arg values to their final type and assign them
2767         for i, arg in enumerate(all_args):
2768             if arg.default and not arg.type.is_pyobject:
2769                 code.putln("if (values[%d]) {" % i)
2770             self.generate_arg_assignment(arg, "values[%d]" % i, code)
2771             if arg.default and not arg.type.is_pyobject:
2772                 code.putln('} else {')
2773                 code.putln(
2774                     "%s = %s;" % (
2775                         arg.entry.cname,
2776                         arg.calculate_default_value_code(code)))
2777                 code.putln('}')
2778
2779     def generate_argument_conversion_code(self, code):
2780         # Generate code to convert arguments from signature type to
2781         # declared type, if needed.  Also copies signature arguments
2782         # into closure fields.
2783         for arg in self.args:
2784             if arg.needs_conversion:
2785                 self.generate_arg_conversion(arg, code)
2786             elif arg.entry.in_closure:
2787                 code.putln('%s = %s;' % (arg.entry.cname, arg.hdr_cname))
2788                 if arg.type.is_pyobject:
2789                     code.put_var_incref(arg.entry)
2790
2791     def generate_arg_conversion(self, arg, code):
2792         # Generate conversion code for one argument.
2793         old_type = arg.hdr_type
2794         new_type = arg.type
2795         if old_type.is_pyobject:
2796             if arg.default:
2797                 code.putln("if (%s) {" % arg.hdr_cname)
2798             else:
2799                 code.putln("assert(%s); {" % arg.hdr_cname)
2800             self.generate_arg_conversion_from_pyobject(arg, code)
2801             code.putln("}")
2802         elif new_type.is_pyobject:
2803             self.generate_arg_conversion_to_pyobject(arg, code)
2804         else:
2805             if new_type.assignable_from(old_type):
2806                 code.putln(
2807                     "%s = %s;" % (arg.entry.cname, arg.hdr_cname))
2808             else:
2809                 error(arg.pos,
2810                     "Cannot convert 1 argument from '%s' to '%s'" %
2811                         (old_type, new_type))
2812     
2813     def generate_arg_conversion_from_pyobject(self, arg, code):
2814         new_type = arg.type
2815         func = new_type.from_py_function
2816         # copied from CoerceFromPyTypeNode
2817         if func:
2818             lhs = arg.entry.cname
2819             rhs = "%s(%s)" % (func, arg.hdr_cname)
2820             if new_type.is_enum:
2821                 rhs = PyrexTypes.typecast(new_type, PyrexTypes.c_long_type, rhs)
2822             code.putln("%s = %s; %s" % (
2823                 lhs, 
2824                 rhs,
2825                 code.error_goto_if(new_type.error_condition(arg.entry.cname), arg.pos)))
2826         else:
2827             error(arg.pos, 
2828                 "Cannot convert Python object argument to type '%s'" 
2829                     % new_type)
2830     
2831     def generate_arg_conversion_to_pyobject(self, arg, code):
2832         old_type = arg.hdr_type
2833         func = old_type.to_py_function
2834         if func:
2835             code.putln("%s = %s(%s); %s" % (
2836                 arg.entry.cname,
2837                 func,
2838                 arg.hdr_cname,
2839                 code.error_goto_if_null(arg.entry.cname, arg.pos)))
2840             code.put_var_gotref(arg.entry)
2841         else:
2842             error(arg.pos,
2843                 "Cannot convert argument of type '%s' to Python object"
2844                     % old_type)
2845
2846     def generate_argument_type_tests(self, code):
2847         # Generate type tests for args whose signature
2848         # type is PyObject * and whose declared type is
2849         # a subtype thereof.
2850         for arg in self.args:
2851             if arg.needs_type_test:
2852                 self.generate_arg_type_test(arg, code)
2853             elif not arg.accept_none and arg.type.is_pyobject:
2854                 self.generate_arg_none_check(arg, code)
2855
2856     def error_value(self):
2857         return self.entry.signature.error_value
2858     
2859     def caller_will_check_exceptions(self):
2860         return 1
2861             
2862 class OverrideCheckNode(StatNode):
2863     # A Node for dispatching to the def method if it
2864     # is overriden. 
2865     #
2866     #  py_func
2867     #
2868     #  args
2869     #  func_temp
2870     #  body
2871     
2872     child_attrs = ['body']
2873     
2874     body = None
2875
2876     def analyse_expressions(self, env):
2877         self.args = env.arg_entries
2878         if self.py_func.is_module_scope:
2879             first_arg = 0
2880         else:
2881             first_arg = 1
2882         import ExprNodes
2883         self.func_node = ExprNodes.RawCNameExprNode(self.pos, py_object_type)
2884         call_tuple = ExprNodes.TupleNode(self.pos, args=[ExprNodes.NameNode(self.pos, name=arg.name) for arg in self.args[first_arg:]])
2885         call_node = ExprNodes.SimpleCallNode(self.pos,
2886                                              function=self.func_node, 
2887                                              args=[ExprNodes.NameNode(self.pos, name=arg.name) for arg in self.args[first_arg:]])
2888         self.body = ReturnStatNode(self.pos, value=call_node)
2889         self.body.analyse_expressions(env)
2890         
2891     def generate_execution_code(self, code):
2892         interned_attr_cname = code.intern_identifier(self.py_func.entry.name)
2893         # Check to see if we are an extension type
2894         if self.py_func.is_module_scope:
2895             self_arg = "((PyObject *)%s)" % Naming.module_cname
2896         else:
2897             self_arg = "((PyObject *)%s)" % self.args[0].cname
2898         code.putln("/* Check if called by wrapper */")
2899         code.putln("if (unlikely(%s)) ;" % Naming.skip_dispatch_cname)
2900         code.putln("/* Check if overriden in Python */")
2901         if self.py_func.is_module_scope:
2902             code.putln("else {")
2903         else:
2904             code.putln("else if (unlikely(Py_TYPE(%s)->tp_dictoffset != 0)) {" % self_arg)
2905         func_node_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
2906         self.func_node.set_cname(func_node_temp)
2907         # need to get attribute manually--scope would return cdef method
2908         err = code.error_goto_if_null(func_node_temp, self.pos)
2909         code.putln("%s = PyObject_GetAttr(%s, %s); %s" % (
2910             func_node_temp, self_arg, interned_attr_cname, err))
2911         code.put_gotref(func_node_temp)
2912         is_builtin_function_or_method = "PyCFunction_Check(%s)" % func_node_temp
2913         is_overridden = "(PyCFunction_GET_FUNCTION(%s) != (void *)&%s)" % (
2914             func_node_temp, self.py_func.entry.func_cname)
2915         code.putln("if (!%s || %s) {" % (is_builtin_function_or_method, is_overridden))
2916         self.body.generate_execution_code(code)
2917         code.putln("}")
2918         code.put_decref_clear(func_node_temp, PyrexTypes.py_object_type)
2919         code.funcstate.release_temp(func_node_temp)
2920         code.putln("}")
2921
2922 class ClassDefNode(StatNode, BlockNode):
2923     pass
2924
2925 class PyClassDefNode(ClassDefNode):
2926     #  A Python class definition.
2927     #
2928     #  name     EncodedString   Name of the class
2929     #  doc      string or None
2930     #  body     StatNode        Attribute definition code
2931     #  entry    Symtab.Entry
2932     #  scope    PyClassScope
2933     #  decorators    [DecoratorNode]        list of decorators or None
2934     #
2935     #  The following subnodes are constructed internally:
2936     #
2937     #  dict     DictNode   Class dictionary
2938     #  classobj ClassNode  Class object
2939     #  target   NameNode   Variable to assign class object to
2940
2941     child_attrs = ["body", "dict", "classobj", "target"]
2942     decorators = None
2943     
2944     def __init__(self, pos, name, bases, doc, body, decorators = None,
2945                  keyword_args = None, starstar_arg = None):
2946         StatNode.__init__(self, pos)
2947         self.name = name
2948         self.doc = doc
2949         self.body = body
2950         self.decorators = decorators
2951         import ExprNodes
2952         self.dict = ExprNodes.DictNode(pos, key_value_pairs = [])
2953         if self.doc and Options.docstrings:
2954             doc = embed_position(self.pos, self.doc)
2955             # FIXME: correct string node?
2956             doc_node = ExprNodes.StringNode(pos, value = doc)
2957         else:
2958             doc_node = None
2959         self.classobj = ExprNodes.ClassNode(pos, name = name,
2960             bases = bases, dict = self.dict, doc = doc_node,
2961             keyword_args = keyword_args, starstar_arg = starstar_arg)
2962         self.target = ExprNodes.NameNode(pos, name = name)
2963         
2964     def as_cclass(self):
2965         """
2966         Return this node as if it were declared as an extension class
2967         """
2968         bases = self.classobj.bases.args
2969         if len(bases) == 0:
2970             base_class_name = None
2971             base_class_module = None
2972         elif len(bases) == 1:
2973             base = bases[0]
2974             path = []
2975             from ExprNodes import AttributeNode, NameNode
2976             while isinstance(base, AttributeNode):
2977                 path.insert(0, base.attribute)
2978                 base = base.obj
2979             if isinstance(base, NameNode):
2980                 path.insert(0, base.name)
2981                 base_class_name = path[-1]
2982                 if len(path) > 1:
2983                     base_class_module = u'.'.join(path[:-1])
2984                 else:
2985                     base_class_module = None
2986             else:
2987                 error(self.classobj.bases.args.pos, "Invalid base class")
2988         else:
2989             error(self.classobj.bases.args.pos, "C class may only have one base class")
2990             return None
2991         
2992         return CClassDefNode(self.pos, 
2993                              visibility = 'private',
2994                              module_name = None,
2995                              class_name = self.name,
2996                              base_class_module = base_class_module,
2997                              base_class_name = base_class_name,
2998                              decorators = self.decorators,
2999                              body = self.body,
3000                              in_pxd = False,
3001                              doc = self.doc)
3002         
3003     def create_scope(self, env):
3004         genv = env
3005         while env.is_py_class_scope or env.is_c_class_scope:
3006             env = env.outer_scope
3007         cenv = self.scope = PyClassScope(name = self.name, outer_scope = genv)
3008         return cenv
3009     
3010     def analyse_declarations(self, env):
3011         self.target.analyse_target_declaration(env)
3012         cenv = self.create_scope(env)
3013         cenv.directives = env.directives
3014         cenv.class_obj_cname = self.target.entry.cname
3015         self.body.analyse_declarations(cenv)
3016     
3017     def analyse_expressions(self, env):
3018         self.dict.analyse_expressions(env)
3019         self.classobj.analyse_expressions(env)
3020         genv = env.global_scope()
3021         cenv = self.scope
3022         self.body.analyse_expressions(cenv)
3023         self.target.analyse_target_expression(env, self.classobj)
3024     
3025     def generate_function_definitions(self, env, code):
3026         self.body.generate_function_definitions(self.scope, code)
3027     
3028     def generate_execution_code(self, code):
3029         code.pyclass_stack.append(self)
3030         cenv = self.scope
3031         self.dict.generate_evaluation_code(code)
3032         cenv.namespace_cname = cenv.class_obj_cname = self.dict.result()
3033         self.body.generate_execution_code(code)
3034         self.classobj.generate_evaluation_code(code)
3035         cenv.namespace_cname = cenv.class_obj_cname = self.classobj.result()
3036         self.target.generate_assignment_code(self.classobj, code)
3037         self.dict.generate_disposal_code(code)
3038         self.dict.free_temps(code)
3039         code.pyclass_stack.pop()
3040
3041
3042 class CClassDefNode(ClassDefNode):
3043     #  An extension type definition.
3044     #
3045     #  visibility         'private' or 'public' or 'extern'
3046     #  typedef_flag       boolean
3047     #  api                boolean
3048     #  module_name        string or None    For import of extern type objects
3049     #  class_name         string            Unqualified name of class
3050     #  as_name            string or None    Name to declare as in this scope
3051     #  base_class_module  string or None    Module containing the base class
3052     #  base_class_name    string or None    Name of the base class
3053     #  objstruct_name     string or None    Specified C name of object struct
3054     #  typeobj_name       string or None    Specified C name of type object
3055     #  in_pxd             boolean           Is in a .pxd file
3056     #  decorators         [DecoratorNode]   list of decorators or None
3057     #  doc                string or None
3058     #  body               StatNode or None
3059     #  entry              Symtab.Entry
3060     #  base_type          PyExtensionType or None
3061     #  buffer_defaults_node DictNode or None Declares defaults for a buffer
3062     #  buffer_defaults_pos
3063
3064     child_attrs = ["body"]
3065     buffer_defaults_node = None
3066     buffer_defaults_pos = None
3067     typedef_flag = False
3068     api = False
3069     objstruct_name = None
3070     typeobj_name = None
3071     decorators = None
3072
3073     def analyse_declarations(self, env):
3074         #print "CClassDefNode.analyse_declarations:", self.class_name
3075         #print "...visibility =", self.visibility
3076         #print "...module_name =", self.module_name
3077
3078         import Buffer
3079         if self.buffer_defaults_node:
3080             buffer_defaults = Buffer.analyse_buffer_options(self.buffer_defaults_pos,
3081                                                             env, [], self.buffer_defaults_node,
3082                                                             need_complete=False)
3083         else:
3084             buffer_defaults = None
3085
3086         if env.in_cinclude and not self.objstruct_name:
3087             error(self.pos, "Object struct name specification required for "
3088                 "C class defined in 'extern from' block")
3089         self.base_type = None
3090         # Now that module imports are cached, we need to 
3091         # import the modules for extern classes. 
3092         if self.module_name:
3093             self.module = None
3094             for module in env.cimported_modules:
3095                 if module.name == self.module_name:
3096                     self.module = module
3097             if self.module is None:
3098                 self.module = ModuleScope(self.module_name, None, env.context)
3099                 self.module.has_extern_class = 1
3100                 env.add_imported_module(self.module)
3101
3102         if self.base_class_name:
3103             if self.base_class_module:
3104                 base_class_scope = env.find_module(self.base_class_module, self.pos)
3105             else:
3106                 base_class_scope = env
3107             if self.base_class_name == 'object':
3108                 # extension classes are special and don't need to inherit from object
3109                 if base_class_scope is None or base_class_scope.lookup('object') is None:
3110                     self.base_class_name = None
3111                     self.base_class_module = None
3112                     base_class_scope = None
3113             if base_class_scope:
3114                 base_class_entry = base_class_scope.find(self.base_class_name, self.pos)
3115                 if base_class_entry:
3116                     if not base_class_entry.is_type:
3117                         error(self.pos, "'%s' is not a type name" % self.base_class_name)
3118                     elif not base_class_entry.type.is_extension_type:
3119                         error(self.pos, "'%s' is not an extension type" % self.base_class_name)
3120                     elif not base_class_entry.type.is_complete():
3121                         error(self.pos, "Base class '%s' of type '%s' is incomplete" % (
3122                             self.base_class_name, self.class_name))
3123                     elif base_class_entry.type.scope and base_class_entry.type.scope.directives and \
3124                              base_class_entry.type.scope.directives['final']:
3125                         error(self.pos, "Base class '%s' of type '%s' is final" % (
3126                             self.base_class_name, self.class_name))
3127                     else:
3128                         self.base_type = base_class_entry.type
3129         has_body = self.body is not None
3130         if self.module_name and self.visibility != 'extern':
3131             module_path = self.module_name.split(".")
3132             home_scope = env.find_imported_module(module_path, self.pos)
3133             if not home_scope:
3134                 return
3135         else:
3136             home_scope = env
3137
3138         if self.visibility == 'extern':
3139             if self.module_name == '__builtin__' and self.class_name in Builtin.builtin_types:
3140                 warning(self.pos, "%s already a builtin Cython type" % self.class_name, 1)
3141
3142         self.entry = home_scope.declare_c_class(
3143             name = self.class_name, 
3144             pos = self.pos,
3145             defining = has_body and self.in_pxd,
3146             implementing = has_body and not self.in_pxd,
3147             module_name = self.module_name,
3148             base_type = self.base_type,
3149             objstruct_cname = self.objstruct_name,
3150             typeobj_cname = self.typeobj_name,
3151             visibility = self.visibility,
3152             typedef_flag = self.typedef_flag,
3153             api = self.api,
3154             buffer_defaults = buffer_defaults)
3155         if home_scope is not env and self.visibility == 'extern':
3156             env.add_imported_entry(self.class_name, self.entry, pos)
3157         self.scope = scope = self.entry.type.scope
3158         if scope is not None:
3159             scope.directives = env.directives
3160
3161         if self.doc and Options.docstrings:
3162             scope.doc = embed_position(self.pos, self.doc)
3163             
3164         if has_body:
3165             self.body.analyse_declarations(scope)
3166             if self.in_pxd:
3167                 scope.defined = 1
3168             else:
3169                 scope.implemented = 1
3170         env.allocate_vtable_names(self.entry)
3171         
3172     def analyse_expressions(self, env):
3173         if self.body:
3174             scope = self.entry.type.scope
3175             self.body.analyse_expressions(scope)
3176     
3177     def generate_function_definitions(self, env, code):
3178         if self.body:
3179             self.body.generate_function_definitions(
3180                 self.entry.type.scope, code)
3181     
3182     def generate_execution_code(self, code):
3183         # This is needed to generate evaluation code for
3184         # default values of method arguments.
3185         if self.body:
3186             self.body.generate_execution_code(code)
3187             
3188     def annotate(self, code):
3189         if self.body:
3190             self.body.annotate(code)
3191
3192
3193 class PropertyNode(StatNode):
3194     #  Definition of a property in an extension type.
3195     #
3196     #  name   string
3197     #  doc    EncodedString or None    Doc string
3198     #  body   StatListNode
3199     
3200     child_attrs = ["body"]
3201
3202     def analyse_declarations(self, env):
3203         entry = env.declare_property(self.name, self.doc, self.pos)
3204         if entry:
3205             entry.scope.directives = env.directives
3206             self.body.analyse_declarations(entry.scope)
3207
3208     def analyse_expressions(self, env):
3209         self.body.analyse_expressions(env)
3210     
3211     def generate_function_definitions(self, env, code):
3212         self.body.generate_function_definitions(env, code)
3213
3214     def generate_execution_code(self, code):
3215         pass
3216
3217     def annotate(self, code):
3218         self.body.annotate(code)
3219
3220
3221 class GlobalNode(StatNode):
3222     # Global variable declaration.
3223     #
3224     # names    [string]
3225     
3226     child_attrs = []
3227
3228     def analyse_declarations(self, env):
3229         for name in self.names:
3230             env.declare_global(name, self.pos)
3231
3232     def analyse_expressions(self, env):
3233         pass
3234     
3235     def generate_execution_code(self, code):
3236         pass
3237
3238
3239 class ExprStatNode(StatNode):
3240     #  Expression used as a statement.
3241     #
3242     #  expr   ExprNode
3243
3244     child_attrs = ["expr"]
3245     
3246     def analyse_declarations(self, env):
3247         import ExprNodes
3248         if isinstance(self.expr, ExprNodes.GeneralCallNode):
3249             func = self.expr.function.as_cython_attribute()
3250             if func == u'declare':
3251                 args, kwds = self.expr.explicit_args_kwds()
3252                 if len(args):
3253                     error(self.expr.pos, "Variable names must be specified.")
3254                 for var, type_node in kwds.key_value_pairs:
3255                     type = type_node.analyse_as_type(env)
3256                     if type is None:
3257                         error(type_node.pos, "Unknown type")
3258                     else:
3259                         env.declare_var(var.value, type, var.pos, is_cdef = True)
3260                 self.__class__ = PassStatNode
3261     
3262     def analyse_expressions(self, env):
3263         self.expr.analyse_expressions(env)
3264     
3265     def generate_execution_code(self, code):
3266         self.expr.generate_evaluation_code(code)
3267         if not self.expr.is_temp and self.expr.result():
3268             code.putln("%s;" % self.expr.result())
3269         self.expr.generate_disposal_code(code)
3270         self.expr.free_temps(code)
3271
3272     def generate_function_definitions(self, env, code):
3273         self.expr.generate_function_definitions(env, code)
3274
3275     def annotate(self, code):
3276         self.expr.annotate(code)
3277
3278
3279 class AssignmentNode(StatNode):
3280     #  Abstract base class for assignment nodes.
3281     #
3282     #  The analyse_expressions and generate_execution_code
3283     #  phases of assignments are split into two sub-phases
3284     #  each, to enable all the right hand sides of a
3285     #  parallel assignment to be evaluated before assigning
3286     #  to any of the left hand sides.
3287
3288     def analyse_expressions(self, env):
3289         self.analyse_types(env)
3290
3291 #       def analyse_expressions(self, env):
3292 #           self.analyse_expressions_1(env)
3293 #           self.analyse_expressions_2(env)
3294
3295     def generate_execution_code(self, code):
3296         self.generate_rhs_evaluation_code(code)
3297         self.generate_assignment_code(code)
3298         
3299
3300 class SingleAssignmentNode(AssignmentNode):
3301     #  The simplest case:
3302     #
3303     #    a = b
3304     #
3305     #  lhs      ExprNode      Left hand side
3306     #  rhs      ExprNode      Right hand side
3307     #  first    bool          Is this guaranteed the first assignment to lhs?
3308     
3309     child_attrs = ["lhs", "rhs"]
3310     first = False
3311     declaration_only = False
3312
3313     def analyse_declarations(self, env):
3314         import ExprNodes
3315         
3316         # handle declarations of the form x = cython.foo()
3317         if isinstance(self.rhs, ExprNodes.CallNode):
3318             func_name = self.rhs.function.as_cython_attribute()
3319             if func_name:
3320                 args, kwds = self.rhs.explicit_args_kwds()
3321                 
3322                 if func_name in ['declare', 'typedef']:
3323                     if len(args) > 2 or kwds is not None:
3324                         error(rhs.pos, "Can only declare one type at a time.")
3325                         return
3326                     type = args[0].analyse_as_type(env)
3327                     if type is None:
3328                         error(args[0].pos, "Unknown type")
3329                         return
3330                     lhs = self.lhs
3331                     if func_name == 'declare':
3332                         if isinstance(lhs, ExprNodes.NameNode):
3333                             vars = [(lhs.name, lhs.pos)]
3334                         elif isinstance(lhs, ExprNodes.TupleNode):
3335                             vars = [(var.name, var.pos) for var in lhs.args]
3336                         else:
3337                             error(lhs.pos, "Invalid declaration")
3338                             return
3339                         for var, pos in vars:
3340                             env.declare_var(var, type, pos, is_cdef = True)
3341                         if len(args) == 2:
3342                             # we have a value
3343                             self.rhs = args[1]
3344                         else:
3345                             self.declaration_only = True
3346                     else:
3347                         self.declaration_only = True
3348                         if not isinstance(lhs, ExprNodes.NameNode):
3349                             error(lhs.pos, "Invalid declaration.")
3350                         env.declare_typedef(lhs.name, type, self.pos, visibility='private')
3351                     
3352                 elif func_name in ['struct', 'union']:
3353                     self.declaration_only = True
3354                     if len(args) > 0 or kwds is None:
3355                         error(rhs.pos, "Struct or union members must be given by name.")
3356                         return
3357                     members = []
3358                     for member, type_node in kwds.key_value_pairs:
3359                         type = type_node.analyse_as_type(env)
3360                         if type is None:
3361                             error(type_node.pos, "Unknown type")
3362                         else:
3363                             members.append((member.value, type, member.pos))
3364                     if len(members) < len(kwds.key_value_pairs):
3365                         return
3366                     if not isinstance(self.lhs, ExprNodes.NameNode):
3367                         error(self.lhs.pos, "Invalid declaration.")
3368                     name = self.lhs.name
3369                     scope = StructOrUnionScope(name)
3370                     env.declare_struct_or_union(name, func_name, scope, False, self.rhs.pos)
3371                     for member, type, pos in members:
3372                         scope.declare_var(member, type, pos)
3373                     
3374         if self.declaration_only:
3375             return
3376         else:
3377             self.lhs.analyse_target_declaration(env)
3378     
3379     def analyse_types(self, env, use_temp = 0):
3380         self.rhs.analyse_types(env)
3381         self.lhs.analyse_target_types(env)
3382         self.lhs.gil_assignment_check(env)
3383         self.rhs = self.rhs.coerce_to(self.lhs.type, env)
3384         if use_temp:
3385             self.rhs = self.rhs.coerce_to_temp(env)
3386     
3387     def generate_rhs_evaluation_code(self, code):
3388         self.rhs.generate_evaluation_code(code)
3389     
3390     def generate_assignment_code(self, code):
3391         self.lhs.generate_assignment_code(self.rhs, code)
3392
3393     def generate_function_definitions(self, env, code):
3394         self.rhs.generate_function_definitions(env, code)
3395
3396     def annotate(self, code):
3397         self.lhs.annotate(code)
3398         self.rhs.annotate(code)
3399
3400
3401 class CascadedAssignmentNode(AssignmentNode):
3402     #  An assignment with multiple left hand sides:
3403     #
3404     #    a = b = c
3405     #
3406     #  lhs_list   [ExprNode]   Left hand sides
3407     #  rhs        ExprNode     Right hand sides
3408     #
3409     #  Used internally:
3410     #
3411     #  coerced_rhs_list   [ExprNode]   RHS coerced to type of each LHS
3412     
3413     child_attrs = ["lhs_list", "rhs", "coerced_rhs_list"]
3414     coerced_rhs_list = None
3415
3416     def analyse_declarations(self, env):
3417         for lhs in self.lhs_list:
3418             lhs.analyse_target_declaration(env)
3419     
3420     def analyse_types(self, env, use_temp = 0):
3421         self.rhs.analyse_types(env)
3422         if not self.rhs.is_simple():
3423             if use_temp:
3424                 self.rhs = self.rhs.coerce_to_temp(env)
3425             else:
3426                 self.rhs = self.rhs.coerce_to_simple(env)
3427         from ExprNodes import CloneNode
3428         self.coerced_rhs_list = []
3429         for lhs in self.lhs_list:
3430             lhs.analyse_target_types(env)
3431             lhs.gil_assignment_check(env)
3432             rhs = CloneNode(self.rhs)
3433             rhs = rhs.coerce_to(lhs.type, env)
3434             self.coerced_rhs_list.append(rhs)
3435
3436     def generate_rhs_evaluation_code(self, code):
3437         self.rhs.generate_evaluation_code(code)
3438     
3439     def generate_assignment_code(self, code):
3440         for i in range(len(self.lhs_list)):
3441             lhs = self.lhs_list[i]
3442             rhs = self.coerced_rhs_list[i]
3443             rhs.generate_evaluation_code(code)
3444             lhs.generate_assignment_code(rhs, code)
3445             # Assignment has disposed of the cloned RHS
3446         self.rhs.generate_disposal_code(code)
3447         self.rhs.free_temps(code)
3448
3449     def generate_function_definitions(self, env, code):
3450         self.rhs.generate_function_definitions(env, code)
3451
3452     def annotate(self, code):
3453         for i in range(len(self.lhs_list)):
3454             lhs = self.lhs_list[i].annotate(code)
3455             rhs = self.coerced_rhs_list[i].annotate(code)
3456         self.rhs.annotate(code)
3457         
3458
3459 class ParallelAssignmentNode(AssignmentNode):
3460     #  A combined packing/unpacking assignment:
3461     #
3462     #    a, b, c =  d, e, f
3463     #
3464     #  This has been rearranged by the parser into
3465     #
3466     #    a = d ; b = e ; c = f
3467     #
3468     #  but we must evaluate all the right hand sides
3469     #  before assigning to any of the left hand sides.
3470     #
3471     #  stats     [AssignmentNode]   The constituent assignments
3472     
3473     child_attrs = ["stats"]
3474
3475     def analyse_declarations(self, env):
3476         for stat in self.stats:
3477             stat.analyse_declarations(env)
3478     
3479     def analyse_expressions(self, env):
3480         for stat in self.stats:
3481             stat.analyse_types(env, use_temp = 1)
3482
3483 #    def analyse_expressions(self, env):
3484 #        for stat in self.stats:
3485 #            stat.analyse_expressions_1(env, use_temp = 1)
3486 #        for stat in self.stats:
3487 #            stat.analyse_expressions_2(env)
3488     
3489     def generate_execution_code(self, code):
3490         for stat in self.stats:
3491             stat.generate_rhs_evaluation_code(code)
3492         for stat in self.stats:
3493             stat.generate_assignment_code(code)
3494
3495     def generate_function_definitions(self, env, code):
3496         for stat in self.stats:
3497             stat.generate_function_definitions(env, code)
3498
3499     def annotate(self, code):
3500         for stat in self.stats:
3501             stat.annotate(code)
3502
3503
3504 class InPlaceAssignmentNode(AssignmentNode):
3505     #  An in place arithmetic operand:
3506     #
3507     #    a += b
3508     #    a -= b
3509     #    ...
3510     #
3511     #  lhs      ExprNode      Left hand side
3512     #  rhs      ExprNode      Right hand side
3513     #  op       char          one of "+-*/%^&|"
3514     #  dup     (ExprNode)     copy of lhs used for operation (auto-generated)
3515     #
3516     #  This code is a bit tricky because in order to obey Python 
3517     #  semantics the sub-expressions (e.g. indices) of the lhs must 
3518     #  not be evaluated twice. So we must re-use the values calculated 
3519     #  in evaluation phase for the assignment phase as well. 
3520     #  Fortunately, the type of the lhs node is fairly constrained 
3521     #  (it must be a NameNode, AttributeNode, or IndexNode).     
3522     
3523     child_attrs = ["lhs", "rhs"]
3524
3525     def analyse_declarations(self, env):
3526         self.lhs.analyse_target_declaration(env)
3527         
3528     def analyse_types(self, env):
3529         self.rhs.analyse_types(env)
3530         self.lhs.analyse_target_types(env)
3531
3532     def generate_execution_code(self, code):
3533         import ExprNodes
3534         self.rhs.generate_evaluation_code(code)
3535         self.lhs.generate_subexpr_evaluation_code(code)
3536         c_op = self.operator
3537         if c_op == "//":
3538             c_op = "/"
3539         elif c_op == "**":
3540             error(self.pos, "No C inplace power operator")
3541         if isinstance(self.lhs, ExprNodes.IndexNode) and self.lhs.is_buffer_access:
3542             if self.lhs.type.is_pyobject:
3543                 error(self.pos, "In-place operators not allowed on object buffers in this release.")
3544             if c_op in ('/', '%') and self.lhs.type.is_int and not code.directives['cdivision']:
3545                 error(self.pos, "In-place non-c divide operators not allowed on int buffers.")
3546             self.lhs.generate_buffer_setitem_code(self.rhs, code, c_op)
3547         else:
3548             # C++
3549             # TODO: make sure overload is declared
3550             code.putln("%s %s= %s;" % (self.lhs.result(), c_op, self.rhs.result()))
3551         self.lhs.generate_subexpr_disposal_code(code)
3552         self.lhs.free_subexpr_temps(code)
3553         self.rhs.generate_disposal_code(code)
3554         self.rhs.free_temps(code)
3555
3556     def annotate(self, code):
3557         self.lhs.annotate(code)
3558         self.rhs.annotate(code)
3559     
3560     def create_binop_node(self):
3561         import ExprNodes
3562         return ExprNodes.binop_node(self.pos, self.operator, self.lhs, self.rhs)
3563
3564
3565 class PrintStatNode(StatNode):
3566     #  print statement
3567     #
3568     #  arg_tuple         TupleNode
3569     #  stream            ExprNode or None (stdout)
3570     #  append_newline    boolean
3571
3572     child_attrs = ["arg_tuple", "stream"]
3573
3574     def analyse_expressions(self, env):
3575         if self.stream:
3576             self.stream.analyse_expressions(env)
3577             self.stream = self.stream.coerce_to_pyobject(env)
3578         self.arg_tuple.analyse_expressions(env)
3579         self.arg_tuple = self.arg_tuple.coerce_to_pyobject(env)
3580         env.use_utility_code(printing_utility_code)
3581         if len(self.arg_tuple.args) == 1 and self.append_newline:
3582             env.use_utility_code(printing_one_utility_code)
3583
3584     nogil_check = Node.gil_error
3585     gil_message = "Python print statement"
3586
3587     def generate_execution_code(self, code):
3588         if self.stream:
3589             self.stream.generate_evaluation_code(code)
3590             stream_result = self.stream.py_result()
3591         else:
3592             stream_result = '0'
3593         if len(self.arg_tuple.args) == 1 and self.append_newline:
3594             arg = self.arg_tuple.args[0]
3595             arg.generate_evaluation_code(code)
3596             
3597             code.putln(
3598                 "if (__Pyx_PrintOne(%s, %s) < 0) %s" % (
3599                     stream_result,
3600                     arg.py_result(),
3601                     code.error_goto(self.pos)))
3602             arg.generate_disposal_code(code)
3603             arg.free_temps(code)
3604         else:
3605             self.arg_tuple.generate_evaluation_code(code)
3606             code.putln(
3607                 "if (__Pyx_Print(%s, %s, %d) < 0) %s" % (
3608                     stream_result,
3609                     self.arg_tuple.py_result(),
3610                     self.append_newline,
3611                     code.error_goto(self.pos)))
3612             self.arg_tuple.generate_disposal_code(code)
3613             self.arg_tuple.free_temps(code)
3614
3615         if self.stream:
3616             self.stream.generate_disposal_code(code)
3617             self.stream.free_temps(code)
3618
3619     def generate_function_definitions(self, env, code):
3620         if self.stream:
3621             self.stream.generate_function_definitions(env, code)
3622         self.arg_tuple.generate_function_definitions(env, code)
3623
3624     def annotate(self, code):
3625         if self.stream:
3626             self.stream.annotate(code)
3627         self.arg_tuple.annotate(code)
3628
3629
3630 class ExecStatNode(StatNode):
3631     #  exec statement
3632     #
3633     #  args     [ExprNode]
3634
3635     child_attrs = ["args"]
3636
3637     def analyse_expressions(self, env):
3638         for i, arg in enumerate(self.args):
3639             arg.analyse_expressions(env)
3640             arg = arg.coerce_to_pyobject(env)
3641             self.args[i] = arg
3642         env.use_utility_code(Builtin.pyexec_utility_code)
3643
3644     nogil_check = Node.gil_error
3645     gil_message = "Python exec statement"
3646
3647     def generate_execution_code(self, code):
3648         args = []
3649         for arg in self.args:
3650             arg.generate_evaluation_code(code)
3651             args.append( arg.py_result() )
3652         args = tuple(args + ['0', '0'][:3-len(args)])
3653         temp_result = code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=True)
3654         code.putln("%s = __Pyx_PyRun(%s, %s, %s);" % (
3655                 (temp_result,) + args))
3656         for arg in self.args:
3657             arg.generate_disposal_code(code)
3658             arg.free_temps(code)
3659         code.putln(
3660             code.error_goto_if_null(temp_result, self.pos))
3661         code.put_gotref(temp_result)
3662         code.put_decref_clear(temp_result, py_object_type)
3663         code.funcstate.release_temp(temp_result)
3664
3665     def annotate(self, code):
3666         for arg in self.args:
3667             arg.annotate(code)
3668
3669
3670 class DelStatNode(StatNode):
3671     #  del statement
3672     #
3673     #  args     [ExprNode]
3674     
3675     child_attrs = ["args"]
3676
3677     def analyse_declarations(self, env):
3678         for arg in self.args:
3679             arg.analyse_target_declaration(env)
3680     
3681     def analyse_expressions(self, env):
3682         for arg in self.args:
3683             arg.analyse_target_expression(env, None)
3684             if arg.type.is_pyobject:
3685                 pass
3686             elif arg.type.is_ptr and arg.type.base_type.is_cpp_class:
3687                 self.cpp_check(env)
3688             elif arg.type.is_cpp_class:
3689                 error(arg.pos, "Deletion of non-heap C++ object")
3690             else:
3691                 error(arg.pos, "Deletion of non-Python, non-C++ object")
3692             #arg.release_target_temp(env)
3693
3694     def nogil_check(self, env):
3695         for arg in self.args:
3696             if arg.type.is_pyobject:
3697                 self.gil_error()
3698
3699     gil_message = "Deleting Python object"
3700
3701     def generate_execution_code(self, code):
3702         for arg in self.args:
3703             if arg.type.is_pyobject:
3704                 arg.generate_deletion_code(code)
3705             elif arg.type.is_ptr and arg.type.base_type.is_cpp_class:
3706                 arg.generate_result_code(code)
3707                 code.putln("delete %s;" % arg.result())
3708             # else error reported earlier
3709
3710     def annotate(self, code):
3711         for arg in self.args:
3712             arg.annotate(code)
3713
3714
3715 class PassStatNode(StatNode):
3716     #  pass statement
3717
3718     child_attrs = []
3719     
3720     def analyse_expressions(self, env):
3721         pass
3722     
3723     def generate_execution_code(self, code):
3724         pass
3725
3726
3727 class BreakStatNode(StatNode):
3728
3729     child_attrs = []
3730
3731     def analyse_expressions(self, env):
3732         pass
3733     
3734     def generate_execution_code(self, code):
3735         if not code.break_label:
3736             error(self.pos, "break statement not inside loop")
3737         else:
3738             code.put_goto(code.break_label)
3739
3740
3741 class ContinueStatNode(StatNode):
3742
3743     child_attrs = []
3744
3745     def analyse_expressions(self, env):
3746         pass
3747     
3748     def generate_execution_code(self, code):
3749         if code.funcstate.in_try_finally:
3750             error(self.pos, "continue statement inside try of try...finally")
3751         elif not code.continue_label:
3752             error(self.pos, "continue statement not inside loop")
3753         else:
3754             code.put_goto(code.continue_label)
3755
3756
3757 class ReturnStatNode(StatNode):
3758     #  return statement
3759     #
3760     #  value         ExprNode or None
3761     #  return_type   PyrexType
3762     
3763     child_attrs = ["value"]
3764
3765     def analyse_expressions(self, env):
3766         return_type = env.return_type
3767         self.return_type = return_type
3768         if not return_type:
3769             error(self.pos, "Return not inside a function body")
3770             return
3771         if self.value:
3772             self.value.analyse_types(env)
3773             if return_type.is_void or return_type.is_returncode:
3774                 error(self.value.pos, 
3775                     "Return with value in void function")
3776             else:
3777                 self.value = self.value.coerce_to(env.return_type, env)
3778         else:
3779             if (not return_type.is_void
3780                 and not return_type.is_pyobject
3781                 and not return_type.is_returncode):
3782                     error(self.pos, "Return value required")
3783
3784     def nogil_check(self, env):
3785         if self.return_type.is_pyobject:
3786             self.gil_error()
3787
3788     gil_message = "Returning Python object"
3789
3790     def generate_execution_code(self, code):
3791         code.mark_pos(self.pos)
3792         if not self.return_type:
3793             # error reported earlier
3794             return
3795         if self.return_type.is_pyobject:
3796             code.put_xdecref(Naming.retval_cname,
3797                              self.return_type)
3798         if self.value:
3799             self.value.generate_evaluation_code(code)
3800             self.value.make_owned_reference(code)
3801             code.putln(
3802                 "%s = %s;" % (
3803                     Naming.retval_cname,
3804                     self.value.result_as(self.return_type)))
3805             self.value.generate_post_assignment_code(code)
3806             self.value.free_temps(code)
3807         else:
3808             if self.return_type.is_pyobject:
3809                 code.put_init_to_py_none(Naming.retval_cname, self.return_type)
3810             elif self.return_type.is_returncode:
3811                 code.putln(
3812                     "%s = %s;" % (
3813                         Naming.retval_cname,
3814                         self.return_type.default_value))
3815         for cname, type in code.funcstate.temps_holding_reference():
3816             code.put_decref_clear(cname, type)
3817         code.put_goto(code.return_label)
3818
3819     def generate_function_definitions(self, env, code):
3820         if self.value is not None:
3821             self.value.generate_function_definitions(env, code)
3822         
3823     def annotate(self, code):
3824         if self.value:
3825             self.value.annotate(code)
3826
3827
3828 class RaiseStatNode(StatNode):
3829     #  raise statement
3830     #
3831     #  exc_type    ExprNode or None
3832     #  exc_value   ExprNode or None
3833     #  exc_tb      ExprNode or None
3834     
3835     child_attrs = ["exc_type", "exc_value", "exc_tb"]
3836
3837     def analyse_expressions(self, env):
3838         if self.exc_type:
3839             self.exc_type.analyse_types(env)
3840             self.exc_type = self.exc_type.coerce_to_pyobject(env)
3841         if self.exc_value:
3842             self.exc_value.analyse_types(env)
3843             self.exc_value = self.exc_value.coerce_to_pyobject(env)
3844         if self.exc_tb:
3845             self.exc_tb.analyse_types(env)
3846             self.exc_tb = self.exc_tb.coerce_to_pyobject(env)
3847         env.use_utility_code(raise_utility_code)
3848
3849     nogil_check = Node.gil_error
3850     gil_message = "Raising exception"
3851
3852     def generate_execution_code(self, code):
3853         if self.exc_type:
3854             self.exc_type.generate_evaluation_code(code)
3855             type_code = self.exc_type.py_result()
3856         else:
3857             type_code = "0"
3858         if self.exc_value:
3859             self.exc_value.generate_evaluation_code(code)
3860             value_code = self.exc_value.py_result()
3861         else:
3862             value_code = "0"
3863         if self.exc_tb:
3864             self.exc_tb.generate_evaluation_code(code)
3865             tb_code = self.exc_tb.py_result()
3866         else:
3867             tb_code = "0"
3868         code.putln(
3869             "__Pyx_Raise(%s, %s, %s);" % (
3870                 type_code,
3871                 value_code,
3872                 tb_code))
3873         for obj in (self.exc_type, self.exc_value, self.exc_tb):
3874             if obj:
3875                 obj.generate_disposal_code(code)
3876                 obj.free_temps(code)
3877         code.putln(
3878             code.error_goto(self.pos))
3879
3880     def generate_function_definitions(self, env, code):
3881         if self.exc_type is not None:
3882             self.exc_type.generate_function_definitions(env, code)
3883         if self.exc_value is not None:
3884             self.exc_value.generate_function_definitions(env, code)
3885         if self.exc_tb is not None:
3886             self.exc_tb.generate_function_definitions(env, code)
3887
3888     def annotate(self, code):
3889         if self.exc_type:
3890             self.exc_type.annotate(code)
3891         if self.exc_value:
3892             self.exc_value.annotate(code)
3893         if self.exc_tb:
3894             self.exc_tb.annotate(code)
3895
3896
3897 class ReraiseStatNode(StatNode):
3898
3899     child_attrs = []
3900
3901     def analyse_expressions(self, env):
3902         env.use_utility_code(restore_exception_utility_code)
3903
3904     nogil_check = Node.gil_error
3905     gil_message = "Raising exception"
3906
3907     def generate_execution_code(self, code):
3908         vars = code.funcstate.exc_vars
3909         if vars:
3910             for varname in vars:
3911                 code.put_giveref(varname)
3912             code.putln("__Pyx_ErrRestore(%s, %s, %s);" % tuple(vars))
3913             for varname in vars:
3914                 code.put("%s = 0; " % varname)
3915             code.putln()
3916             code.putln(code.error_goto(self.pos))
3917         else:
3918             error(self.pos, "Reraise not inside except clause")
3919         
3920
3921 class AssertStatNode(StatNode):
3922     #  assert statement
3923     #
3924     #  cond    ExprNode
3925     #  value   ExprNode or None
3926     
3927     child_attrs = ["cond", "value"]
3928
3929     def analyse_expressions(self, env):
3930         self.cond = self.cond.analyse_boolean_expression(env)
3931         if self.value:
3932             self.value.analyse_types(env)
3933             self.value = self.value.coerce_to_pyobject(env)
3934
3935     nogil_check = Node.gil_error
3936     gil_message = "Raising exception"
3937     
3938     def generate_execution_code(self, code):
3939         code.putln("#ifndef PYREX_WITHOUT_ASSERTIONS")
3940         self.cond.generate_evaluation_code(code)
3941         code.putln(
3942             "if (unlikely(!%s)) {" %
3943                 self.cond.result())
3944         if self.value:
3945             self.value.generate_evaluation_code(code)
3946             code.putln(
3947                 "PyErr_SetObject(PyExc_AssertionError, %s);" %
3948                     self.value.py_result())
3949             self.value.generate_disposal_code(code)
3950             self.value.free_temps(code)
3951         else:
3952             code.putln(
3953                 "PyErr_SetNone(PyExc_AssertionError);")
3954         code.putln(
3955                 code.error_goto(self.pos))
3956         code.putln(
3957             "}")
3958         self.cond.generate_disposal_code(code)
3959         self.cond.free_temps(code)
3960         code.putln("#endif")
3961
3962     def generate_function_definitions(self, env, code):
3963         self.cond.generate_function_definitions(env, code)
3964         if self.value is not None:
3965             self.value.generate_function_definitions(env, code)
3966
3967     def annotate(self, code):
3968         self.cond.annotate(code)
3969         if self.value:
3970             self.value.annotate(code)
3971
3972
3973 class IfStatNode(StatNode):
3974     #  if statement
3975     #
3976     #  if_clauses   [IfClauseNode]
3977     #  else_clause  StatNode or None
3978
3979     child_attrs = ["if_clauses", "else_clause"]
3980     
3981     def analyse_control_flow(self, env):
3982         env.start_branching(self.pos)
3983         for if_clause in self.if_clauses:
3984             if_clause.analyse_control_flow(env)
3985             env.next_branch(if_clause.end_pos())
3986         if self.else_clause:
3987             self.else_clause.analyse_control_flow(env)
3988         env.finish_branching(self.end_pos())
3989
3990     def analyse_declarations(self, env):
3991         for if_clause in self.if_clauses:
3992             if_clause.analyse_declarations(env)
3993         if self.else_clause:
3994             self.else_clause.analyse_declarations(env)
3995     
3996     def analyse_expressions(self, env):
3997         for if_clause in self.if_clauses:
3998             if_clause.analyse_expressions(env)
3999         if self.else_clause:
4000             self.else_clause.analyse_expressions(env)
4001
4002     def generate_execution_code(self, code):
4003         code.mark_pos(self.pos)
4004         end_label = code.new_label()
4005         for if_clause in self.if_clauses:
4006             if_clause.generate_execution_code(code, end_label)
4007         if self.else_clause:
4008             code.putln("/*else*/ {")
4009             self.else_clause.generate_execution_code(code)
4010             code.putln("}")
4011         code.put_label(end_label)
4012
4013     def generate_function_definitions(self, env, code):
4014         for clause in self.if_clauses:
4015             clause.generate_function_definitions(env, code)
4016         if self.else_clause is not None:
4017             self.else_clause.generate_function_definitions(env, code)
4018
4019     def annotate(self, code):
4020         for if_clause in self.if_clauses:
4021             if_clause.annotate(code)
4022         if self.else_clause:
4023             self.else_clause.annotate(code)
4024
4025
4026 class IfClauseNode(Node):
4027     #  if or elif clause in an if statement
4028     #
4029     #  condition   ExprNode
4030     #  body        StatNode
4031     
4032     child_attrs = ["condition", "body"]
4033
4034     def analyse_control_flow(self, env):
4035         self.body.analyse_control_flow(env)
4036         
4037     def analyse_declarations(self, env):
4038         self.body.analyse_declarations(env)
4039     
4040     def analyse_expressions(self, env):
4041         self.condition = \
4042             self.condition.analyse_temp_boolean_expression(env)
4043         self.body.analyse_expressions(env)
4044
4045     def get_constant_condition_result(self):
4046         if self.condition.has_constant_result():
4047             return bool(self.condition.constant_result)
4048         else:
4049             return None
4050
4051     def generate_execution_code(self, code, end_label):
4052         self.condition.generate_evaluation_code(code)
4053         code.putln(
4054             "if (%s) {" %
4055                 self.condition.result())
4056         self.condition.generate_disposal_code(code)
4057         self.condition.free_temps(code)
4058         self.body.generate_execution_code(code)
4059         code.put_goto(end_label)
4060         code.putln("}")
4061
4062     def generate_function_definitions(self, env, code):
4063         self.condition.generate_function_definitions(env, code)
4064         self.body.generate_function_definitions(env, code)
4065
4066     def annotate(self, code):
4067         self.condition.annotate(code)
4068         self.body.annotate(code)
4069         
4070
4071 class SwitchCaseNode(StatNode):
4072     # Generated in the optimization of an if-elif-else node
4073     #
4074     # conditions    [ExprNode]
4075     # body          StatNode
4076     
4077     child_attrs = ['conditions', 'body']
4078
4079     def generate_execution_code(self, code):
4080         for cond in self.conditions:
4081             code.mark_pos(cond.pos)
4082             cond.generate_evaluation_code(code)
4083             code.putln("case %s:" % cond.result())
4084         self.body.generate_execution_code(code)
4085         code.putln("break;")
4086
4087     def generate_function_definitions(self, env, code):
4088         for cond in self.conditions:
4089             cond.generate_function_definitions(env, code)
4090         self.body.generate_function_definitions(env, code)
4091         
4092     def annotate(self, code):
4093         for cond in self.conditions:
4094             cond.annotate(code)
4095         self.body.annotate(code)
4096
4097 class SwitchStatNode(StatNode):
4098     # Generated in the optimization of an if-elif-else node
4099     #
4100     # test          ExprNode
4101     # cases         [SwitchCaseNode]
4102     # else_clause   StatNode or None
4103     
4104     child_attrs = ['test', 'cases', 'else_clause']
4105     
4106     def generate_execution_code(self, code):
4107         self.test.generate_evaluation_code(code)
4108         code.putln("switch (%s) {" % self.test.result())
4109         for case in self.cases:
4110             case.generate_execution_code(code)
4111         if self.else_clause is not None:
4112             code.putln("default:")
4113             self.else_clause.generate_execution_code(code)
4114             code.putln("break;")
4115         code.putln("}")
4116
4117     def generate_function_definitions(self, env, code):
4118         self.test.generate_function_definitions(env, code)
4119         for case in self.cases:
4120             case.generate_function_definitions(env, code)
4121         if self.else_clause is not None:
4122             self.else_clause.generate_function_definitions(env, code)
4123
4124     def annotate(self, code):
4125         self.test.annotate(code)
4126         for case in self.cases:
4127             case.annotate(code)
4128         if self.else_clause is not None:
4129             self.else_clause.annotate(code)
4130             
4131 class LoopNode(object):
4132     
4133     def analyse_control_flow(self, env):
4134         env.start_branching(self.pos)
4135         self.body.analyse_control_flow(env)
4136         env.next_branch(self.body.end_pos())
4137         if self.else_clause:
4138             self.else_clause.analyse_control_flow(env)
4139         env.finish_branching(self.end_pos())
4140
4141     
4142 class WhileStatNode(LoopNode, StatNode):
4143     #  while statement
4144     #
4145     #  condition    ExprNode
4146     #  body         StatNode
4147     #  else_clause  StatNode
4148
4149     child_attrs = ["condition", "body", "else_clause"]
4150
4151     def analyse_declarations(self, env):
4152         self.body.analyse_declarations(env)
4153         if self.else_clause:
4154             self.else_clause.analyse_declarations(env)
4155     
4156     def analyse_expressions(self, env):
4157         self.condition = \
4158             self.condition.analyse_temp_boolean_expression(env)
4159         self.body.analyse_expressions(env)
4160         if self.else_clause:
4161             self.else_clause.analyse_expressions(env)
4162     
4163     def generate_execution_code(self, code):
4164         old_loop_labels = code.new_loop_labels()
4165         code.putln(
4166             "while (1) {")
4167         self.condition.generate_evaluation_code(code)
4168         self.condition.generate_disposal_code(code)
4169         code.putln(
4170             "if (!%s) break;" %
4171                 self.condition.result())
4172         self.condition.free_temps(code)
4173         self.body.generate_execution_code(code)
4174         code.put_label(code.continue_label)
4175         code.putln("}")
4176         break_label = code.break_label
4177         code.set_loop_labels(old_loop_labels)
4178         if self.else_clause:
4179             code.putln("/*else*/ {")
4180             self.else_clause.generate_execution_code(code)
4181             code.putln("}")
4182         code.put_label(break_label)
4183
4184     def generate_function_definitions(self, env, code):
4185         self.condition.generate_function_definitions(env, code)
4186         self.body.generate_function_definitions(env, code)
4187         if self.else_clause is not None:
4188             self.else_clause.generate_function_definitions(env, code)
4189
4190     def annotate(self, code):
4191         self.condition.annotate(code)
4192         self.body.annotate(code)
4193         if self.else_clause:
4194             self.else_clause.annotate(code)
4195
4196
4197 def ForStatNode(pos, **kw):
4198     if 'iterator' in kw:
4199         return ForInStatNode(pos, **kw)
4200     else:
4201         return ForFromStatNode(pos, **kw)
4202
4203 class ForInStatNode(LoopNode, StatNode):
4204     #  for statement
4205     #
4206     #  target        ExprNode
4207     #  iterator      IteratorNode
4208     #  body          StatNode
4209     #  else_clause   StatNode
4210     #  item          NextNode       used internally
4211     
4212     child_attrs = ["target", "iterator", "body", "else_clause"]
4213     item = None
4214     
4215     def analyse_declarations(self, env):
4216         self.target.analyse_target_declaration(env)
4217         self.body.analyse_declarations(env)
4218         if self.else_clause:
4219             self.else_clause.analyse_declarations(env)
4220
4221     def analyse_expressions(self, env):
4222         import ExprNodes
4223         self.target.analyse_target_types(env)
4224         self.iterator.analyse_expressions(env)
4225         self.item = ExprNodes.NextNode(self.iterator, env)
4226         self.item = self.item.coerce_to(self.target.type, env)
4227         self.body.analyse_expressions(env)
4228         if self.else_clause:
4229             self.else_clause.analyse_expressions(env)
4230
4231     def generate_execution_code(self, code):
4232         old_loop_labels = code.new_loop_labels()
4233         self.iterator.allocate_counter_temp(code)
4234         self.iterator.generate_evaluation_code(code)
4235         code.putln(
4236             "for (;;) {")
4237         self.item.generate_evaluation_code(code)
4238         self.target.generate_assignment_code(self.item, code)
4239         self.body.generate_execution_code(code)
4240         code.put_label(code.continue_label)
4241         code.putln(
4242             "}")
4243         break_label = code.break_label
4244         code.set_loop_labels(old_loop_labels)
4245
4246         if self.else_clause:
4247             # in nested loops, the 'else' block can contain a
4248             # 'continue' statement for the outer loop, but we may need
4249             # to generate cleanup code before taking that path, so we
4250             # intercept it here
4251             orig_continue_label = code.continue_label
4252             code.continue_label = code.new_label('outer_continue')
4253
4254             code.putln("/*else*/ {")
4255             self.else_clause.generate_execution_code(code)
4256             code.putln("}")
4257
4258             if code.label_used(code.continue_label):
4259                 code.put_goto(break_label)
4260                 code.put_label(code.continue_label)
4261                 self.iterator.generate_disposal_code(code)
4262                 code.put_goto(orig_continue_label)
4263             code.set_loop_labels(old_loop_labels)
4264
4265         if code.label_used(break_label):
4266             code.put_label(break_label)
4267         self.iterator.release_counter_temp(code)
4268         self.iterator.generate_disposal_code(code)
4269         self.iterator.free_temps(code)
4270
4271     def generate_function_definitions(self, env, code):
4272         self.target.generate_function_definitions(env, code)
4273         self.iterator.generate_function_definitions(env, code)
4274         self.body.generate_function_definitions(env, code)
4275         if self.else_clause is not None:
4276             self.else_clause.generate_function_definitions(env, code)
4277
4278     def annotate(self, code):
4279         self.target.annotate(code)
4280         self.iterator.annotate(code)
4281         self.body.annotate(code)
4282         if self.else_clause:
4283             self.else_clause.annotate(code)
4284         self.item.annotate(code)
4285
4286
4287 class ForFromStatNode(LoopNode, StatNode):
4288     #  for name from expr rel name rel expr
4289     #
4290     #  target        NameNode
4291     #  bound1        ExprNode
4292     #  relation1     string
4293     #  relation2     string
4294     #  bound2        ExprNode
4295     #  step          ExprNode or None
4296     #  body          StatNode
4297     #  else_clause   StatNode or None
4298     #
4299     #  Used internally:
4300     #
4301     #  from_range         bool
4302     #  is_py_target       bool
4303     #  loopvar_node       ExprNode (usually a NameNode or temp node)
4304     #  py_loopvar_node    PyTempNode or None
4305     child_attrs = ["target", "bound1", "bound2", "step", "body", "else_clause"]
4306
4307     is_py_target = False
4308     loopvar_node = None
4309     py_loopvar_node = None
4310     from_range = False
4311
4312     gil_message = "For-loop using object bounds or target"
4313
4314     def nogil_check(self, env):
4315         for x in (self.target, self.bound1, self.bound2):
4316             if x.type.is_pyobject:
4317                 self.gil_error()
4318
4319     def analyse_declarations(self, env):
4320         self.target.analyse_target_declaration(env)
4321         self.body.analyse_declarations(env)
4322         if self.else_clause:
4323             self.else_clause.analyse_declarations(env)
4324
4325     def analyse_expressions(self, env):
4326         import ExprNodes
4327         self.target.analyse_target_types(env)
4328         self.bound1.analyse_types(env)
4329         self.bound2.analyse_types(env)
4330         if self.step is not None:
4331             if isinstance(self.step, ExprNodes.UnaryMinusNode):
4332                 warning(self.step.pos, "Probable infinite loop in for-from-by statment. Consider switching the directions of the relations.", 2)
4333             self.step.analyse_types(env)
4334         
4335         target_type = self.target.type
4336         if self.target.type.is_numeric:
4337             loop_type = self.target.type
4338         else:
4339             loop_type = PyrexTypes.c_int_type
4340             if not self.bound1.type.is_pyobject:
4341                 loop_type = PyrexTypes.widest_numeric_type(loop_type, self.bound1.type)
4342             if not self.bound2.type.is_pyobject:
4343                 loop_type = PyrexTypes.widest_numeric_type(loop_type, self.bound2.type)
4344             if self.step is not None and not self.step.type.is_pyobject:
4345                 loop_type = PyrexTypes.widest_numeric_type(loop_type, self.step.type)
4346         self.bound1 = self.bound1.coerce_to(loop_type, env)
4347         self.bound2 = self.bound2.coerce_to(loop_type, env)
4348         if not self.bound2.is_literal:
4349             self.bound2 = self.bound2.coerce_to_temp(env)
4350         if self.step is not None:
4351             self.step = self.step.coerce_to(loop_type, env)            
4352             if not self.step.is_literal:
4353                 self.step = self.step.coerce_to_temp(env)
4354
4355         target_type = self.target.type
4356         if not (target_type.is_pyobject or target_type.is_numeric):
4357             error(self.target.pos,
4358                 "for-from loop variable must be c numeric type or Python object")
4359         if target_type.is_numeric:
4360             self.is_py_target = False
4361             if isinstance(self.target, ExprNodes.IndexNode) and self.target.is_buffer_access:
4362                 raise error(self.pos, "Buffer indexing not allowed as for loop target.")
4363             self.loopvar_node = self.target
4364             self.py_loopvar_node = None
4365         else:
4366             self.is_py_target = True
4367             c_loopvar_node = ExprNodes.TempNode(self.pos, loop_type, env)
4368             self.loopvar_node = c_loopvar_node
4369             self.py_loopvar_node = \
4370                 ExprNodes.CloneNode(c_loopvar_node).coerce_to_pyobject(env)
4371         self.body.analyse_expressions(env)
4372         if self.else_clause:
4373             self.else_clause.analyse_expressions(env)
4374             
4375     def generate_execution_code(self, code):
4376         old_loop_labels = code.new_loop_labels()
4377         from_range = self.from_range
4378         self.bound1.generate_evaluation_code(code)
4379         self.bound2.generate_evaluation_code(code)
4380         offset, incop = self.relation_table[self.relation1]
4381         if self.step is not None:
4382             self.step.generate_evaluation_code(code)
4383             step = self.step.result()
4384             incop = "%s=%s" % (incop[0], step)
4385         import ExprNodes
4386         if isinstance(self.loopvar_node, ExprNodes.TempNode):
4387             self.loopvar_node.allocate(code)
4388         if isinstance(self.py_loopvar_node, ExprNodes.TempNode):
4389             self.py_loopvar_node.allocate(code)
4390         if from_range:
4391             loopvar_name = code.funcstate.allocate_temp(self.target.type, False)
4392         else:
4393             loopvar_name = self.loopvar_node.result()
4394         code.putln(
4395             "for (%s = %s%s; %s %s %s; %s%s) {" % (
4396                 loopvar_name,
4397                 self.bound1.result(), offset,
4398                 loopvar_name, self.relation2, self.bound2.result(),
4399                 loopvar_name, incop))
4400         if self.py_loopvar_node:
4401             self.py_loopvar_node.generate_evaluation_code(code)
4402             self.target.generate_assignment_code(self.py_loopvar_node, code)
4403         elif from_range:
4404             code.putln("%s = %s;" % (
4405                             self.target.result(), loopvar_name))
4406         self.body.generate_execution_code(code)
4407         code.put_label(code.continue_label)
4408         if self.py_loopvar_node:
4409             # This mess is to make for..from loops with python targets behave 
4410             # exactly like those with C targets with regards to re-assignment 
4411             # of the loop variable. 
4412             import ExprNodes
4413             if self.target.entry.is_pyglobal:
4414                 # We know target is a NameNode, this is the only ugly case. 
4415                 target_node = ExprNodes.PyTempNode(self.target.pos, None)
4416                 target_node.allocate(code)
4417                 interned_cname = code.intern_identifier(self.target.entry.name)
4418                 code.globalstate.use_utility_code(ExprNodes.get_name_interned_utility_code)
4419                 code.putln("%s = __Pyx_GetName(%s, %s); %s" % (
4420                                 target_node.result(),
4421                                 Naming.module_cname, 
4422                                 interned_cname,
4423                                 code.error_goto_if_null(target_node.result(), self.target.pos)))
4424                 code.put_gotref(target_node.result())
4425             else:
4426                 target_node = self.target
4427             from_py_node = ExprNodes.CoerceFromPyTypeNode(self.loopvar_node.type, target_node, None)
4428             from_py_node.temp_code = loopvar_name
4429             from_py_node.generate_result_code(code)
4430             if self.target.entry.is_pyglobal:
4431                 code.put_decref(target_node.result(), target_node.type)
4432                 target_node.release(code)
4433         code.putln("}")
4434         if self.py_loopvar_node:
4435             # This is potentially wasteful, but we don't want the semantics to 
4436             # depend on whether or not the loop is a python type. 
4437             self.py_loopvar_node.generate_evaluation_code(code)
4438             self.target.generate_assignment_code(self.py_loopvar_node, code)
4439         if from_range:
4440             code.funcstate.release_temp(loopvar_name)
4441         break_label = code.break_label
4442         code.set_loop_labels(old_loop_labels)
4443         if self.else_clause:
4444             code.putln("/*else*/ {")
4445             self.else_clause.generate_execution_code(code)
4446             code.putln("}")
4447         code.put_label(break_label)
4448         self.bound1.generate_disposal_code(code)
4449         self.bound1.free_temps(code)
4450         self.bound2.generate_disposal_code(code)
4451         self.bound2.free_temps(code)
4452         if isinstance(self.loopvar_node, ExprNodes.TempNode):
4453             self.loopvar_node.release(code)
4454         if isinstance(self.py_loopvar_node, ExprNodes.TempNode):
4455             self.py_loopvar_node.release(code)
4456         if self.step is not None:
4457             self.step.generate_disposal_code(code)
4458             self.step.free_temps(code)
4459     
4460     relation_table = {
4461         # {relop : (initial offset, increment op)}
4462         '<=': ("",   "++"),
4463         '<' : ("+1", "++"),
4464         '>=': ("",   "--"),
4465         '>' : ("-1", "--")
4466     }
4467
4468     def generate_function_definitions(self, env, code):
4469         self.target.generate_function_definitions(env, code)
4470         self.bound1.generate_function_definitions(env, code)
4471         self.bound2.generate_function_definitions(env, code)
4472         if self.step is not None:
4473             self.step.generate_function_definitions(env, code)
4474         self.body.generate_function_definitions(env, code)
4475         if self.else_clause is not None:
4476             self.else_clause.generate_function_definitions(env, code)
4477     
4478     def annotate(self, code):
4479         self.target.annotate(code)
4480         self.bound1.annotate(code)
4481         self.bound2.annotate(code)
4482         if self.step:
4483             self.step.annotate(code)
4484         self.body.annotate(code)
4485         if self.else_clause:
4486             self.else_clause.annotate(code)
4487
4488
4489 class WithStatNode(StatNode):
4490     """
4491     Represents a Python with statement.
4492     
4493     This is only used at parse tree level; and is not present in
4494     analysis or generation phases.
4495     """
4496     #  manager          The with statement manager object
4497     #  target            Node (lhs expression)
4498     #  body             StatNode
4499     child_attrs = ["manager", "target", "body"]
4500
4501 class TryExceptStatNode(StatNode):
4502     #  try .. except statement
4503     #
4504     #  body             StatNode
4505     #  except_clauses   [ExceptClauseNode]
4506     #  else_clause      StatNode or None
4507
4508     child_attrs = ["body", "except_clauses", "else_clause"]
4509     
4510     def analyse_control_flow(self, env):
4511         env.start_branching(self.pos)
4512         self.body.analyse_control_flow(env)
4513         successful_try = env.control_flow # grab this for later
4514         env.next_branch(self.body.end_pos())
4515         env.finish_branching(self.body.end_pos())
4516         
4517         env.start_branching(self.except_clauses[0].pos)
4518         for except_clause in self.except_clauses:
4519             except_clause.analyse_control_flow(env)
4520             env.next_branch(except_clause.end_pos())
4521             
4522         # the else cause it executed only when the try clause finishes
4523         env.control_flow.incoming = successful_try
4524         if self.else_clause:
4525             self.else_clause.analyse_control_flow(env)
4526         env.finish_branching(self.end_pos())
4527
4528     def analyse_declarations(self, env):
4529         self.body.analyse_declarations(env)
4530         for except_clause in self.except_clauses:
4531             except_clause.analyse_declarations(env)
4532         if self.else_clause:
4533             self.else_clause.analyse_declarations(env)
4534         env.use_utility_code(reset_exception_utility_code)
4535
4536     def analyse_expressions(self, env):
4537         self.body.analyse_expressions(env)
4538         default_clause_seen = 0
4539         for except_clause in self.except_clauses:
4540             except_clause.analyse_expressions(env)
4541             if default_clause_seen:
4542                 error(except_clause.pos, "default 'except:' must be last")
4543             if not except_clause.pattern:
4544                 default_clause_seen = 1
4545         self.has_default_clause = default_clause_seen
4546         if self.else_clause:
4547             self.else_clause.analyse_expressions(env)
4548
4549     nogil_check = Node.gil_error
4550     gil_message = "Try-except statement"
4551
4552     def generate_execution_code(self, code):
4553         old_return_label = code.return_label
4554         old_break_label = code.break_label
4555         old_continue_label = code.continue_label
4556         old_error_label = code.new_error_label()
4557         our_error_label = code.error_label
4558         except_end_label = code.new_label('exception_handled')
4559         except_error_label = code.new_label('except_error')
4560         except_return_label = code.new_label('except_return')
4561         try_return_label = code.new_label('try_return')
4562         try_break_label = code.new_label('try_break')
4563         try_continue_label = code.new_label('try_continue')
4564         try_end_label = code.new_label('try_end')
4565
4566         code.putln("{")
4567         code.putln("PyObject %s;" %
4568                    ', '.join(['*%s' % var for var in Naming.exc_save_vars]))
4569         code.putln("__Pyx_ExceptionSave(%s);" %
4570                    ', '.join(['&%s' % var for var in Naming.exc_save_vars]))
4571         for var in Naming.exc_save_vars:
4572             code.put_xgotref(var)
4573         code.putln(
4574             "/*try:*/ {")
4575         code.return_label = try_return_label
4576         code.break_label = try_break_label
4577         code.continue_label = try_continue_label
4578         self.body.generate_execution_code(code)
4579         code.putln(
4580             "}")
4581         temps_to_clean_up = code.funcstate.all_free_managed_temps()
4582         code.error_label = except_error_label
4583         code.return_label = except_return_label
4584         if self.else_clause:
4585             code.putln(
4586                 "/*else:*/ {")
4587             self.else_clause.generate_execution_code(code)
4588             code.putln(
4589                 "}")
4590         for var in Naming.exc_save_vars:
4591             code.put_xdecref_clear(var, py_object_type)
4592         code.put_goto(try_end_label)
4593         if code.label_used(try_return_label):
4594             code.put_label(try_return_label)
4595             for var in Naming.exc_save_vars: code.put_xgiveref(var)
4596             code.putln("__Pyx_ExceptionReset(%s);" %
4597                        ', '.join(Naming.exc_save_vars))
4598             code.put_goto(old_return_label)
4599         code.put_label(our_error_label)
4600         for temp_name, type in temps_to_clean_up:
4601             code.put_xdecref_clear(temp_name, type)
4602         for except_clause in self.except_clauses:
4603             except_clause.generate_handling_code(code, except_end_label)
4604
4605         error_label_used = code.label_used(except_error_label)
4606         if error_label_used or not self.has_default_clause:
4607             if error_label_used:
4608                 code.put_label(except_error_label)
4609             for var in Naming.exc_save_vars: code.put_xgiveref(var)
4610             code.putln("__Pyx_ExceptionReset(%s);" %
4611                        ', '.join(Naming.exc_save_vars))
4612             code.put_goto(old_error_label)
4613
4614         for exit_label, old_label in zip(
4615             [try_break_label, try_continue_label, except_return_label],
4616             [old_break_label, old_continue_label, old_return_label]):
4617
4618             if code.label_used(exit_label):
4619                 code.put_label(exit_label)
4620                 for var in Naming.exc_save_vars: code.put_xgiveref(var)
4621                 code.putln("__Pyx_ExceptionReset(%s);" %
4622                            ', '.join(Naming.exc_save_vars))
4623                 code.put_goto(old_label)
4624
4625         if code.label_used(except_end_label):
4626             code.put_label(except_end_label)
4627             for var in Naming.exc_save_vars: code.put_xgiveref(var)
4628             code.putln("__Pyx_ExceptionReset(%s);" %
4629                        ', '.join(Naming.exc_save_vars))
4630         code.put_label(try_end_label)
4631         code.putln("}")
4632
4633         code.return_label = old_return_label
4634         code.break_label = old_break_label
4635         code.continue_label = old_continue_label
4636         code.error_label = old_error_label
4637
4638     def generate_function_definitions(self, env, code):
4639         self.body.generate_function_definitions(env, code)
4640         for except_clause in self.except_clauses:
4641             except_clause.generate_function_definitions(env, code)
4642         if self.else_clause is not None:
4643             self.else_clause.generate_function_definitions(env, code)
4644
4645     def annotate(self, code):
4646         self.body.annotate(code)
4647         for except_node in self.except_clauses:
4648             except_node.annotate(code)
4649         if self.else_clause:
4650             self.else_clause.annotate(code)
4651
4652
4653 class ExceptClauseNode(Node):
4654     #  Part of try ... except statement.
4655     #
4656     #  pattern        [ExprNode]
4657     #  target         ExprNode or None
4658     #  body           StatNode
4659     #  excinfo_target NameNode or None   optional target for exception info
4660     #  match_flag     string             result of exception match
4661     #  exc_value      ExcValueNode       used internally
4662     #  function_name  string             qualified name of enclosing function
4663     #  exc_vars       (string * 3)       local exception variables
4664
4665     # excinfo_target is never set by the parser, but can be set by a transform
4666     # in order to extract more extensive information about the exception as a
4667     # sys.exc_info()-style tuple into a target variable
4668     
4669     child_attrs = ["pattern", "target", "body", "exc_value", "excinfo_target"]
4670
4671     exc_value = None
4672     excinfo_target = None
4673
4674     def analyse_declarations(self, env):
4675         if self.target:
4676             self.target.analyse_target_declaration(env)
4677         if self.excinfo_target is not None:
4678             self.excinfo_target.analyse_target_declaration(env)
4679         self.body.analyse_declarations(env)
4680     
4681     def analyse_expressions(self, env):
4682         import ExprNodes
4683         genv = env.global_scope()
4684         self.function_name = env.qualified_name
4685         if self.pattern:
4686             # normalise/unpack self.pattern into a list
4687             for i, pattern in enumerate(self.pattern):
4688                 pattern.analyse_expressions(env)
4689                 self.pattern[i] = pattern.coerce_to_pyobject(env)
4690
4691         if self.target:
4692             self.exc_value = ExprNodes.ExcValueNode(self.pos, env)
4693             self.target.analyse_target_expression(env, self.exc_value)
4694         if self.excinfo_target is not None:
4695             import ExprNodes
4696             self.excinfo_tuple = ExprNodes.TupleNode(pos=self.pos, args=[
4697                 ExprNodes.ExcValueNode(pos=self.pos, env=env) for x in range(3)])
4698             self.excinfo_tuple.analyse_expressions(env)
4699             self.excinfo_target.analyse_target_expression(env, self.excinfo_tuple)
4700
4701         self.body.analyse_expressions(env)
4702
4703     def generate_handling_code(self, code, end_label):
4704         code.mark_pos(self.pos)
4705         if self.pattern:
4706             exc_tests = []
4707             for pattern in self.pattern:
4708                 pattern.generate_evaluation_code(code)
4709                 exc_tests.append("PyErr_ExceptionMatches(%s)" % pattern.py_result())
4710
4711             match_flag = code.funcstate.allocate_temp(PyrexTypes.c_int_type, False)
4712             code.putln(
4713                 "%s = %s;" % (match_flag, ' || '.join(exc_tests)))
4714             for pattern in self.pattern:
4715                 pattern.generate_disposal_code(code)
4716                 pattern.free_temps(code)
4717             code.putln(
4718                 "if (%s) {" %
4719                     match_flag)
4720             code.funcstate.release_temp(match_flag)
4721         else:
4722             code.putln("/*except:*/ {")
4723
4724         if not getattr(self.body, 'stats', True) and \
4725                 self.excinfo_target is None and self.target is None:
4726             # most simple case: no exception variable, empty body (pass)
4727             # => reset the exception state, done
4728             code.putln("PyErr_Restore(0,0,0);")
4729             code.put_goto(end_label)
4730             code.putln("}")
4731             return
4732         
4733         exc_vars = [code.funcstate.allocate_temp(py_object_type,
4734                                                  manage_ref=True)
4735                     for i in xrange(3)]
4736         code.putln('__Pyx_AddTraceback("%s");' % self.function_name)
4737         # We always have to fetch the exception value even if
4738         # there is no target, because this also normalises the 
4739         # exception and stores it in the thread state.
4740         code.globalstate.use_utility_code(get_exception_utility_code)
4741         exc_args = "&%s, &%s, &%s" % tuple(exc_vars)
4742         code.putln("if (__Pyx_GetException(%s) < 0) %s" % (exc_args,
4743             code.error_goto(self.pos)))
4744         for x in exc_vars:
4745             code.put_gotref(x)
4746         if self.target:
4747             self.exc_value.set_var(exc_vars[1])
4748             self.exc_value.generate_evaluation_code(code)
4749             self.target.generate_assignment_code(self.exc_value, code)
4750         if self.excinfo_target is not None:
4751             for tempvar, node in zip(exc_vars, self.excinfo_tuple.args):
4752                 node.set_var(tempvar)
4753             self.excinfo_tuple.generate_evaluation_code(code)
4754             self.excinfo_target.generate_assignment_code(self.excinfo_tuple, code)
4755
4756         old_break_label, old_continue_label = code.break_label, code.continue_label
4757         code.break_label = code.new_label('except_break')
4758         code.continue_label = code.new_label('except_continue')
4759
4760         old_exc_vars = code.funcstate.exc_vars
4761         code.funcstate.exc_vars = exc_vars
4762         self.body.generate_execution_code(code)
4763         code.funcstate.exc_vars = old_exc_vars
4764         for var in exc_vars:
4765             code.putln("__Pyx_DECREF(%s); %s = 0;" % (var, var))
4766         code.put_goto(end_label)
4767         
4768         if code.label_used(code.break_label):
4769             code.put_label(code.break_label)
4770             for var in exc_vars:
4771                 code.putln("__Pyx_DECREF(%s); %s = 0;" % (var, var))
4772             code.put_goto(old_break_label)
4773         code.break_label = old_break_label
4774
4775         if code.label_used(code.continue_label):
4776             code.put_label(code.continue_label)
4777             for var in exc_vars:
4778                 code.putln("__Pyx_DECREF(%s); %s = 0;" % (var, var))
4779             code.put_goto(old_continue_label)
4780         code.continue_label = old_continue_label
4781
4782         for temp in exc_vars:
4783             code.funcstate.release_temp(temp)
4784
4785         code.putln(
4786             "}")
4787
4788     def generate_function_definitions(self, env, code):
4789         if self.target is not None:
4790             self.target.generate_function_definitions(env, code)
4791         self.body.generate_function_definitions(env, code)
4792         
4793     def annotate(self, code):
4794         if self.pattern:
4795             for pattern in self.pattern:
4796                 pattern.annotate(code)
4797         if self.target:
4798             self.target.annotate(code)
4799         self.body.annotate(code)
4800
4801
4802 class TryFinallyStatNode(StatNode):
4803     #  try ... finally statement
4804     #
4805     #  body             StatNode
4806     #  finally_clause   StatNode
4807     #
4808     #  The plan is that we funnel all continue, break
4809     #  return and error gotos into the beginning of the
4810     #  finally block, setting a variable to remember which
4811     #  one we're doing. At the end of the finally block, we
4812     #  switch on the variable to figure out where to go.
4813     #  In addition, if we're doing an error, we save the
4814     #  exception on entry to the finally block and restore
4815     #  it on exit.
4816
4817     child_attrs = ["body", "finally_clause"]
4818     
4819     preserve_exception = 1
4820     
4821     disallow_continue_in_try_finally = 0
4822     # There doesn't seem to be any point in disallowing
4823     # continue in the try block, since we have no problem
4824     # handling it.
4825
4826     def create_analysed(pos, env, body, finally_clause):
4827         node = TryFinallyStatNode(pos, body=body, finally_clause=finally_clause)
4828         return node
4829     create_analysed = staticmethod(create_analysed)
4830     
4831     def analyse_control_flow(self, env):
4832         env.start_branching(self.pos)
4833         self.body.analyse_control_flow(env)
4834         env.next_branch(self.body.end_pos())
4835         env.finish_branching(self.body.end_pos())
4836         self.finally_clause.analyse_control_flow(env)
4837
4838     def analyse_declarations(self, env):
4839         self.body.analyse_declarations(env)
4840         self.finally_clause.analyse_declarations(env)
4841     
4842     def analyse_expressions(self, env):
4843         self.body.analyse_expressions(env)
4844         self.finally_clause.analyse_expressions(env)
4845
4846     nogil_check = Node.gil_error
4847     gil_message = "Try-finally statement"
4848
4849     def generate_execution_code(self, code):
4850         old_error_label = code.error_label
4851         old_labels = code.all_new_labels()
4852         new_labels = code.get_all_labels()
4853         new_error_label = code.error_label
4854         catch_label = code.new_label()
4855         code.putln(
4856             "/*try:*/ {")
4857         if self.disallow_continue_in_try_finally:
4858             was_in_try_finally = code.funcstate.in_try_finally
4859             code.funcstate.in_try_finally = 1
4860         self.body.generate_execution_code(code)
4861         if self.disallow_continue_in_try_finally:
4862             code.funcstate.in_try_finally = was_in_try_finally
4863         code.putln(
4864             "}")
4865         temps_to_clean_up = code.funcstate.all_free_managed_temps()
4866         code.mark_pos(self.finally_clause.pos)
4867         code.putln(
4868             "/*finally:*/ {")
4869         cases_used = []
4870         error_label_used = 0
4871         for i, new_label in enumerate(new_labels):
4872             if new_label in code.labels_used:
4873                 cases_used.append(i)
4874                 if new_label == new_error_label:
4875                     error_label_used = 1
4876                     error_label_case = i
4877         if cases_used:
4878             code.putln(
4879                     "int __pyx_why;")
4880             if error_label_used and self.preserve_exception:
4881                 code.putln(
4882                     "PyObject *%s, *%s, *%s;" % Naming.exc_vars)
4883                 code.putln(
4884                     "int %s;" % Naming.exc_lineno_name)
4885                 exc_var_init_zero = ''.join(["%s = 0; " % var for var in Naming.exc_vars])
4886                 exc_var_init_zero += '%s = 0;' % Naming.exc_lineno_name
4887                 code.putln(exc_var_init_zero)
4888             else:
4889                 exc_var_init_zero = None
4890             code.use_label(catch_label)
4891             code.putln(
4892                     "__pyx_why = 0; goto %s;" % catch_label)
4893             for i in cases_used:
4894                 new_label = new_labels[i]
4895                 #if new_label and new_label != "<try>":
4896                 if new_label == new_error_label and self.preserve_exception:
4897                     self.put_error_catcher(code, 
4898                         new_error_label, i+1, catch_label, temps_to_clean_up)
4899                 else:
4900                     code.put('%s: ' % new_label)
4901                     if exc_var_init_zero:
4902                         code.putln(exc_var_init_zero)
4903                     code.putln("__pyx_why = %s; goto %s;" % (
4904                             i+1,
4905                             catch_label))
4906             code.put_label(catch_label)
4907         code.set_all_labels(old_labels)
4908         if error_label_used:
4909             code.new_error_label()
4910             finally_error_label = code.error_label
4911         self.finally_clause.generate_execution_code(code)
4912         if error_label_used:
4913             if finally_error_label in code.labels_used and self.preserve_exception:
4914                 over_label = code.new_label()
4915                 code.put_goto(over_label);
4916                 code.put_label(finally_error_label)
4917                 code.putln("if (__pyx_why == %d) {" % (error_label_case + 1))
4918                 for var in Naming.exc_vars:
4919                     code.putln("Py_XDECREF(%s);" % var)
4920                 code.putln("}")
4921                 code.put_goto(old_error_label)
4922                 code.put_label(over_label)
4923             code.error_label = old_error_label
4924         if cases_used:
4925             code.putln(
4926                 "switch (__pyx_why) {")
4927             for i in cases_used:
4928                 old_label = old_labels[i]
4929                 if old_label == old_error_label and self.preserve_exception:
4930                     self.put_error_uncatcher(code, i+1, old_error_label)
4931                 else:
4932                     code.use_label(old_label)
4933                     code.putln(
4934                         "case %s: goto %s;" % (
4935                             i+1,
4936                             old_label))
4937             code.putln(
4938                 "}")
4939         code.putln(
4940             "}")
4941
4942     def generate_function_definitions(self, env, code):
4943         self.body.generate_function_definitions(env, code)
4944         self.finally_clause.generate_function_definitions(env, code)
4945
4946     def put_error_catcher(self, code, error_label, i, catch_label, temps_to_clean_up):
4947         code.globalstate.use_utility_code(restore_exception_utility_code)
4948         code.putln(
4949             "%s: {" %
4950                 error_label)
4951         code.putln(
4952                 "__pyx_why = %s;" %
4953                     i)
4954         for temp_name, type in temps_to_clean_up:
4955             code.put_xdecref_clear(temp_name, type)
4956         code.putln(
4957                 "__Pyx_ErrFetch(&%s, &%s, &%s);" %
4958                     Naming.exc_vars)
4959         code.putln(
4960                 "%s = %s;" % (
4961                     Naming.exc_lineno_name, Naming.lineno_cname))
4962         code.put_goto(catch_label)
4963         code.putln("}")
4964             
4965     def put_error_uncatcher(self, code, i, error_label):
4966         code.globalstate.use_utility_code(restore_exception_utility_code)
4967         code.putln(
4968             "case %s: {" %
4969                 i)
4970         code.putln(
4971                 "__Pyx_ErrRestore(%s, %s, %s);" %
4972                     Naming.exc_vars)
4973         code.putln(
4974                 "%s = %s;" % (
4975                     Naming.lineno_cname, Naming.exc_lineno_name))
4976         for var in Naming.exc_vars:
4977             code.putln(
4978                 "%s = 0;" %
4979                     var)
4980         code.put_goto(error_label)
4981         code.putln(
4982             "}")
4983
4984     def annotate(self, code):
4985         self.body.annotate(code)
4986         self.finally_clause.annotate(code)
4987
4988
4989 class GILStatNode(TryFinallyStatNode):
4990     #  'with gil' or 'with nogil' statement
4991     #
4992     #   state   string   'gil' or 'nogil'
4993
4994 #    child_attrs = []
4995     
4996     preserve_exception = 0
4997
4998     def __init__(self, pos, state, body):
4999         self.state = state
5000         TryFinallyStatNode.__init__(self, pos,
5001             body = body,
5002             finally_clause = GILExitNode(pos, state = state))
5003
5004     def analyse_expressions(self, env):
5005         env.use_utility_code(force_init_threads_utility_code)
5006         was_nogil = env.nogil
5007         env.nogil = 1
5008         TryFinallyStatNode.analyse_expressions(self, env)
5009         env.nogil = was_nogil
5010
5011     nogil_check = None
5012
5013     def generate_execution_code(self, code):
5014         code.mark_pos(self.pos)
5015         code.putln("{")
5016         if self.state == 'gil':
5017             code.putln("#ifdef WITH_THREAD")
5018             code.putln("PyGILState_STATE _save = PyGILState_Ensure();")
5019             code.putln("#endif")
5020         else:
5021             code.putln("#ifdef WITH_THREAD")
5022             code.putln("PyThreadState *_save;")
5023             code.putln("#endif")
5024             code.putln("Py_UNBLOCK_THREADS")
5025         TryFinallyStatNode.generate_execution_code(self, code)
5026         code.putln("}")
5027
5028
5029 class GILExitNode(StatNode):
5030     #  Used as the 'finally' block in a GILStatNode
5031     #
5032     #  state   string   'gil' or 'nogil'
5033
5034     child_attrs = []
5035
5036     def analyse_expressions(self, env):
5037         pass
5038
5039     def generate_execution_code(self, code):
5040         if self.state == 'gil':
5041             code.putln("#ifdef WITH_THREAD")
5042             code.putln("PyGILState_Release(_save);")
5043             code.putln("#endif")
5044         else:
5045             code.putln("Py_BLOCK_THREADS")
5046
5047
5048 class CImportStatNode(StatNode):
5049     #  cimport statement
5050     #
5051     #  module_name   string           Qualified name of module being imported
5052     #  as_name       string or None   Name specified in "as" clause, if any
5053
5054     child_attrs = []
5055     
5056     def analyse_declarations(self, env):
5057         if not env.is_module_scope:
5058             error(self.pos, "cimport only allowed at module level")
5059             return
5060         module_scope = env.find_module(self.module_name, self.pos)
5061         if "." in self.module_name:
5062             names = [EncodedString(name) for name in self.module_name.split(".")]
5063             top_name = names[0]
5064             top_module_scope = env.context.find_submodule(top_name)
5065             module_scope = top_module_scope
5066             for name in names[1:]:
5067                 submodule_scope = module_scope.find_submodule(name)
5068                 module_scope.declare_module(name, submodule_scope, self.pos)
5069                 module_scope = submodule_scope
5070             if self.as_name:
5071                 env.declare_module(self.as_name, module_scope, self.pos)
5072             else:
5073                 env.declare_module(top_name, top_module_scope, self.pos)
5074         else:
5075             name = self.as_name or self.module_name
5076             env.declare_module(name, module_scope, self.pos)
5077
5078     def analyse_expressions(self, env):
5079         pass
5080     
5081     def generate_execution_code(self, code):
5082         pass
5083     
5084
5085 class FromCImportStatNode(StatNode):
5086     #  from ... cimport statement
5087     #
5088     #  module_name     string                        Qualified name of module
5089     #  imported_names  [(pos, name, as_name, kind)]  Names to be imported
5090     
5091     child_attrs = []
5092
5093     def analyse_declarations(self, env):
5094         if not env.is_module_scope:
5095             error(self.pos, "cimport only allowed at module level")
5096             return
5097         module_scope = env.find_module(self.module_name, self.pos)
5098         env.add_imported_module(module_scope)
5099         for pos, name, as_name, kind in self.imported_names:
5100             if name == "*":
5101                 for local_name, entry in module_scope.entries.items():
5102                     env.add_imported_entry(local_name, entry, pos)
5103             else:
5104                 entry = module_scope.lookup(name)
5105                 if entry:
5106                     if kind and not self.declaration_matches(entry, kind):
5107                         entry.redeclared(pos)
5108                 else:
5109                     if kind == 'struct' or kind == 'union':
5110                         entry = module_scope.declare_struct_or_union(name,
5111                             kind = kind, scope = None, typedef_flag = 0, pos = pos)
5112                     elif kind == 'class':
5113                         entry = module_scope.declare_c_class(name, pos = pos,
5114                             module_name = self.module_name)
5115                     else:
5116                         submodule_scope = env.context.find_module(name, relative_to = module_scope, pos = self.pos)
5117                         if submodule_scope.parent_module is module_scope:
5118                             env.declare_module(as_name or name, submodule_scope, self.pos)
5119                         else:
5120                             error(pos, "Name '%s' not declared in module '%s'"
5121                                 % (name, self.module_name))
5122                         
5123                 if entry:
5124                     local_name = as_name or name
5125                     env.add_imported_entry(local_name, entry, pos)
5126     
5127     def declaration_matches(self, entry, kind):
5128         if not entry.is_type:
5129             return 0
5130         type = entry.type
5131         if kind == 'class':
5132             if not type.is_extension_type:
5133                 return 0
5134         else:
5135             if not type.is_struct_or_union:
5136                 return 0
5137             if kind != type.kind:
5138                 return 0
5139         return 1
5140
5141     def analyse_expressions(self, env):
5142         pass
5143     
5144     def generate_execution_code(self, code):
5145         pass
5146
5147
5148 class FromImportStatNode(StatNode):
5149     #  from ... import statement
5150     #
5151     #  module           ImportNode
5152     #  items            [(string, NameNode)]
5153     #  interned_items   [(string, NameNode, ExprNode)]
5154     #  item             PyTempNode            used internally
5155     #  import_star      boolean               used internally
5156
5157     child_attrs = ["module"]
5158     import_star = 0
5159     
5160     def analyse_declarations(self, env):
5161         for name, target in self.items:
5162             if name == "*":
5163                 if not env.is_module_scope:
5164                     error(self.pos, "import * only allowed at module level")
5165                     return
5166                 env.has_import_star = 1
5167                 self.import_star = 1
5168             else:
5169                 target.analyse_target_declaration(env)
5170     
5171     def analyse_expressions(self, env):
5172         import ExprNodes
5173         self.module.analyse_expressions(env)
5174         self.item = ExprNodes.RawCNameExprNode(self.pos, py_object_type)
5175         self.interned_items = []
5176         for name, target in self.items:
5177             if name == '*':
5178                 for _, entry in env.entries.items():
5179                     if not entry.is_type and entry.type.is_extension_type:
5180                         env.use_utility_code(ExprNodes.type_test_utility_code)
5181                         break
5182             else:
5183                 entry =  env.lookup(target.name)
5184                 # check whether or not entry is already cimported
5185                 if (entry.is_type and entry.type.name == name
5186                     and hasattr(entry.type, 'module_name')):
5187                     if entry.type.module_name == self.module.module_name.value:
5188                         # cimported with absolute name
5189                         continue
5190                     try:
5191                         # cimported with relative name
5192                         module = env.find_module(self.module.module_name.value,
5193                                                  pos=None)
5194                         if entry.type.module_name == module.qualified_name:
5195                             continue
5196                     except AttributeError:
5197                         pass 
5198                 target.analyse_target_expression(env, None)
5199                 if target.type is py_object_type:
5200                     coerced_item = None
5201                 else:
5202                     coerced_item = self.item.coerce_to(target.type, env)
5203                 self.interned_items.append((name, target, coerced_item))
5204     
5205     def generate_execution_code(self, code):
5206         self.module.generate_evaluation_code(code)
5207         if self.import_star:
5208             code.putln(
5209                 'if (%s(%s) < 0) %s;' % (
5210                     Naming.import_star,
5211                     self.module.py_result(),
5212                     code.error_goto(self.pos)))
5213         item_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
5214         self.item.set_cname(item_temp)
5215         for name, target, coerced_item in self.interned_items:
5216             cname = code.intern_identifier(name)
5217             code.putln(
5218                 '%s = PyObject_GetAttr(%s, %s); %s' % (
5219                     item_temp,
5220                     self.module.py_result(),
5221                     cname,
5222                     code.error_goto_if_null(item_temp, self.pos)))
5223             code.put_gotref(item_temp)
5224             if coerced_item is None:
5225                 target.generate_assignment_code(self.item, code)
5226             else:
5227                 coerced_item.allocate_temp_result(code)
5228                 coerced_item.generate_result_code(code)
5229                 target.generate_assignment_code(coerced_item, code)
5230             code.put_decref_clear(item_temp, py_object_type)
5231         code.funcstate.release_temp(item_temp)
5232         self.module.generate_disposal_code(code)
5233         self.module.free_temps(code)
5234
5235
5236
5237 #------------------------------------------------------------------------------------
5238 #
5239 #  Runtime support code
5240 #
5241 #------------------------------------------------------------------------------------
5242
5243 utility_function_predeclarations = \
5244 """
5245 /* inline attribute */
5246 #ifndef CYTHON_INLINE
5247   #if defined(__GNUC__)
5248     #define CYTHON_INLINE __inline__
5249   #elif defined(_MSC_VER)
5250     #define CYTHON_INLINE __inline
5251   #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
5252     #define CYTHON_INLINE inline
5253   #else
5254     #define CYTHON_INLINE 
5255   #endif
5256 #endif
5257
5258 /* unused attribute */
5259 #ifndef CYTHON_UNUSED
5260 # if defined(__GNUC__)
5261 #   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
5262 #     define CYTHON_UNUSED __attribute__ ((__unused__)) 
5263 #   else
5264 #     define CYTHON_UNUSED
5265 #   endif
5266 # elif defined(__ICC) || defined(__INTEL_COMPILER)
5267 #   define CYTHON_UNUSED __attribute__ ((__unused__)) 
5268 # else
5269 #   define CYTHON_UNUSED 
5270 # endif
5271 #endif
5272
5273 typedef struct {PyObject **p; char *s; const long n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/
5274
5275 """
5276
5277 if Options.gcc_branch_hints:
5278     branch_prediction_macros = \
5279     """
5280 #ifdef __GNUC__
5281 /* Test for GCC > 2.95 */
5282 #if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)) 
5283 #define likely(x)   __builtin_expect(!!(x), 1)
5284 #define unlikely(x) __builtin_expect(!!(x), 0)
5285 #else /* __GNUC__ > 2 ... */
5286 #define likely(x)   (x)
5287 #define unlikely(x) (x)
5288 #endif /* __GNUC__ > 2 ... */
5289 #else /* __GNUC__ */
5290 #define likely(x)   (x)
5291 #define unlikely(x) (x)
5292 #endif /* __GNUC__ */
5293     """
5294 else:
5295     branch_prediction_macros = \
5296     """
5297 #define likely(x)   (x)
5298 #define unlikely(x) (x)
5299     """
5300
5301 #get_name_predeclaration = \
5302 #"static PyObject *__Pyx_GetName(PyObject *dict, char *name); /*proto*/"
5303
5304 #get_name_interned_predeclaration = \
5305 #"static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/"
5306
5307 #------------------------------------------------------------------------------------
5308
5309 printing_utility_code = UtilityCode(
5310 proto = """
5311 static int __Pyx_Print(PyObject*, PyObject *, int); /*proto*/
5312 #if PY_MAJOR_VERSION >= 3
5313 static PyObject* %s = 0;
5314 static PyObject* %s = 0;
5315 #endif
5316 """ % (Naming.print_function, Naming.print_function_kwargs),
5317 cleanup = """
5318 #if PY_MAJOR_VERSION >= 3
5319 Py_CLEAR(%s);
5320 Py_CLEAR(%s);
5321 #endif
5322 """ % (Naming.print_function, Naming.print_function_kwargs),
5323 impl = r"""
5324 #if PY_MAJOR_VERSION < 3
5325 static PyObject *__Pyx_GetStdout(void) {
5326     PyObject *f = PySys_GetObject((char *)"stdout");
5327     if (!f) {
5328         PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
5329     }
5330     return f;
5331 }
5332
5333 static int __Pyx_Print(PyObject* f, PyObject *arg_tuple, int newline) {
5334     PyObject* v;
5335     int i;
5336
5337     if (!f) {
5338         if (!(f = __Pyx_GetStdout()))
5339             return -1;
5340     }
5341     for (i=0; i < PyTuple_GET_SIZE(arg_tuple); i++) {
5342         if (PyFile_SoftSpace(f, 1)) {
5343             if (PyFile_WriteString(" ", f) < 0)
5344                 return -1;
5345         }
5346         v = PyTuple_GET_ITEM(arg_tuple, i);
5347         if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0)
5348             return -1;
5349         if (PyString_Check(v)) {
5350             char *s = PyString_AsString(v);
5351             Py_ssize_t len = PyString_Size(v);
5352             if (len > 0 &&
5353                 isspace(Py_CHARMASK(s[len-1])) &&
5354                 s[len-1] != ' ')
5355                     PyFile_SoftSpace(f, 0);
5356         }
5357     }
5358     if (newline) {
5359         if (PyFile_WriteString("\n", f) < 0)
5360             return -1;
5361         PyFile_SoftSpace(f, 0);
5362     }
5363     return 0;
5364 }
5365
5366 #else /* Python 3 has a print function */
5367
5368 static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) {
5369     PyObject* kwargs = 0;
5370     PyObject* result = 0;
5371     PyObject* end_string;
5372     if (unlikely(!%(PRINT_FUNCTION)s)) {
5373         %(PRINT_FUNCTION)s = __Pyx_GetAttrString(%(BUILTINS)s, "print");
5374         if (!%(PRINT_FUNCTION)s)
5375             return -1;
5376     }
5377     if (stream) {
5378         kwargs = PyDict_New();
5379         if (unlikely(!kwargs))
5380             return -1;
5381         if (unlikely(PyDict_SetItemString(kwargs, "file", stream) < 0))
5382             goto bad;
5383         if (!newline) {
5384             end_string = PyUnicode_FromStringAndSize(" ", 1);
5385             if (unlikely(!end_string))
5386                 goto bad;
5387             if (PyDict_SetItemString(kwargs, "end", end_string) < 0) {
5388                 Py_DECREF(end_string);
5389                 goto bad;
5390             }
5391             Py_DECREF(end_string);
5392         }
5393     } else if (!newline) {
5394         if (unlikely(!%(PRINT_KWARGS)s)) {
5395             %(PRINT_KWARGS)s = PyDict_New();
5396             if (unlikely(!%(PRINT_KWARGS)s))
5397                 return -1;
5398             end_string = PyUnicode_FromStringAndSize(" ", 1);
5399             if (unlikely(!end_string))
5400                 return -1;
5401             if (PyDict_SetItemString(%(PRINT_KWARGS)s, "end", end_string) < 0) {
5402                 Py_DECREF(end_string);
5403                 return -1;
5404             }
5405             Py_DECREF(end_string);
5406         }
5407         kwargs = %(PRINT_KWARGS)s;
5408     }
5409     result = PyObject_Call(%(PRINT_FUNCTION)s, arg_tuple, kwargs);
5410     if (unlikely(kwargs) && (kwargs != %(PRINT_KWARGS)s))
5411         Py_DECREF(kwargs);
5412     if (!result)
5413         return -1;
5414     Py_DECREF(result);
5415     return 0;
5416 bad:
5417     if (kwargs != %(PRINT_KWARGS)s)
5418         Py_XDECREF(kwargs);
5419     return -1;
5420 }
5421
5422 #endif
5423 """ % {'BUILTINS'       : Naming.builtins_cname,
5424        'PRINT_FUNCTION' : Naming.print_function,
5425        'PRINT_KWARGS'   : Naming.print_function_kwargs}
5426 )
5427
5428
5429 printing_one_utility_code = UtilityCode(
5430 proto = """
5431 static int __Pyx_PrintOne(PyObject* stream, PyObject *o); /*proto*/
5432 """,
5433 impl = r"""
5434 #if PY_MAJOR_VERSION < 3
5435
5436 static int __Pyx_PrintOne(PyObject* f, PyObject *o) {
5437     if (!f) {
5438         if (!(f = __Pyx_GetStdout()))
5439             return -1;
5440     }
5441     if (PyFile_SoftSpace(f, 0)) {
5442         if (PyFile_WriteString(" ", f) < 0)
5443             return -1;
5444     }
5445     if (PyFile_WriteObject(o, f, Py_PRINT_RAW) < 0)
5446         return -1;
5447     if (PyFile_WriteString("\n", f) < 0)
5448         return -1;
5449     return 0;
5450     /* the line below is just to avoid compiler
5451      * compiler warnings about unused functions */
5452     return __Pyx_Print(f, NULL, 0);
5453 }
5454
5455 #else /* Python 3 has a print function */
5456
5457 static int __Pyx_PrintOne(PyObject* stream, PyObject *o) {
5458     int res;
5459     PyObject* arg_tuple = PyTuple_New(1);
5460     if (unlikely(!arg_tuple))
5461         return -1;
5462     Py_INCREF(o);
5463     PyTuple_SET_ITEM(arg_tuple, 0, o);
5464     res = __Pyx_Print(stream, arg_tuple, 1);
5465     Py_DECREF(arg_tuple);
5466     return res;
5467 }
5468
5469 #endif
5470 """,
5471 requires=[printing_utility_code])
5472
5473
5474
5475 #------------------------------------------------------------------------------------
5476
5477 # Exception raising code
5478 #
5479 # Exceptions are raised by __Pyx_Raise() and stored as plain
5480 # type/value/tb in PyThreadState->curexc_*.  When being caught by an
5481 # 'except' statement, curexc_* is moved over to exc_* by
5482 # __Pyx_GetException()
5483
5484 restore_exception_utility_code = UtilityCode(
5485 proto = """
5486 static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
5487 static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
5488 """,
5489 impl = """
5490 static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) {
5491     PyObject *tmp_type, *tmp_value, *tmp_tb;
5492     PyThreadState *tstate = PyThreadState_GET();
5493
5494     tmp_type = tstate->curexc_type;
5495     tmp_value = tstate->curexc_value;
5496     tmp_tb = tstate->curexc_traceback;
5497     tstate->curexc_type = type;
5498     tstate->curexc_value = value;
5499     tstate->curexc_traceback = tb;
5500     Py_XDECREF(tmp_type);
5501     Py_XDECREF(tmp_value);
5502     Py_XDECREF(tmp_tb);
5503 }
5504
5505 static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) {
5506     PyThreadState *tstate = PyThreadState_GET();
5507     *type = tstate->curexc_type;
5508     *value = tstate->curexc_value;
5509     *tb = tstate->curexc_traceback;
5510
5511     tstate->curexc_type = 0;
5512     tstate->curexc_value = 0;
5513     tstate->curexc_traceback = 0;
5514 }
5515
5516 """)
5517
5518 # The following function is based on do_raise() from ceval.c. There
5519 # are separate versions for Python2 and Python3 as exception handling
5520 # has changed quite a lot between the two versions.
5521
5522 raise_utility_code = UtilityCode(
5523 proto = """
5524 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
5525 """,
5526 impl = """
5527 #if PY_MAJOR_VERSION < 3
5528 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) {
5529     Py_XINCREF(type);
5530     Py_XINCREF(value);
5531     Py_XINCREF(tb);
5532     /* First, check the traceback argument, replacing None with NULL. */
5533     if (tb == Py_None) {
5534         Py_DECREF(tb);
5535         tb = 0;
5536     }
5537     else if (tb != NULL && !PyTraceBack_Check(tb)) {
5538         PyErr_SetString(PyExc_TypeError,
5539             "raise: arg 3 must be a traceback or None");
5540         goto raise_error;
5541     }
5542     /* Next, replace a missing value with None */
5543     if (value == NULL) {
5544         value = Py_None;
5545         Py_INCREF(value);
5546     }
5547     #if PY_VERSION_HEX < 0x02050000
5548     if (!PyClass_Check(type))
5549     #else
5550     if (!PyType_Check(type))
5551     #endif
5552     {
5553         /* Raising an instance.  The value should be a dummy. */
5554         if (value != Py_None) {
5555             PyErr_SetString(PyExc_TypeError,
5556                 "instance exception may not have a separate value");
5557             goto raise_error;
5558         }
5559         /* Normalize to raise <class>, <instance> */
5560         Py_DECREF(value);
5561         value = type;
5562         #if PY_VERSION_HEX < 0x02050000
5563             if (PyInstance_Check(type)) {
5564                 type = (PyObject*) ((PyInstanceObject*)type)->in_class;
5565                 Py_INCREF(type);
5566             }
5567             else {
5568                 type = 0;
5569                 PyErr_SetString(PyExc_TypeError,
5570                     "raise: exception must be an old-style class or instance");
5571                 goto raise_error;
5572             }
5573         #else
5574             type = (PyObject*) Py_TYPE(type);
5575             Py_INCREF(type);
5576             if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
5577                 PyErr_SetString(PyExc_TypeError,
5578                     "raise: exception class must be a subclass of BaseException");
5579                 goto raise_error;
5580             }
5581         #endif
5582     }
5583
5584     __Pyx_ErrRestore(type, value, tb);
5585     return;
5586 raise_error:
5587     Py_XDECREF(value);
5588     Py_XDECREF(type);
5589     Py_XDECREF(tb);
5590     return;
5591 }
5592
5593 #else /* Python 3+ */
5594
5595 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb) {
5596     if (tb == Py_None) {
5597         tb = 0;
5598     } else if (tb && !PyTraceBack_Check(tb)) {
5599         PyErr_SetString(PyExc_TypeError,
5600             "raise: arg 3 must be a traceback or None");
5601         goto bad;
5602     }
5603     if (value == Py_None)
5604         value = 0;
5605
5606     if (PyExceptionInstance_Check(type)) {
5607         if (value) {
5608             PyErr_SetString(PyExc_TypeError,
5609                 "instance exception may not have a separate value");
5610             goto bad;
5611         }
5612         value = type;
5613         type = (PyObject*) Py_TYPE(value);
5614     } else if (!PyExceptionClass_Check(type)) {
5615         PyErr_SetString(PyExc_TypeError,
5616             "raise: exception class must be a subclass of BaseException");
5617         goto bad;
5618     }
5619
5620     PyErr_SetObject(type, value);
5621
5622     if (tb) {
5623         PyThreadState *tstate = PyThreadState_GET();
5624         PyObject* tmp_tb = tstate->curexc_traceback;
5625         if (tb != tmp_tb) {
5626             Py_INCREF(tb);
5627             tstate->curexc_traceback = tb;
5628             Py_XDECREF(tmp_tb);
5629         }
5630     }
5631
5632 bad:
5633     return;
5634 }
5635 #endif
5636 """,
5637 requires=[restore_exception_utility_code])
5638
5639 #------------------------------------------------------------------------------------
5640
5641 get_exception_utility_code = UtilityCode(
5642 proto = """
5643 static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
5644 """,
5645 impl = """
5646 static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) {
5647     PyObject *local_type, *local_value, *local_tb;
5648     PyObject *tmp_type, *tmp_value, *tmp_tb;
5649     PyThreadState *tstate = PyThreadState_GET();
5650     local_type = tstate->curexc_type;
5651     local_value = tstate->curexc_value;
5652     local_tb = tstate->curexc_traceback;
5653     tstate->curexc_type = 0;
5654     tstate->curexc_value = 0;
5655     tstate->curexc_traceback = 0;
5656     PyErr_NormalizeException(&local_type, &local_value, &local_tb);
5657     if (unlikely(tstate->curexc_type))
5658         goto bad;
5659     #if PY_MAJOR_VERSION >= 3
5660     if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0))
5661         goto bad;
5662     #endif
5663     *type = local_type;
5664     *value = local_value;
5665     *tb = local_tb;
5666     Py_INCREF(local_type);
5667     Py_INCREF(local_value);
5668     Py_INCREF(local_tb);
5669     tmp_type = tstate->exc_type;
5670     tmp_value = tstate->exc_value;
5671     tmp_tb = tstate->exc_traceback;
5672     tstate->exc_type = local_type;
5673     tstate->exc_value = local_value;
5674     tstate->exc_traceback = local_tb;
5675     /* Make sure tstate is in a consistent state when we XDECREF
5676        these objects (XDECREF may run arbitrary code). */
5677     Py_XDECREF(tmp_type);
5678     Py_XDECREF(tmp_value);
5679     Py_XDECREF(tmp_tb);
5680     return 0;
5681 bad:
5682     *type = 0;
5683     *value = 0;
5684     *tb = 0;
5685     Py_XDECREF(local_type);
5686     Py_XDECREF(local_value);
5687     Py_XDECREF(local_tb);
5688     return -1;
5689 }
5690
5691 """)
5692
5693 #------------------------------------------------------------------------------------
5694
5695 get_exception_tuple_utility_code = UtilityCode(proto="""
5696 static PyObject *__Pyx_GetExceptionTuple(void); /*proto*/
5697 """,
5698 # I doubt that calling __Pyx_GetException() here is correct as it moves
5699 # the exception from tstate->curexc_* to tstate->exc_*, which prevents
5700 # exception handlers later on from receiving it.
5701 impl = """
5702 static PyObject *__Pyx_GetExceptionTuple(void) {
5703     PyObject *type = NULL, *value = NULL, *tb = NULL;
5704     if (__Pyx_GetException(&type, &value, &tb) == 0) {
5705         PyObject* exc_info = PyTuple_New(3);
5706         if (exc_info) {
5707             Py_INCREF(type);
5708             Py_INCREF(value);
5709             Py_INCREF(tb);
5710             PyTuple_SET_ITEM(exc_info, 0, type);
5711             PyTuple_SET_ITEM(exc_info, 1, value);
5712             PyTuple_SET_ITEM(exc_info, 2, tb);
5713             return exc_info;
5714         }
5715     }
5716     return NULL;
5717 }
5718 """,
5719 requires=[get_exception_utility_code])
5720
5721 #------------------------------------------------------------------------------------
5722
5723 reset_exception_utility_code = UtilityCode(
5724 proto = """
5725 static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
5726 static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
5727 """,
5728 impl = """
5729 static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) {
5730     PyThreadState *tstate = PyThreadState_GET();
5731     *type = tstate->exc_type;
5732     *value = tstate->exc_value;
5733     *tb = tstate->exc_traceback;
5734     Py_XINCREF(*type);
5735     Py_XINCREF(*value);
5736     Py_XINCREF(*tb);
5737 }
5738
5739 static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) {
5740     PyObject *tmp_type, *tmp_value, *tmp_tb;
5741     PyThreadState *tstate = PyThreadState_GET();
5742     tmp_type = tstate->exc_type;
5743     tmp_value = tstate->exc_value;
5744     tmp_tb = tstate->exc_traceback;
5745     tstate->exc_type = type;
5746     tstate->exc_value = value;
5747     tstate->exc_traceback = tb;
5748     Py_XDECREF(tmp_type);
5749     Py_XDECREF(tmp_value);
5750     Py_XDECREF(tmp_tb);
5751 }
5752 """)
5753
5754 #------------------------------------------------------------------------------------
5755
5756 arg_type_test_utility_code = UtilityCode(
5757 proto = """
5758 static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
5759     const char *name, int exact); /*proto*/
5760 """,
5761 impl = """
5762 static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
5763     const char *name, int exact)
5764 {
5765     if (!type) {
5766         PyErr_Format(PyExc_SystemError, "Missing type object");
5767         return 0;
5768     }
5769     if (none_allowed && obj == Py_None) return 1;
5770     else if (exact) {
5771         if (Py_TYPE(obj) == type) return 1;
5772     }
5773     else {
5774         if (PyObject_TypeCheck(obj, type)) return 1;
5775     }
5776     PyErr_Format(PyExc_TypeError,
5777         "Argument '%s' has incorrect type (expected %s, got %s)",
5778         name, type->tp_name, Py_TYPE(obj)->tp_name);
5779     return 0;
5780 }
5781 """)
5782
5783 #------------------------------------------------------------------------------------
5784 #
5785 #  __Pyx_RaiseArgtupleInvalid raises the correct exception when too
5786 #  many or too few positional arguments were found.  This handles
5787 #  Py_ssize_t formatting correctly.
5788
5789 raise_argtuple_invalid_utility_code = UtilityCode(
5790 proto = """
5791 static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
5792     Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/
5793 """,
5794 impl = """
5795 static void __Pyx_RaiseArgtupleInvalid(
5796     const char* func_name,
5797     int exact,
5798     Py_ssize_t num_min,
5799     Py_ssize_t num_max,
5800     Py_ssize_t num_found)
5801 {
5802     Py_ssize_t num_expected;
5803     const char *number, *more_or_less;
5804
5805     if (num_found < num_min) {
5806         num_expected = num_min;
5807         more_or_less = "at least";
5808     } else {
5809         num_expected = num_max;
5810         more_or_less = "at most";
5811     }
5812     if (exact) {
5813         more_or_less = "exactly";
5814     }
5815     number = (num_expected == 1) ? "" : "s";
5816     PyErr_Format(PyExc_TypeError,
5817         #if PY_VERSION_HEX < 0x02050000
5818             "%s() takes %s %d positional argument%s (%d given)",
5819         #else
5820             "%s() takes %s %zd positional argument%s (%zd given)",
5821         #endif
5822         func_name, more_or_less, num_expected, number, num_found);
5823 }
5824 """)
5825
5826 raise_keyword_required_utility_code = UtilityCode(
5827 proto = """
5828 static CYTHON_INLINE void __Pyx_RaiseKeywordRequired(const char* func_name, PyObject* kw_name); /*proto*/
5829 """,
5830 impl = """
5831 static CYTHON_INLINE void __Pyx_RaiseKeywordRequired(
5832     const char* func_name,
5833     PyObject* kw_name)
5834 {
5835     PyErr_Format(PyExc_TypeError,
5836         #if PY_MAJOR_VERSION >= 3
5837         "%s() needs keyword-only argument %U", func_name, kw_name);
5838         #else
5839         "%s() needs keyword-only argument %s", func_name,
5840         PyString_AS_STRING(kw_name));
5841         #endif
5842 }
5843 """)
5844
5845 raise_double_keywords_utility_code = UtilityCode(
5846 proto = """
5847 static void __Pyx_RaiseDoubleKeywordsError(
5848     const char* func_name, PyObject* kw_name); /*proto*/
5849 """,
5850 impl = """
5851 static void __Pyx_RaiseDoubleKeywordsError(
5852     const char* func_name,
5853     PyObject* kw_name)
5854 {
5855     PyErr_Format(PyExc_TypeError,
5856         #if PY_MAJOR_VERSION >= 3
5857         "%s() got multiple values for keyword argument '%U'", func_name, kw_name);
5858         #else
5859         "%s() got multiple values for keyword argument '%s'", func_name,
5860         PyString_AS_STRING(kw_name));
5861         #endif
5862 }
5863 """)
5864
5865 #------------------------------------------------------------------------------------
5866 #
5867 #  __Pyx_CheckKeywordStrings raises an error if non-string keywords
5868 #  were passed to a function, or if any keywords were passed to a
5869 #  function that does not accept them.
5870
5871 keyword_string_check_utility_code = UtilityCode(
5872 proto = """
5873 static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict,
5874     const char* function_name, int kw_allowed); /*proto*/
5875 """,
5876 impl = """
5877 static CYTHON_INLINE int __Pyx_CheckKeywordStrings(
5878     PyObject *kwdict,
5879     const char* function_name,
5880     int kw_allowed)
5881 {
5882     PyObject* key = 0;
5883     Py_ssize_t pos = 0;
5884     while (PyDict_Next(kwdict, &pos, &key, 0)) {
5885         #if PY_MAJOR_VERSION < 3
5886         if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key)))
5887         #else
5888         if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key)))
5889         #endif
5890             goto invalid_keyword_type;
5891     }
5892     if ((!kw_allowed) && unlikely(key))
5893         goto invalid_keyword;
5894     return 1;
5895 invalid_keyword_type:
5896     PyErr_Format(PyExc_TypeError,
5897         "%s() keywords must be strings", function_name);
5898     return 0;
5899 invalid_keyword:
5900     PyErr_Format(PyExc_TypeError,
5901     #if PY_MAJOR_VERSION < 3
5902         "%s() got an unexpected keyword argument '%s'",
5903         function_name, PyString_AsString(key));
5904     #else
5905         "%s() got an unexpected keyword argument '%U'",
5906         function_name, key);
5907     #endif
5908     return 0;
5909 }
5910 """)
5911
5912 #------------------------------------------------------------------------------------
5913 #
5914 #  __Pyx_ParseOptionalKeywords copies the optional/unknown keyword
5915 #  arguments from the kwds dict into kwds2.  If kwds2 is NULL, unknown
5916 #  keywords will raise an invalid keyword error.
5917 #
5918 #  Three kinds of errors are checked: 1) non-string keywords, 2)
5919 #  unexpected keywords and 3) overlap with positional arguments.
5920 #
5921 #  If num_posargs is greater 0, it denotes the number of positional
5922 #  arguments that were passed and that must therefore not appear
5923 #  amongst the keywords as well.
5924 #
5925 #  This method does not check for required keyword arguments.
5926 #
5927
5928 parse_keywords_utility_code = UtilityCode(
5929 proto = """
5930 static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \
5931     PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \
5932     const char* function_name); /*proto*/
5933 """,
5934 impl = """
5935 static int __Pyx_ParseOptionalKeywords(
5936     PyObject *kwds,
5937     PyObject **argnames[],
5938     PyObject *kwds2,
5939     PyObject *values[],
5940     Py_ssize_t num_pos_args,
5941     const char* function_name)
5942 {
5943     PyObject *key = 0, *value = 0;
5944     Py_ssize_t pos = 0;
5945     PyObject*** name;
5946     PyObject*** first_kw_arg = argnames + num_pos_args;
5947
5948     while (PyDict_Next(kwds, &pos, &key, &value)) {
5949         name = first_kw_arg;
5950         while (*name && (**name != key)) name++;
5951         if (*name) {
5952             values[name-argnames] = value;
5953         } else {
5954             #if PY_MAJOR_VERSION < 3
5955             if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) {
5956             #else
5957             if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) {
5958             #endif
5959                 goto invalid_keyword_type;
5960             } else {
5961                 for (name = first_kw_arg; *name; name++) {
5962                     #if PY_MAJOR_VERSION >= 3
5963                     if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) &&
5964                         PyUnicode_Compare(**name, key) == 0) break;
5965                     #else
5966                     if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) &&
5967                         _PyString_Eq(**name, key)) break;
5968                     #endif
5969                 }
5970                 if (*name) {
5971                     values[name-argnames] = value;
5972                 } else {
5973                     /* unexpected keyword found */
5974                     for (name=argnames; name != first_kw_arg; name++) {
5975                         if (**name == key) goto arg_passed_twice;
5976                         #if PY_MAJOR_VERSION >= 3
5977                         if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) &&
5978                             PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice;
5979                         #else
5980                         if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) &&
5981                             _PyString_Eq(**name, key)) goto arg_passed_twice;
5982                         #endif
5983                     }
5984                     if (kwds2) {
5985                         if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
5986                     } else {
5987                         goto invalid_keyword;
5988                     }
5989                 }
5990             }
5991         }
5992     }
5993     return 0;
5994 arg_passed_twice:
5995     __Pyx_RaiseDoubleKeywordsError(function_name, **name);
5996     goto bad;
5997 invalid_keyword_type:
5998     PyErr_Format(PyExc_TypeError,
5999         "%s() keywords must be strings", function_name);
6000     goto bad;
6001 invalid_keyword:
6002     PyErr_Format(PyExc_TypeError,
6003     #if PY_MAJOR_VERSION < 3
6004         "%s() got an unexpected keyword argument '%s'",
6005         function_name, PyString_AsString(key));
6006     #else
6007         "%s() got an unexpected keyword argument '%U'",
6008         function_name, key);
6009     #endif
6010 bad:
6011     return -1;
6012 }
6013 """)
6014
6015 #------------------------------------------------------------------------------------
6016
6017 traceback_utility_code = UtilityCode(
6018 proto = """
6019 static void __Pyx_AddTraceback(const char *funcname); /*proto*/
6020 """,
6021 impl = """
6022 #include "compile.h"
6023 #include "frameobject.h"
6024 #include "traceback.h"
6025
6026 static void __Pyx_AddTraceback(const char *funcname) {
6027     PyObject *py_srcfile = 0;
6028     PyObject *py_funcname = 0;
6029     PyObject *py_globals = 0;
6030     PyCodeObject *py_code = 0;
6031     PyFrameObject *py_frame = 0;
6032
6033     #if PY_MAJOR_VERSION < 3
6034     py_srcfile = PyString_FromString(%(FILENAME)s);
6035     #else
6036     py_srcfile = PyUnicode_FromString(%(FILENAME)s);
6037     #endif
6038     if (!py_srcfile) goto bad;
6039     if (%(CLINENO)s) {
6040         #if PY_MAJOR_VERSION < 3
6041         py_funcname = PyString_FromFormat( "%%s (%%s:%%d)", funcname, %(CFILENAME)s, %(CLINENO)s);
6042         #else
6043         py_funcname = PyUnicode_FromFormat( "%%s (%%s:%%d)", funcname, %(CFILENAME)s, %(CLINENO)s);
6044         #endif
6045     }
6046     else {
6047         #if PY_MAJOR_VERSION < 3
6048         py_funcname = PyString_FromString(funcname);
6049         #else
6050         py_funcname = PyUnicode_FromString(funcname);
6051         #endif
6052     }
6053     if (!py_funcname) goto bad;
6054     py_globals = PyModule_GetDict(%(GLOBALS)s);
6055     if (!py_globals) goto bad;
6056     py_code = PyCode_New(
6057         0,            /*int argcount,*/
6058         #if PY_MAJOR_VERSION >= 3
6059         0,            /*int kwonlyargcount,*/
6060         #endif
6061         0,            /*int nlocals,*/
6062         0,            /*int stacksize,*/
6063         0,            /*int flags,*/
6064         %(EMPTY_BYTES)s, /*PyObject *code,*/
6065         %(EMPTY_TUPLE)s,  /*PyObject *consts,*/
6066         %(EMPTY_TUPLE)s,  /*PyObject *names,*/
6067         %(EMPTY_TUPLE)s,  /*PyObject *varnames,*/
6068         %(EMPTY_TUPLE)s,  /*PyObject *freevars,*/
6069         %(EMPTY_TUPLE)s,  /*PyObject *cellvars,*/
6070         py_srcfile,   /*PyObject *filename,*/
6071         py_funcname,  /*PyObject *name,*/
6072         %(LINENO)s,   /*int firstlineno,*/
6073         %(EMPTY_BYTES)s  /*PyObject *lnotab*/
6074     );
6075     if (!py_code) goto bad;
6076     py_frame = PyFrame_New(
6077         PyThreadState_GET(), /*PyThreadState *tstate,*/
6078         py_code,             /*PyCodeObject *code,*/
6079         py_globals,          /*PyObject *globals,*/
6080         0                    /*PyObject *locals*/
6081     );
6082     if (!py_frame) goto bad;
6083     py_frame->f_lineno = %(LINENO)s;
6084     PyTraceBack_Here(py_frame);
6085 bad:
6086     Py_XDECREF(py_srcfile);
6087     Py_XDECREF(py_funcname);
6088     Py_XDECREF(py_code);
6089     Py_XDECREF(py_frame);
6090 }
6091 """ % {
6092     'FILENAME': Naming.filename_cname,
6093     'LINENO':  Naming.lineno_cname,
6094     'CFILENAME': Naming.cfilenm_cname,
6095     'CLINENO':  Naming.clineno_cname,
6096     'GLOBALS': Naming.module_cname,
6097     'EMPTY_TUPLE' : Naming.empty_tuple,
6098     'EMPTY_BYTES' : Naming.empty_bytes,
6099 })
6100
6101 #------------------------------------------------------------------------------------
6102
6103 unraisable_exception_utility_code = UtilityCode(
6104 proto = """
6105 static void __Pyx_WriteUnraisable(const char *name); /*proto*/
6106 """,
6107 impl = """
6108 static void __Pyx_WriteUnraisable(const char *name) {
6109     PyObject *old_exc, *old_val, *old_tb;
6110     PyObject *ctx;
6111     __Pyx_ErrFetch(&old_exc, &old_val, &old_tb);
6112     #if PY_MAJOR_VERSION < 3
6113     ctx = PyString_FromString(name);
6114     #else
6115     ctx = PyUnicode_FromString(name);
6116     #endif
6117     __Pyx_ErrRestore(old_exc, old_val, old_tb);
6118     if (!ctx) {
6119         PyErr_WriteUnraisable(Py_None);
6120     } else {
6121         PyErr_WriteUnraisable(ctx);
6122         Py_DECREF(ctx);
6123     }
6124 }
6125 """,
6126 requires=[restore_exception_utility_code])
6127
6128 #------------------------------------------------------------------------------------
6129
6130 set_vtable_utility_code = UtilityCode(
6131 proto = """
6132 static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/
6133 """,
6134 impl = """
6135 static int __Pyx_SetVtable(PyObject *dict, void *vtable) {
6136 #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0)
6137     PyObject *ob = PyCapsule_New(vtable, 0, 0);
6138 #else
6139     PyObject *ob = PyCObject_FromVoidPtr(vtable, 0);
6140 #endif
6141     if (!ob)
6142         goto bad;
6143     if (PyDict_SetItemString(dict, "__pyx_vtable__", ob) < 0)
6144         goto bad;
6145     Py_DECREF(ob);
6146     return 0;
6147 bad:
6148     Py_XDECREF(ob);
6149     return -1;
6150 }
6151 """)
6152
6153 #------------------------------------------------------------------------------------
6154
6155 get_vtable_utility_code = UtilityCode(
6156 proto = """
6157 static int __Pyx_GetVtable(PyObject *dict, void *vtabptr); /*proto*/
6158 """,
6159 impl = r"""
6160 static int __Pyx_GetVtable(PyObject *dict, void *vtabptr) {
6161     PyObject *ob = PyMapping_GetItemString(dict, (char *)"__pyx_vtable__");
6162     if (!ob)
6163         goto bad;
6164 #if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0)
6165     *(void **)vtabptr = PyCapsule_GetPointer(ob, 0);
6166 #else
6167     *(void **)vtabptr = PyCObject_AsVoidPtr(ob);
6168 #endif
6169     if (!*(void **)vtabptr)
6170         goto bad;
6171     Py_DECREF(ob);
6172     return 0;
6173 bad:
6174     Py_XDECREF(ob);
6175     return -1;
6176 }
6177 """)
6178
6179 #------------------------------------------------------------------------------------
6180
6181 init_string_tab_utility_code = UtilityCode(
6182 proto = """
6183 static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/
6184 """,
6185 impl = """
6186 static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
6187     while (t->p) {
6188         #if PY_MAJOR_VERSION < 3
6189         if (t->is_unicode) {
6190             *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
6191         } else if (t->intern) {
6192             *t->p = PyString_InternFromString(t->s);
6193         } else {
6194             *t->p = PyString_FromStringAndSize(t->s, t->n - 1);
6195         }
6196         #else  /* Python 3+ has unicode identifiers */
6197         if (t->is_unicode | t->is_str) {
6198             if (t->intern) {
6199                 *t->p = PyUnicode_InternFromString(t->s);
6200             } else if (t->encoding) {
6201                 *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
6202             } else {
6203                 *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
6204             }
6205         } else {
6206             *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
6207         }
6208         #endif
6209         if (!*t->p)
6210             return -1;
6211         ++t;
6212     }
6213     return 0;
6214 }
6215 """)
6216
6217 #------------------------------------------------------------------------------------
6218
6219 force_init_threads_utility_code = UtilityCode(
6220 proto="""
6221 #ifndef __PYX_FORCE_INIT_THREADS
6222   #if PY_VERSION_HEX < 0x02040200
6223     #define __PYX_FORCE_INIT_THREADS 1
6224   #else
6225     #define __PYX_FORCE_INIT_THREADS 0
6226   #endif
6227 #endif
6228 """)
6229
6230 #------------------------------------------------------------------------------------
6231
6232 # Note that cPython ignores PyTrace_EXCEPTION, 
6233 # but maybe some other profilers don't. 
6234
6235 profile_utility_code = UtilityCode(proto="""
6236 #ifndef CYTHON_PROFILE
6237   #define CYTHON_PROFILE 1
6238 #endif
6239
6240 #ifndef CYTHON_PROFILE_REUSE_FRAME
6241   #define CYTHON_PROFILE_REUSE_FRAME 0
6242 #endif
6243
6244 #if CYTHON_PROFILE
6245
6246   #include "compile.h"
6247   #include "frameobject.h"
6248   #include "traceback.h"
6249
6250   #if CYTHON_PROFILE_REUSE_FRAME
6251     #define CYTHON_FRAME_MODIFIER static
6252     #define CYTHON_FRAME_DEL
6253   #else
6254     #define CYTHON_FRAME_MODIFIER
6255     #define CYTHON_FRAME_DEL Py_DECREF(%(FRAME)s)
6256   #endif
6257
6258   #define __Pyx_TraceDeclarations                                  \\
6259   static PyCodeObject *%(FRAME_CODE)s = NULL;                      \\
6260   CYTHON_FRAME_MODIFIER PyFrameObject *%(FRAME)s = NULL;           \\
6261   int __Pyx_use_tracing = 0;                                                         
6262
6263   #define __Pyx_TraceCall(funcname, srcfile, firstlineno)                            \\
6264   if (unlikely(PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc)) {      \\
6265       __Pyx_use_tracing = __Pyx_TraceSetupAndCall(&%(FRAME_CODE)s, &%(FRAME)s, funcname, srcfile, firstlineno);  \\
6266   }
6267
6268   #define __Pyx_TraceException()                                                           \\
6269   if (unlikely(__Pyx_use_tracing( && PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc) {  \\
6270       PyObject *exc_info = __Pyx_GetExceptionTuple();                                      \\
6271       if (exc_info) {                                                                      \\
6272           PyThreadState_GET()->c_profilefunc(                                              \\
6273               PyThreadState_GET()->c_profileobj, %(FRAME)s, PyTrace_EXCEPTION, exc_info);  \\
6274           Py_DECREF(exc_info);                                                             \\
6275       }                                                                                    \\
6276   }
6277
6278   #define __Pyx_TraceReturn(result)                                                  \\
6279   if (unlikely(__Pyx_use_tracing) && PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc) {  \\
6280       PyThreadState_GET()->c_profilefunc(                                            \\
6281           PyThreadState_GET()->c_profileobj, %(FRAME)s, PyTrace_RETURN, (PyObject*)result);     \\
6282       CYTHON_FRAME_DEL;                                                               \\
6283   }
6284
6285   static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno); /*proto*/
6286   static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, const char *funcname, const char *srcfile, int firstlineno); /*proto*/
6287
6288 #else
6289
6290   #define __Pyx_TraceDeclarations
6291   #define __Pyx_TraceCall(funcname, srcfile, firstlineno) 
6292   #define __Pyx_TraceException() 
6293   #define __Pyx_TraceReturn(result) 
6294
6295 #endif /* CYTHON_PROFILE */
6296 """ 
6297 % {
6298     "FRAME": Naming.frame_cname,
6299     "FRAME_CODE": Naming.frame_code_cname,
6300 },
6301 impl = """
6302
6303 #if CYTHON_PROFILE
6304
6305 static int __Pyx_TraceSetupAndCall(PyCodeObject** code,
6306                                    PyFrameObject** frame,
6307                                    const char *funcname,
6308                                    const char *srcfile,
6309                                    int firstlineno) {
6310     if (*frame == NULL || !CYTHON_PROFILE_REUSE_FRAME) {
6311         if (*code == NULL) {
6312             *code = __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno);
6313             if (*code == NULL) return 0;
6314         }
6315         *frame = PyFrame_New(
6316             PyThreadState_GET(),            /*PyThreadState *tstate*/
6317             *code,                          /*PyCodeObject *code*/
6318             PyModule_GetDict(%(MODULE)s),      /*PyObject *globals*/
6319             0                               /*PyObject *locals*/
6320         );
6321         if (*frame == NULL) return 0;
6322     }
6323     else {
6324         (*frame)->f_tstate = PyThreadState_GET();
6325     }
6326     return PyThreadState_GET()->c_profilefunc(PyThreadState_GET()->c_profileobj, *frame, PyTrace_CALL, NULL) == 0;
6327 }
6328
6329 static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno) {
6330     PyObject *py_srcfile = 0;
6331     PyObject *py_funcname = 0;
6332     PyCodeObject *py_code = 0;
6333
6334     #if PY_MAJOR_VERSION < 3
6335     py_funcname = PyString_FromString(funcname);
6336     py_srcfile = PyString_FromString(srcfile);
6337     #else
6338     py_funcname = PyUnicode_FromString(funcname);
6339     py_srcfile = PyUnicode_FromString(srcfile);
6340     #endif
6341     if (!py_funcname | !py_srcfile) goto bad;
6342
6343     py_code = PyCode_New(
6344         0,                /*int argcount,*/
6345         #if PY_MAJOR_VERSION >= 3
6346         0,                /*int kwonlyargcount,*/
6347         #endif
6348         0,                /*int nlocals,*/
6349         0,                /*int stacksize,*/
6350         0,                /*int flags,*/
6351         %(EMPTY_BYTES)s,  /*PyObject *code,*/
6352         %(EMPTY_TUPLE)s,  /*PyObject *consts,*/
6353         %(EMPTY_TUPLE)s,  /*PyObject *names,*/
6354         %(EMPTY_TUPLE)s,  /*PyObject *varnames,*/
6355         %(EMPTY_TUPLE)s,  /*PyObject *freevars,*/
6356         %(EMPTY_TUPLE)s,  /*PyObject *cellvars,*/
6357         py_srcfile,       /*PyObject *filename,*/
6358         py_funcname,      /*PyObject *name,*/
6359         firstlineno,      /*int firstlineno,*/
6360         %(EMPTY_BYTES)s   /*PyObject *lnotab*/
6361     );
6362
6363 bad: 
6364     Py_XDECREF(py_srcfile);
6365     Py_XDECREF(py_funcname);
6366     
6367     return py_code;
6368 }
6369
6370 #endif /* CYTHON_PROFILE */
6371 """ % {
6372     'EMPTY_TUPLE' : Naming.empty_tuple,
6373     'EMPTY_BYTES' : Naming.empty_bytes,
6374     "MODULE": Naming.module_cname,
6375 })