Nodes.py 280 KB
Newer Older
1

William Stein's avatar
William Stein committed
2 3 4
#
#   Pyrex - Parse tree nodes
#
5 6 7 8 9 10 11 12
import cython
from cython import set
cython.declare(sys=object, os=object, time=object, copy=object,
               Builtin=object, error=object, warning=object, Naming=object, PyrexTypes=object,
               py_object_type=object, ModuleScope=object, LocalScope=object, ClosureScope=object, \
               StructOrUnionScope=object, PyClassScope=object, CClassScope=object,
               CppClassScope=object, UtilityCode=object, EncodedString=object,
               absolute_path_length=cython.Py_ssize_t)
William Stein's avatar
William Stein committed
13

14
import sys, os, time, copy
Robert Bradshaw's avatar
Robert Bradshaw committed
15

16
import Builtin
17
from Errors import error, warning, InternalError
William Stein's avatar
William Stein committed
18 19
import Naming
import PyrexTypes
20
import TypeSlots
21
from PyrexTypes import py_object_type, error_type, CFuncType
Stefan Behnel's avatar
Stefan Behnel committed
22
from Symtab import ModuleScope, LocalScope, ClosureScope, \
DaniloFreitas's avatar
DaniloFreitas committed
23
    StructOrUnionScope, PyClassScope, CClassScope, CppClassScope
24
from Cython.Utils import open_new_file, replace_suffix
25
from Code import UtilityCode, ClosureTempAllocator
26
from StringEncoding import EncodedString, escape_byte_string, split_string_literal
William Stein's avatar
William Stein committed
27
import Options
28
import ControlFlow
29
import DebugFlags
William Stein's avatar
William Stein committed
30

Gary Furnish's avatar
Gary Furnish committed
31
absolute_path_length = 0
32 33 34 35 36 37 38

def relative_position(pos):
    """
    We embed the relative filename in the generated C file, since we
    don't want to have to regnerate and compile all the source code
    whenever the Python install directory moves (which could happen,
    e.g,. when distributing binaries.)
39

40 41 42 43 44 45 46 47 48
    INPUT:
        a position tuple -- (absolute filename, line number column position)

    OUTPUT:
        relative filename
        line number

    AUTHOR: William Stein
    """
Gary Furnish's avatar
Gary Furnish committed
49 50
    global absolute_path_length
    if absolute_path_length==0:
51
        absolute_path_length = len(os.path.abspath(os.getcwd()))
52
    return (pos[0].get_filenametable_entry()[absolute_path_length+1:], pos[1])
53 54 55 56

def embed_position(pos, docstring):
    if not Options.embed_pos_in_docstring:
        return docstring
57
    pos_line = u'File: %s (starting at line %s)' % relative_position(pos)
58 59
    if docstring is None:
        # unicode string
60
        return EncodedString(pos_line)
61 62 63 64 65 66 67 68 69 70 71 72

    # make sure we can encode the filename in the docstring encoding
    # otherwise make the docstring a unicode string
    encoding = docstring.encoding
    if encoding is not None:
        try:
            encoded_bytes = pos_line.encode(encoding)
        except UnicodeEncodeError:
            encoding = None

    if not docstring:
        # reuse the string encoding of the original docstring
73
        doc = EncodedString(pos_line)
74
    else:
75
        doc = EncodedString(pos_line + u'\n' + docstring)
76 77
    doc.encoding = encoding
    return doc
78

79 80 81 82 83 84 85

from Code import CCodeWriter
from types import FunctionType

def write_func_call(func):
    def f(*args, **kwds):
        if len(args) > 1 and isinstance(args[1], CCodeWriter):
Robert Bradshaw's avatar
Robert Bradshaw committed
86 87
            # here we annotate the code with this function call
            # but only if new code is generated
88
            node, code = args[:2]
Robert Bradshaw's avatar
Robert Bradshaw committed
89 90
            marker = '                    /* %s -> %s.%s %s */' % (
                    ' ' * code.call_level,
91 92
                    node.__class__.__name__,
                    func.__name__,
Robert Bradshaw's avatar
Robert Bradshaw committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
                    node.pos[1:])
            pristine = code.buffer.stream.tell()
            code.putln(marker)
            start = code.buffer.stream.tell()
            code.call_level += 4
            res = func(*args, **kwds)
            code.call_level -= 4
            if start == code.buffer.stream.tell():
                code.buffer.stream.seek(pristine)
            else:
                marker = marker.replace('->', '<-')
                code.putln(marker)
            return res
        else:
            return func(*args, **kwds)
108 109 110 111
    return f

class VerboseCodeWriter(type):
    # Set this as a metaclass to trace function calls in code.
112
    # This slows down code generation and makes much larger files.
113 114 115 116 117 118 119 120
    def __new__(cls, name, bases, attrs):
        attrs = dict(attrs)
        for mname, m in attrs.items():
            if isinstance(m, FunctionType):
                attrs[mname] = write_func_call(m)
        return super(VerboseCodeWriter, cls).__new__(cls, name, bases, attrs)


Stefan Behnel's avatar
Stefan Behnel committed
121
class Node(object):
William Stein's avatar
William Stein committed
122 123 124
    #  pos         (string, int, int)   Source file position
    #  is_name     boolean              Is a NameNode
    #  is_literal  boolean              Is a ConstNode
125

126 127
    if DebugFlags.debug_trace_code_generation:
        __metaclass__ = VerboseCodeWriter
128

William Stein's avatar
William Stein committed
129 130
    is_name = 0
    is_literal = 0
131
    temps = None
132

133 134 135
    # All descandants should set child_attrs to a list of the attributes
    # containing nodes considered "children" in the tree. Each such attribute
    # can either contain a single node or a list of nodes. See Visitor.py.
136
    child_attrs = None
137

William Stein's avatar
William Stein committed
138 139 140
    def __init__(self, pos, **kw):
        self.pos = pos
        self.__dict__.update(kw)
141

142 143
    gil_message = "Operation"

144
    nogil_check = None
145

146
    def gil_error(self, env=None):
147
        error(self.pos, "%s not allowed without gil" % self.gil_message)
148

Robert Bradshaw's avatar
Robert Bradshaw committed
149
    cpp_message = "Operation"
150

Robert Bradshaw's avatar
Robert Bradshaw committed
151 152 153 154 155 156
    def cpp_check(self, env):
        if not env.is_cpp():
            self.cpp_error()

    def cpp_error(self):
        error(self.pos, "%s only allowed in c++" % self.cpp_message)
157

158 159 160 161 162 163
    def clone_node(self):
        """Clone the node. This is defined as a shallow copy, except for member lists
           amongst the child attributes (from get_child_accessors) which are also
           copied. Lists containing child nodes are thus seen as a way for the node
           to hold multiple children directly; the list is not treated as a seperate
           level in the tree."""
164 165 166
        result = copy.copy(self)
        for attrname in result.child_attrs:
            value = getattr(result, attrname)
167
            if isinstance(value, list):
168
                setattr(result, attrname, [x for x in value])
169
        return result
170 171


William Stein's avatar
William Stein committed
172
    #
173
    #  There are 4 phases of parse tree processing, applied in order to
William Stein's avatar
William Stein committed
174 175
    #  all the statements in a given scope-block:
    #
176 177 178 179
    #  (0) analyse_control_flow
    #        Create the control flow tree into which state can be asserted and
    #        queried.
    #
William Stein's avatar
William Stein committed
180 181 182 183 184
    #  (1) analyse_declarations
    #        Make symbol table entries for all declarations at the current
    #        level, both explicit (def, cdef, etc.) and implicit (assignment
    #        to an otherwise undeclared name).
    #
185
    #  (2) analyse_expressions
William Stein's avatar
William Stein committed
186 187
    #         Determine the result types of expressions and fill in the
    #         'type' attribute of each ExprNode. Insert coercion nodes into the
188
    #         tree where needed to convert to and from Python objects.
William Stein's avatar
William Stein committed
189 190 191 192
    #         Allocate temporary locals for intermediate results. Fill
    #         in the 'result_code' attribute of each ExprNode with a C code
    #         fragment.
    #
193
    #  (3) generate_code
William Stein's avatar
William Stein committed
194 195 196 197
    #         Emit C code for all declarations, statements and expressions.
    #         Recursively applies the 3 processing phases to the bodies of
    #         functions.
    #
198

199 200
    def analyse_control_flow(self, env):
        pass
201

William Stein's avatar
William Stein committed
202 203
    def analyse_declarations(self, env):
        pass
204

William Stein's avatar
William Stein committed
205 206 207
    def analyse_expressions(self, env):
        raise InternalError("analyse_expressions not implemented for %s" % \
            self.__class__.__name__)
208

William Stein's avatar
William Stein committed
209 210 211
    def generate_code(self, code):
        raise InternalError("generate_code not implemented for %s" % \
            self.__class__.__name__)
212

213 214 215 216
    def annotate(self, code):
        # mro does the wrong thing
        if isinstance(self, BlockNode):
            self.body.annotate(code)
217

218 219 220 221
    def end_pos(self):
        try:
            return self._end_pos
        except AttributeError:
Stefan Behnel's avatar
Stefan Behnel committed
222
            pos = self.pos
223 224 225
            if not self.child_attrs:
                self._end_pos = pos
                return pos
226
            for attr in self.child_attrs:
227
                child = getattr(self, attr)
228
                # Sometimes lists, sometimes nodes
229 230 231
                if child is None:
                    pass
                elif isinstance(child, list):
Stefan Behnel's avatar
Stefan Behnel committed
232 233
                    for c in child:
                        pos = max(pos, c.end_pos())
234
                else:
Stefan Behnel's avatar
Stefan Behnel committed
235 236 237
                    pos = max(pos, child.end_pos())
            self._end_pos = pos
            return pos
William Stein's avatar
William Stein committed
238

239
    def dump(self, level=0, filter_out=("pos",), cutoff=100, encountered=None):
240 241
        if cutoff == 0:
            return "<...nesting level cutoff...>"
242 243 244
        if encountered is None:
            encountered = set()
        if id(self) in encountered:
245
            return "<%s (0x%x) -- already output>" % (self.__class__.__name__, id(self))
246
        encountered.add(id(self))
247

248 249
        def dump_child(x, level):
            if isinstance(x, Node):
250
                return x.dump(level, filter_out, cutoff-1, encountered)
251
            elif isinstance(x, list):
Robert Bradshaw's avatar
Robert Bradshaw committed
252
                return "[%s]" % ", ".join([dump_child(item, level) for item in x])
253 254
            else:
                return repr(x)
255 256


257
        attrs = [(key, value) for key, value in self.__dict__.items() if key not in filter_out]
258
        if len(attrs) == 0:
259
            return "<%s (0x%x)>" % (self.__class__.__name__, id(self))
260 261
        else:
            indent = "  " * level
262
            res = "<%s (0x%x)\n" % (self.__class__.__name__, id(self))
263 264 265 266
            for key, value in attrs:
                res += "%s  %s: %s\n" % (indent, key, dump_child(value, level + 1))
            res += "%s>" % indent
            return res
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

class CompilerDirectivesNode(Node):
    """
    Sets compiler directives for the children nodes
    """
    #  directives     {string:value}  A dictionary holding the right value for
    #                                 *all* possible directives.
    #  body           Node
    child_attrs = ["body"]

    def analyse_control_flow(self, env):
        old = env.directives
        env.directives = self.directives
        self.body.analyse_control_flow(env)
        env.directives = old

    def analyse_declarations(self, env):
        old = env.directives
        env.directives = self.directives
        self.body.analyse_declarations(env)
        env.directives = old
288

289 290 291 292 293 294 295 296 297 298 299 300 301
    def analyse_expressions(self, env):
        old = env.directives
        env.directives = self.directives
        self.body.analyse_expressions(env)
        env.directives = old

    def generate_function_definitions(self, env, code):
        env_old = env.directives
        code_old = code.globalstate.directives
        code.globalstate.directives = self.directives
        self.body.generate_function_definitions(env, code)
        env.directives = env_old
        code.globalstate.directives = code_old
302

303 304 305 306 307
    def generate_execution_code(self, code):
        old = code.globalstate.directives
        code.globalstate.directives = self.directives
        self.body.generate_execution_code(code)
        code.globalstate.directives = old
308

309 310 311 312 313
    def annotate(self, code):
        old = code.globalstate.directives
        code.globalstate.directives = self.directives
        self.body.annotate(code)
        code.globalstate.directives = old
314

Stefan Behnel's avatar
Stefan Behnel committed
315
class BlockNode(object):
William Stein's avatar
William Stein committed
316 317
    #  Mixin class for nodes representing a declaration block.

318
    def generate_cached_builtins_decls(self, env, code):
319
        entries = env.global_scope().undeclared_cached_builtins
320
        for entry in entries:
321
            code.globalstate.add_cached_builtin_decl(entry)
322
        del entries[:]
323 324 325 326

    def generate_lambda_definitions(self, env, code):
        for node in env.lambda_defs:
            node.generate_function_definitions(env, code)
William Stein's avatar
William Stein committed
327 328 329

class StatListNode(Node):
    # stats     a list of StatNode
330

331
    child_attrs = ["stats"]
332 333 334 335 336

    def create_analysed(pos, env, *args, **kw):
        node = StatListNode(pos, *args, **kw)
        return node # No node-specific analysis necesarry
    create_analysed = staticmethod(create_analysed)
337

338 339 340 341
    def analyse_control_flow(self, env):
        for stat in self.stats:
            stat.analyse_control_flow(env)

William Stein's avatar
William Stein committed
342 343 344 345
    def analyse_declarations(self, env):
        #print "StatListNode.analyse_declarations" ###
        for stat in self.stats:
            stat.analyse_declarations(env)
346

William Stein's avatar
William Stein committed
347 348 349 350
    def analyse_expressions(self, env):
        #print "StatListNode.analyse_expressions" ###
        for stat in self.stats:
            stat.analyse_expressions(env)
351

352
    def generate_function_definitions(self, env, code):
William Stein's avatar
William Stein committed
353 354
        #print "StatListNode.generate_function_definitions" ###
        for stat in self.stats:
355
            stat.generate_function_definitions(env, code)
356

William Stein's avatar
William Stein committed
357 358 359 360 361
    def generate_execution_code(self, code):
        #print "StatListNode.generate_execution_code" ###
        for stat in self.stats:
            code.mark_pos(stat.pos)
            stat.generate_execution_code(code)
362

363 364 365
    def annotate(self, code):
        for stat in self.stats:
            stat.annotate(code)
366

William Stein's avatar
William Stein committed
367 368 369 370 371 372 373 374 375 376 377 378 379

class StatNode(Node):
    #
    #  Code generation for statements is split into the following subphases:
    #
    #  (1) generate_function_definitions
    #        Emit C code for the definitions of any structs,
    #        unions, enums and functions defined in the current
    #        scope-block.
    #
    #  (2) generate_execution_code
    #        Emit C code for executable statements.
    #
380

381
    def generate_function_definitions(self, env, code):
William Stein's avatar
William Stein committed
382
        pass
383

William Stein's avatar
William Stein committed
384 385 386 387 388 389 390 391
    def generate_execution_code(self, code):
        raise InternalError("generate_execution_code not implemented for %s" % \
            self.__class__.__name__)


class CDefExternNode(StatNode):
    #  include_file   string or None
    #  body           StatNode
392

393
    child_attrs = ["body"]
394

William Stein's avatar
William Stein committed
395 396 397 398 399 400 401
    def analyse_declarations(self, env):
        if self.include_file:
            env.add_include_file(self.include_file)
        old_cinclude_flag = env.in_cinclude
        env.in_cinclude = 1
        self.body.analyse_declarations(env)
        env.in_cinclude = old_cinclude_flag
402

William Stein's avatar
William Stein committed
403 404
    def analyse_expressions(self, env):
        pass
405

William Stein's avatar
William Stein committed
406 407
    def generate_execution_code(self, code):
        pass
408 409 410

    def annotate(self, code):
        self.body.annotate(code)
411

William Stein's avatar
William Stein committed
412 413 414 415 416 417 418 419

class CDeclaratorNode(Node):
    # Part of a C declaration.
    #
    # Processing during analyse_declarations phase:
    #
    #   analyse
    #      Returns (name, type) pair where name is the
420
    #      CNameDeclaratorNode of the name being declared
William Stein's avatar
William Stein committed
421 422
    #      and type is the type it is being declared as.
    #
423
    #  calling_convention  string   Calling convention of CFuncDeclaratorNode
424
    #                               for which this is a base
425

426 427
    child_attrs = []

428 429
    calling_convention = ""

William Stein's avatar
William Stein committed
430 431

class CNameDeclaratorNode(CDeclaratorNode):
Robert Bradshaw's avatar
Robert Bradshaw committed
432 433 434
    #  name    string             The Pyrex name being declared
    #  cname   string or None     C name, if specified
    #  default ExprNode or None   the value assigned on declaration
435

Robert Bradshaw's avatar
Robert Bradshaw committed
436
    child_attrs = ['default']
437

438
    default = None
439

440 441
    def analyse(self, base_type, env, nonempty = 0):
        if nonempty and self.name == '':
442
            # May have mistaken the name for the type.
443
            if base_type.is_ptr or base_type.is_array or base_type.is_buffer:
444
                error(self.pos, "Missing argument name")
445 446
            elif base_type.is_void:
                error(self.pos, "Use spam() rather than spam(void) to declare a function with no arguments.")
447 448 449
            else:
                self.name = base_type.declaration_code("", for_display=1, pyrex=1)
                base_type = py_object_type
450
        self.type = base_type
William Stein's avatar
William Stein committed
451
        return self, base_type
452

William Stein's avatar
William Stein committed
453 454
class CPtrDeclaratorNode(CDeclaratorNode):
    # base     CDeclaratorNode
455

456 457
    child_attrs = ["base"]

458
    def analyse(self, base_type, env, nonempty = 0):
William Stein's avatar
William Stein committed
459 460 461 462
        if base_type.is_pyobject:
            error(self.pos,
                "Pointer base type cannot be a Python object")
        ptr_type = PyrexTypes.c_ptr_type(base_type)
463
        return self.base.analyse(ptr_type, env, nonempty = nonempty)
Danilo Freitas's avatar
Danilo Freitas committed
464 465 466 467 468 469 470 471 472 473

class CReferenceDeclaratorNode(CDeclaratorNode):
    # base     CDeclaratorNode

    child_attrs = ["base"]

    def analyse(self, base_type, env, nonempty = 0):
        if base_type.is_pyobject:
            error(self.pos,
                  "Reference base type cannot be a Python object")
474
        ref_type = PyrexTypes.c_ref_type(base_type)
Danilo Freitas's avatar
Danilo Freitas committed
475 476
        return self.base.analyse(ref_type, env, nonempty = nonempty)

William Stein's avatar
William Stein committed
477 478 479
class CArrayDeclaratorNode(CDeclaratorNode):
    # base        CDeclaratorNode
    # dimension   ExprNode
480 481

    child_attrs = ["base", "dimension"]
482

483
    def analyse(self, base_type, env, nonempty = 0):
Robert Bradshaw's avatar
Robert Bradshaw committed
484 485 486 487 488 489 490 491 492 493 494 495 496
        if base_type.is_cpp_class:
            from ExprNodes import TupleNode
            if isinstance(self.dimension, TupleNode):
                args = self.dimension.args
            else:
                args = self.dimension,
            values = [v.analyse_as_type(env) for v in args]
            if None in values:
                ix = values.index(None)
                error(args[ix].pos, "Template parameter not a type.")
                return error_type
            base_type = base_type.specialize_here(self.pos, values)
            return self.base.analyse(base_type, env, nonempty = nonempty)
William Stein's avatar
William Stein committed
497 498 499 500
        if self.dimension:
            self.dimension.analyse_const_expression(env)
            if not self.dimension.type.is_int:
                error(self.dimension.pos, "Array dimension not integer")
501 502 503 504 505 506 507
            size = self.dimension.get_constant_c_result_code()
            if size is not None:
                try:
                    size = int(size)
                except ValueError:
                    # runtime constant?
                    pass
William Stein's avatar
William Stein committed
508 509 510 511 512 513 514 515
        else:
            size = None
        if not base_type.is_complete():
            error(self.pos,
                "Array element type '%s' is incomplete" % base_type)
        if base_type.is_pyobject:
            error(self.pos,
                "Array element cannot be a Python object")
516 517 518
        if base_type.is_cfunction:
            error(self.pos,
                "Array element cannot be a function")
William Stein's avatar
William Stein committed
519
        array_type = PyrexTypes.c_array_type(base_type, size)
520
        return self.base.analyse(array_type, env, nonempty = nonempty)
William Stein's avatar
William Stein committed
521 522 523 524 525 526 527 528


class CFuncDeclaratorNode(CDeclaratorNode):
    # base             CDeclaratorNode
    # args             [CArgDeclNode]
    # has_varargs      boolean
    # exception_value  ConstNode
    # exception_check  boolean    True if PyErr_Occurred check needed
529 530
    # nogil            boolean    Can be called without gil
    # with_gil         boolean    Acquire gil around function body
531

532 533
    child_attrs = ["base", "args", "exception_value"]

534
    overridable = 0
535
    optional_arg_count = 0
William Stein's avatar
William Stein committed
536

537
    def analyse(self, return_type, env, nonempty = 0, directive_locals = {}):
538 539
        if nonempty:
            nonempty -= 1
William Stein's avatar
William Stein committed
540
        func_type_args = []
541 542 543
        for i, arg_node in enumerate(self.args):
            name_declarator, type = arg_node.analyse(env, nonempty = nonempty,
                                                     is_self_arg = (i == 0 and env.is_c_class_scope))
William Stein's avatar
William Stein committed
544
            name = name_declarator.name
545 546 547 548 549
            if name in directive_locals:
                type_node = directive_locals[name]
                other_type = type_node.analyse_as_type(env)
                if other_type is None:
                    error(type_node.pos, "Not a type")
Robert Bradshaw's avatar
Robert Bradshaw committed
550
                elif (type is not PyrexTypes.py_object_type
551 552 553 554 555
                      and not type.same_as(other_type)):
                    error(self.base.pos, "Signature does not agree with previous declaration")
                    error(type_node.pos, "Previous declaration here")
                else:
                    type = other_type
William Stein's avatar
William Stein committed
556
            if name_declarator.cname:
557
                error(self.pos,
William Stein's avatar
William Stein committed
558 559 560 561 562 563
                    "Function argument cannot have C name specification")
            # Turn *[] argument into **
            if type.is_array:
                type = PyrexTypes.c_ptr_type(type.base_type)
            # Catch attempted C-style func(void) decl
            if type.is_void:
Robert Bradshaw's avatar
Robert Bradshaw committed
564
                error(arg_node.pos, "Use spam() rather than spam(void) to declare a function with no arguments.")
William Stein's avatar
William Stein committed
565 566 567
            func_type_args.append(
                PyrexTypes.CFuncTypeArg(name, type, arg_node.pos))
            if arg_node.default:
568
                self.optional_arg_count += 1
569 570
            elif self.optional_arg_count:
                error(self.pos, "Non-default argument follows default argument")
571

572 573
        if self.optional_arg_count:
            scope = StructOrUnionScope()
574
            arg_count_member = '%sn' % Naming.pyrex_prefix
Robert Bradshaw's avatar
Robert Bradshaw committed
575
            scope.declare_var(arg_count_member, PyrexTypes.c_int_type, self.pos)
576 577
            for arg in func_type_args[len(func_type_args)-self.optional_arg_count:]:
                scope.declare_var(arg.name, arg.type, arg.pos, allow_pyobject = 1)
578
            struct_cname = env.mangle(Naming.opt_arg_prefix, self.base.name)
579 580 581 582 583 584
            self.op_args_struct = env.global_scope().declare_struct_or_union(name = struct_cname,
                                        kind = 'struct',
                                        scope = scope,
                                        typedef_flag = 0,
                                        pos = self.pos,
                                        cname = struct_cname)
585
            self.op_args_struct.defined_in_pxd = 1
586
            self.op_args_struct.used = 1
587

William Stein's avatar
William Stein committed
588 589
        exc_val = None
        exc_check = 0
590 591
        if self.exception_check == '+':
            env.add_include_file('stdexcept')
William Stein's avatar
William Stein committed
592
        if return_type.is_pyobject \
Robert Bradshaw's avatar
Robert Bradshaw committed
593 594
            and (self.exception_value or self.exception_check) \
            and self.exception_check != '+':
William Stein's avatar
William Stein committed
595 596 597 598 599
                error(self.pos,
                    "Exception clause not allowed for function returning Python object")
        else:
            if self.exception_value:
                self.exception_value.analyse_const_expression(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
600
                if self.exception_check == '+':
601
                    self.exception_value.analyse_types(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
602 603 604 605 606 607
                    exc_val_type = self.exception_value.type
                    if not exc_val_type.is_error and \
                          not exc_val_type.is_pyobject and \
                          not (exc_val_type.is_cfunction and not exc_val_type.return_type.is_pyobject and len(exc_val_type.args)==0):
                        error(self.exception_value.pos,
                            "Exception value must be a Python exception or cdef function with no arguments.")
608
                    exc_val = self.exception_value
Robert Bradshaw's avatar
Robert Bradshaw committed
609
                else:
610
                    self.exception_value = self.exception_value.coerce_to(return_type, env)
611 612 613 614 615 616 617 618
                    if self.exception_value.analyse_const_expression(env):
                        exc_val = self.exception_value.get_constant_c_result_code()
                        if exc_val is None:
                            raise InternalError("get_constant_c_result_code not implemented for %s" %
                                self.exception_value.__class__.__name__)
                        if not return_type.assignable_from(self.exception_value.type):
                            error(self.exception_value.pos,
                                  "Exception value incompatible with function return type")
William Stein's avatar
William Stein committed
619
            exc_check = self.exception_check
620 621 622
        if return_type.is_cfunction:
            error(self.pos,
                "Function cannot return a function")
William Stein's avatar
William Stein committed
623
        func_type = PyrexTypes.CFuncType(
624
            return_type, func_type_args, self.has_varargs,
625
            optional_arg_count = self.optional_arg_count,
626
            exception_value = exc_val, exception_check = exc_check,
627
            calling_convention = self.base.calling_convention,
628
            nogil = self.nogil, with_gil = self.with_gil, is_overridable = self.overridable)
629
        if self.optional_arg_count:
630
            func_type.op_arg_struct = PyrexTypes.c_ptr_type(self.op_args_struct.type)
631 632 633 634 635 636 637
        callspec = env.directives['callspec']
        if callspec:
            current = func_type.calling_convention
            if current and current != callspec:
                error(self.pos, "cannot have both '%s' and '%s' "
                      "calling conventions" % (current, callspec))
            func_type.calling_convention = callspec
William Stein's avatar
William Stein committed
638 639 640 641 642 643 644 645 646
        return self.base.analyse(func_type, env)


class CArgDeclNode(Node):
    # Item in a function declaration argument list.
    #
    # base_type      CBaseTypeNode
    # declarator     CDeclaratorNode
    # not_none       boolean            Tagged with 'not None'
647 648
    # or_none        boolean            Tagged with 'or None'
    # accept_none    boolean            Resolved boolean for not_none/or_none
William Stein's avatar
William Stein committed
649
    # default        ExprNode or None
650
    # default_value  PyObjectConst      constant for default value
651
    # annotation     ExprNode or None   Py3 function arg annotation
William Stein's avatar
William Stein committed
652
    # is_self_arg    boolean            Is the "self" arg of an extension type method
653
    # is_type_arg    boolean            Is the "class" arg of an extension type classmethod
654 655
    # is_kw_only     boolean            Is a keyword-only argument

656 657
    child_attrs = ["base_type", "declarator", "default"]

William Stein's avatar
William Stein committed
658
    is_self_arg = 0
659
    is_type_arg = 0
660
    is_generic = 1
661 662 663
    kw_only = 0
    not_none = 0
    or_none = 0
664 665
    type = None
    name_declarator = None
666
    default_value = None
667
    annotation = None
668

669 670 671
    def analyse(self, env, nonempty = 0, is_self_arg = False):
        if is_self_arg:
            self.base_type.is_self_arg = self.is_self_arg = True
672 673 674 675 676 677 678 679 680 681 682 683
        if self.type is None:
            # The parser may missinterpret names as types...
            # We fix that here.
            if isinstance(self.declarator, CNameDeclaratorNode) and self.declarator.name == '':
                if nonempty:
                    self.declarator.name = self.base_type.name
                    self.base_type.name = None
                    self.base_type.is_basic_c_type = False
                could_be_name = True
            else:
                could_be_name = False
            base_type = self.base_type.analyse(env, could_be_name = could_be_name)
Robert Bradshaw's avatar
Robert Bradshaw committed
684
            if hasattr(self.base_type, 'arg_name') and self.base_type.arg_name:
685
                self.declarator.name = self.base_type.arg_name
686 687
            # The parser is unable to resolve the ambiguity of [] as part of the
            # type (e.g. in buffers) or empty declarator (as with arrays).
688
            # This is only arises for empty multi-dimensional arrays.
689 690
            if (base_type.is_array
                    and isinstance(self.base_type, TemplatedTypeNode)
691 692 693 694 695 696
                    and isinstance(self.declarator, CArrayDeclaratorNode)):
                declarator = self.declarator
                while isinstance(declarator.base, CArrayDeclaratorNode):
                    declarator = declarator.base
                declarator.base = self.base_type.array_declarator
                base_type = base_type.base_type
697
            return self.declarator.analyse(base_type, env, nonempty = nonempty)
698
        else:
699
            return self.name_declarator, self.type
William Stein's avatar
William Stein committed
700

701 702 703 704 705 706 707 708 709
    def calculate_default_value_code(self, code):
        if self.default_value is None:
            if self.default:
                if self.default.is_literal:
                    # will not output any code, just assign the result_code
                    self.default.generate_evaluation_code(code)
                    return self.type.cast_code(self.default.result())
                self.default_value = code.get_argument_default_const(self.type)
        return self.default_value
710

711 712 713 714
    def annotate(self, code):
        if self.default:
            self.default.annotate(code)

William Stein's avatar
William Stein committed
715 716 717 718 719 720 721 722

class CBaseTypeNode(Node):
    # Abstract base class for C base type nodes.
    #
    # Processing during analyse_declarations phase:
    #
    #   analyse
    #     Returns the type.
723

William Stein's avatar
William Stein committed
724
    pass
725

726 727
    def analyse_as_type(self, env):
        return self.analyse(env)
728

729 730
class CAnalysedBaseTypeNode(Node):
    # type            type
731

732
    child_attrs = []
733

734 735
    def analyse(self, env, could_be_name = False):
        return self.type
William Stein's avatar
William Stein committed
736 737 738 739 740 741 742

class CSimpleBaseTypeNode(CBaseTypeNode):
    # name             string
    # module_path      [string]     Qualifying name components
    # is_basic_c_type  boolean
    # signed           boolean
    # longness         integer
743
    # complex          boolean
William Stein's avatar
William Stein committed
744
    # is_self_arg      boolean      Is self argument of C method
745
    # ##is_type_arg      boolean      Is type argument of class method
William Stein's avatar
William Stein committed
746

747
    child_attrs = []
748
    arg_name = None   # in case the argument name was interpreted as a type
749 750 751
    module_path = []
    is_basic_c_type = False
    complex = False
752

753
    def analyse(self, env, could_be_name = False):
William Stein's avatar
William Stein committed
754
        # Return type descriptor.
755
        #print "CSimpleBaseTypeNode.analyse: is_self_arg =", self.is_self_arg ###
William Stein's avatar
William Stein committed
756 757 758 759 760 761 762 763 764
        type = None
        if self.is_basic_c_type:
            type = PyrexTypes.simple_c_type(self.signed, self.longness, self.name)
            if not type:
                error(self.pos, "Unrecognised type modifier combination")
        elif self.name == "object" and not self.module_path:
            type = py_object_type
        elif self.name is None:
            if self.is_self_arg and env.is_c_class_scope:
765
                #print "CSimpleBaseTypeNode.analyse: defaulting to parent type" ###
William Stein's avatar
William Stein committed
766
                type = env.parent_type
767 768
            ## elif self.is_type_arg and env.is_c_class_scope:
            ##     type = Builtin.type_type
William Stein's avatar
William Stein committed
769 770 771
            else:
                type = py_object_type
        else:
772 773 774 775
            if self.module_path:
                scope = env.find_imported_module(self.module_path, self.pos)
            else:
                scope = env
William Stein's avatar
William Stein committed
776
            if scope:
777 778
                if scope.is_c_class_scope:
                    scope = scope.global_scope()
779
                entry = scope.lookup(self.name)
William Stein's avatar
William Stein committed
780 781
                if entry and entry.is_type:
                    type = entry.type
782 783 784
                elif could_be_name:
                    if self.is_self_arg and env.is_c_class_scope:
                        type = env.parent_type
785 786
                    ## elif self.is_type_arg and env.is_c_class_scope:
                    ##     type = Builtin.type_type
787 788 789
                    else:
                        type = py_object_type
                    self.arg_name = self.name
William Stein's avatar
William Stein committed
790
                else:
Danilo Freitas's avatar
Danilo Freitas committed
791 792 793
                    if self.templates:
                        if not self.name in self.templates:
                            error(self.pos, "'%s' is not a type identifier" % self.name)
794
                        type = PyrexTypes.TemplatePlaceholderType(self.name)
Danilo Freitas's avatar
Danilo Freitas committed
795 796
                    else:
                        error(self.pos, "'%s' is not a type identifier" % self.name)
797
        if self.complex:
798 799 800
            if not type.is_numeric or type.is_complex:
                error(self.pos, "can only complexify c numeric types")
            type = PyrexTypes.CComplexType(type)
801
            type.create_declaration_utility_code(env)
802 803 804 805 806 807 808 809
        elif type is Builtin.complex_type:
            # Special case: optimise builtin complex type into C's
            # double complex.  The parser cannot do this (as for the
            # normal scalar types) as the user may have redeclared the
            # 'complex' type.  Testing for the exact type here works.
            type = PyrexTypes.c_double_complex_type
            type.create_declaration_utility_code(env)
            self.complex = True
William Stein's avatar
William Stein committed
810 811 812 813 814
        if type:
            return type
        else:
            return PyrexTypes.error_type

Robert Bradshaw's avatar
Robert Bradshaw committed
815
class CNestedBaseTypeNode(CBaseTypeNode):
816
    # For C++ classes that live inside other C++ classes.
Robert Bradshaw's avatar
Robert Bradshaw committed
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835

    # name             string
    # base_type        CBaseTypeNode

    child_attrs = ['base_type']

    def analyse(self, env, could_be_name = None):
        base_type = self.base_type.analyse(env)
        if base_type is PyrexTypes.error_type:
            return PyrexTypes.error_type
        if not base_type.is_cpp_class:
            error(self.pos, "'%s' is not a valid type scope" % base_type)
            return PyrexTypes.error_type
        type_entry = base_type.scope.lookup_here(self.name)
        if not type_entry or not type_entry.is_type:
            error(self.pos, "'%s.%s' is not a type identifier" % (base_type, self.name))
            return PyrexTypes.error_type
        return type_entry.type

Danilo Freitas's avatar
Danilo Freitas committed
836
class TemplatedTypeNode(CBaseTypeNode):
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
837
    #  After parsing:
838 839
    #  positional_args  [ExprNode]        List of positional arguments
    #  keyword_args     DictNode          Keyword arguments
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
840 841 842
    #  base_type_node   CBaseTypeNode

    #  After analysis:
843
    #  type             PyrexTypes.BufferType or PyrexTypes.CppClassType  ...containing the right options
844

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
845

846 847
    child_attrs = ["base_type_node", "positional_args",
                   "keyword_args", "dtype_node"]
848

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
849
    dtype_node = None
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
850 851

    name = None
852

853 854 855
    def analyse(self, env, could_be_name = False, base_type = None):
        if base_type is None:
            base_type = self.base_type_node.analyse(env)
856
        if base_type.is_error: return base_type
857

858
        if base_type.is_cpp_class:
859
            # Templated class
860
            if self.keyword_args and self.keyword_args.key_value_pairs:
861 862 863 864 865
                error(self.pos, "c++ templates cannot take keyword arguments");
                self.type = PyrexTypes.error_type
            else:
                template_types = []
                for template_node in self.positional_args:
866 867 868 869 870
                    type = template_node.analyse_as_type(env)
                    if type is None:
                        error(template_node.pos, "unknown type in template argument")
                        return error_type
                    template_types.append(type)
871
                self.type = base_type.specialize_here(self.pos, template_types)
872

873 874
        elif base_type.is_pyobject:
            # Buffer
875
            import Buffer
876

877 878 879 880 881 882
            options = Buffer.analyse_buffer_options(
                self.pos,
                env,
                self.positional_args,
                self.keyword_args,
                base_type.buffer_defaults)
883

Robert Bradshaw's avatar
Robert Bradshaw committed
884 885 886
            if sys.version_info[0] < 3:
                # Py 2.x enforces byte strings as keyword arguments ...
                options = dict([ (name.encode('ASCII'), value)
887
                                 for name, value in options.items() ])
Stefan Behnel's avatar
Stefan Behnel committed
888

889
            self.type = PyrexTypes.BufferType(base_type, **options)
890

891 892
        else:
            # Array
893
            empty_declarator = CNameDeclaratorNode(self.pos, name="", cname=None)
894 895 896 897
            if len(self.positional_args) > 1 or self.keyword_args.key_value_pairs:
                error(self.pos, "invalid array declaration")
                self.type = PyrexTypes.error_type
            else:
898
                # It would be nice to merge this class with CArrayDeclaratorNode,
899 900 901 902 903
                # but arrays are part of the declaration, not the type...
                if not self.positional_args:
                    dimension = None
                else:
                    dimension = self.positional_args[0]
904 905
                self.array_declarator = CArrayDeclaratorNode(self.pos,
                    base = empty_declarator,
906 907
                    dimension = dimension)
                self.type = self.array_declarator.analyse(base_type, env)[1]
908

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
909
        return self.type
William Stein's avatar
William Stein committed
910 911 912 913

class CComplexBaseTypeNode(CBaseTypeNode):
    # base_type   CBaseTypeNode
    # declarator  CDeclaratorNode
914

915 916
    child_attrs = ["base_type", "declarator"]

917 918
    def analyse(self, env, could_be_name = False):
        base = self.base_type.analyse(env, could_be_name)
William Stein's avatar
William Stein committed
919 920 921 922 923 924 925 926 927 928
        _, type = self.declarator.analyse(base, env)
        return type


class CVarDefNode(StatNode):
    #  C variable definition or forward/extern function declaration.
    #
    #  visibility    'private' or 'public' or 'extern'
    #  base_type     CBaseTypeNode
    #  declarators   [CDeclaratorNode]
929
    #  in_pxd        boolean
Stefan Behnel's avatar
Stefan Behnel committed
930
    #  api           boolean
931

932
    #  decorators    [cython.locals(...)] or None
933
    #  directive_locals { string : NameNode } locals defined by cython.locals(...)
934 935

    child_attrs = ["base_type", "declarators"]
936

Robert Bradshaw's avatar
Robert Bradshaw committed
937
    decorators = None
938
    directive_locals = None
939

William Stein's avatar
William Stein committed
940
    def analyse_declarations(self, env, dest_scope = None):
941 942
        if self.directive_locals is None:
            self.directive_locals = {}
William Stein's avatar
William Stein committed
943 944
        if not dest_scope:
            dest_scope = env
945
        self.dest_scope = dest_scope
William Stein's avatar
William Stein committed
946
        base_type = self.base_type.analyse(env)
947

948 949 950
        # If the field is an external typedef, we cannot be sure about the type,
        # so do conversion ourself rather than rely on the CPython mechanism (through
        # a property; made in AnalyseDeclarationsTransform).
951
        if (dest_scope.is_c_class_scope
952
            and self.visibility in ('public', 'readonly')):
953 954
            need_property = True
        else:
955
            need_property = False
956
        visibility = self.visibility
957

William Stein's avatar
William Stein committed
958
        for declarator in self.declarators:
959 960 961 962
            if isinstance(declarator, CFuncDeclaratorNode):
                name_declarator, type = declarator.analyse(base_type, env, directive_locals=self.directive_locals)
            else:
                name_declarator, type = declarator.analyse(base_type, env)
William Stein's avatar
William Stein committed
963 964 965 966 967 968 969 970 971
            if not type.is_complete():
                if not (self.visibility == 'extern' and type.is_array):
                    error(declarator.pos,
                        "Variable type '%s' is incomplete" % type)
            if self.visibility == 'extern' and type.is_pyobject:
                error(declarator.pos,
                    "Python object cannot be declared extern")
            name = name_declarator.name
            cname = name_declarator.cname
972 973 974
            if name == '':
                error(declarator.pos, "Missing name in declaration.")
                return
William Stein's avatar
William Stein committed
975
            if type.is_cfunction:
976
                entry = dest_scope.declare_cfunction(name, type, declarator.pos,
Stefan Behnel's avatar
Stefan Behnel committed
977 978
                    cname = cname, visibility = self.visibility, in_pxd = self.in_pxd,
                    api = self.api)
Robert Bradshaw's avatar
Robert Bradshaw committed
979
                if entry is not None:
980
                    entry.directive_locals = copy.copy(self.directive_locals)
William Stein's avatar
William Stein committed
981
            else:
982
                if self.directive_locals:
983
                    error(self.pos, "Decorators can only be followed by functions")
984
                if self.in_pxd and self.visibility != 'extern':
985
                    error(self.pos,
986
                        "Only 'extern' C variable declaration allowed in .pxd file")
987
                entry = dest_scope.declare_var(name, type, declarator.pos,
988
                            cname=cname, visibility=visibility, api=self.api, is_cdef=1)
989
                entry.needs_property = need_property
990

William Stein's avatar
William Stein committed
991 992 993 994 995 996

class CStructOrUnionDefNode(StatNode):
    #  name          string
    #  cname         string or None
    #  kind          "struct" or "union"
    #  typedef_flag  boolean
997
    #  visibility    "public" or "private"
998
    #  api           boolean
Stefan Behnel's avatar
Stefan Behnel committed
999
    #  in_pxd        boolean
William Stein's avatar
William Stein committed
1000 1001
    #  attributes    [CVarDefNode] or None
    #  entry         Entry
1002
    #  packed        boolean
1003

1004 1005
    child_attrs = ["attributes"]

William Stein's avatar
William Stein committed
1006 1007
    def analyse_declarations(self, env):
        scope = None
1008 1009
        if self.visibility == 'extern' and self.packed:
            error(self.pos, "Cannot declare extern struct as 'packed'")
William Stein's avatar
William Stein committed
1010
        if self.attributes is not None:
1011
            scope = StructOrUnionScope(self.name)
William Stein's avatar
William Stein committed
1012 1013
        self.entry = env.declare_struct_or_union(
            self.name, self.kind, scope, self.typedef_flag, self.pos,
1014 1015
            self.cname, visibility = self.visibility, api = self.api,
            packed = self.packed)
William Stein's avatar
William Stein committed
1016
        if self.attributes is not None:
Stefan Behnel's avatar
Stefan Behnel committed
1017 1018
            if self.in_pxd and not env.in_cinclude:
                self.entry.defined_in_pxd = 1
William Stein's avatar
William Stein committed
1019 1020
            for attr in self.attributes:
                attr.analyse_declarations(env, scope)
1021
            if self.visibility != 'extern':
Stefan Behnel's avatar
Stefan Behnel committed
1022
                need_typedef_indirection = False
1023 1024 1025
                for attr in scope.var_entries:
                    type = attr.type
                    while type.is_array:
1026 1027
                        type = type.base_type
                    if type == self.entry.type:
1028 1029 1030 1031 1032 1033
                        error(attr.pos, "Struct cannot contain itself as a member.")
                    if self.typedef_flag:
                        while type.is_ptr:
                            type = type.base_type
                        if type == self.entry.type:
                            need_typedef_indirection = True
Robert Bradshaw's avatar
Robert Bradshaw committed
1034
                if need_typedef_indirection:
1035
                    # C can't handle typedef structs that refer to themselves.
Robert Bradshaw's avatar
Robert Bradshaw committed
1036
                    struct_entry = self.entry
Stefan Behnel's avatar
Stefan Behnel committed
1037 1038 1039
                    self.entry = env.declare_typedef(
                        self.name, struct_entry.type, self.pos,
                        cname = self.cname, visibility='ignore')
Robert Bradshaw's avatar
Robert Bradshaw committed
1040
                    struct_entry.type.typedef_flag = False
Stefan Behnel's avatar
Stefan Behnel committed
1041
                    # FIXME: this might be considered a hack ;-)
1042 1043
                    struct_entry.cname = struct_entry.type.cname = \
                                         '_' + self.entry.type.typedef_cname
1044

William Stein's avatar
William Stein committed
1045 1046
    def analyse_expressions(self, env):
        pass
1047

William Stein's avatar
William Stein committed
1048 1049 1050 1051
    def generate_execution_code(self, code):
        pass


Robert Bradshaw's avatar
Robert Bradshaw committed
1052 1053 1054 1055
class CppClassNode(CStructOrUnionDefNode):

    #  name          string
    #  cname         string or None
1056
    #  visibility    "extern"
Robert Bradshaw's avatar
Robert Bradshaw committed
1057 1058 1059
    #  in_pxd        boolean
    #  attributes    [CVarDefNode] or None
    #  entry         Entry
DaniloFreitas's avatar
DaniloFreitas committed
1060
    #  base_classes  [string]
Danilo Freitas's avatar
Danilo Freitas committed
1061
    #  templates     [string] or None
Robert Bradshaw's avatar
Robert Bradshaw committed
1062 1063 1064

    def analyse_declarations(self, env):
        scope = None
1065
        if self.attributes is not None:
Robert Bradshaw's avatar
Robert Bradshaw committed
1066
            scope = CppClassScope(self.name, env)
1067 1068 1069 1070 1071 1072 1073 1074 1075
        base_class_types = []
        for base_class_name in self.base_classes:
            base_class_entry = env.lookup(base_class_name)
            if base_class_entry is None:
                error(self.pos, "'%s' not found" % base_class_name)
            elif not base_class_entry.is_type or not base_class_entry.type.is_cpp_class:
                error(self.pos, "'%s' is not a cpp class type" % base_class_name)
            else:
                base_class_types.append(base_class_entry.type)
1076 1077 1078 1079
        if self.templates is None:
            template_types = None
        else:
            template_types = [PyrexTypes.TemplatePlaceholderType(template_name) for template_name in self.templates]
1080
        self.entry = env.declare_cpp_class(
1081
            self.name, scope, self.pos,
1082
            self.cname, base_class_types, visibility = self.visibility, templates = template_types)
1083 1084
        if self.entry is None:
            return
Danilo Freitas's avatar
Danilo Freitas committed
1085
        self.entry.is_cpp_class = 1
Robert Bradshaw's avatar
Robert Bradshaw committed
1086 1087 1088 1089
        if self.attributes is not None:
            if self.in_pxd and not env.in_cinclude:
                self.entry.defined_in_pxd = 1
            for attr in self.attributes:
Robert Bradshaw's avatar
Robert Bradshaw committed
1090
                attr.analyse_declarations(scope)
Robert Bradshaw's avatar
Robert Bradshaw committed
1091

William Stein's avatar
William Stein committed
1092 1093 1094 1095 1096
class CEnumDefNode(StatNode):
    #  name           string or None
    #  cname          string or None
    #  items          [CEnumDefItemNode]
    #  typedef_flag   boolean
Stefan Behnel's avatar
Stefan Behnel committed
1097
    #  visibility     "public" or "private"
1098
    #  api            boolean
Stefan Behnel's avatar
Stefan Behnel committed
1099
    #  in_pxd         boolean
William Stein's avatar
William Stein committed
1100
    #  entry          Entry
Robert Bradshaw's avatar
Robert Bradshaw committed
1101

1102
    child_attrs = ["items"]
1103

William Stein's avatar
William Stein committed
1104 1105
    def analyse_declarations(self, env):
        self.entry = env.declare_enum(self.name, self.pos,
1106
            cname = self.cname, typedef_flag = self.typedef_flag,
1107
            visibility = self.visibility, api = self.api)
Stefan Behnel's avatar
Stefan Behnel committed
1108 1109 1110 1111 1112
        if self.items is not None:
            if self.in_pxd and not env.in_cinclude:
                self.entry.defined_in_pxd = 1
            for item in self.items:
                item.analyse_declarations(env, self.entry)
William Stein's avatar
William Stein committed
1113

1114 1115 1116
    def analyse_expressions(self, env):
        pass

William Stein's avatar
William Stein committed
1117
    def generate_execution_code(self, code):
1118
        if self.visibility == 'public' or self.api:
1119
            temp = code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=True)
Robert Bradshaw's avatar
Robert Bradshaw committed
1120 1121
            for item in self.entry.enum_values:
                code.putln("%s = PyInt_FromLong(%s); %s" % (
1122
                        temp,
Robert Bradshaw's avatar
Robert Bradshaw committed
1123
                        item.cname,
1124
                        code.error_goto_if_null(temp, item.pos)))
Stefan Behnel's avatar
merge  
Stefan Behnel committed
1125
                code.put_gotref(temp)
1126
                code.putln('if (__Pyx_SetAttrString(%s, "%s", %s) < 0) %s' % (
1127 1128
                        Naming.module_cname,
                        item.name,
1129
                        temp,
Robert Bradshaw's avatar
Robert Bradshaw committed
1130
                        code.error_goto(item.pos)))
Stefan Behnel's avatar
merge  
Stefan Behnel committed
1131
                code.put_decref_clear(temp, PyrexTypes.py_object_type)
1132
            code.funcstate.release_temp(temp)
William Stein's avatar
William Stein committed
1133 1134 1135 1136 1137 1138


class CEnumDefItemNode(StatNode):
    #  name     string
    #  cname    string or None
    #  value    ExprNode or None
1139

1140 1141
    child_attrs = ["value"]

William Stein's avatar
William Stein committed
1142 1143 1144
    def analyse_declarations(self, env, enum_entry):
        if self.value:
            self.value.analyse_const_expression(env)
1145 1146 1147
            if not self.value.type.is_int:
                self.value = self.value.coerce_to(PyrexTypes.c_int_type, env)
                self.value.analyse_const_expression(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
1148
        entry = env.declare_const(self.name, enum_entry.type,
1149
            self.value, self.pos, cname = self.cname,
1150
            visibility = enum_entry.visibility, api = enum_entry.api)
William Stein's avatar
William Stein committed
1151 1152 1153 1154
        enum_entry.enum_values.append(entry)


class CTypeDefNode(StatNode):
Stefan Behnel's avatar
Stefan Behnel committed
1155 1156 1157
    #  base_type    CBaseTypeNode
    #  declarator   CDeclaratorNode
    #  visibility   "public" or "private"
1158
    #  api          boolean
Stefan Behnel's avatar
Stefan Behnel committed
1159
    #  in_pxd       boolean
1160 1161

    child_attrs = ["base_type", "declarator"]
1162

William Stein's avatar
William Stein committed
1163 1164 1165 1166 1167
    def analyse_declarations(self, env):
        base = self.base_type.analyse(env)
        name_declarator, type = self.declarator.analyse(base, env)
        name = name_declarator.name
        cname = name_declarator.cname
Stefan Behnel's avatar
Stefan Behnel committed
1168
        entry = env.declare_typedef(name, type, self.pos,
1169
            cname = cname, visibility = self.visibility, api = self.api)
Stefan Behnel's avatar
Stefan Behnel committed
1170 1171
        if self.in_pxd and not env.in_cinclude:
            entry.defined_in_pxd = 1
Robert Bradshaw's avatar
Robert Bradshaw committed
1172

William Stein's avatar
William Stein committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    def analyse_expressions(self, env):
        pass
    def generate_execution_code(self, code):
        pass


class FuncDefNode(StatNode, BlockNode):
    #  Base class for function definition nodes.
    #
    #  return_type     PyrexType
    #  #filename        string        C name of filename string const
    #  entry           Symtab.Entry
1185
    #  needs_closure   boolean        Whether or not this function has inner functions/classes/yield
Vitja Makarov's avatar
Vitja Makarov committed
1186
    #  needs_outer_scope boolean      Whether or not this function requires outer scope
1187
    #  directive_locals { string : NameNode } locals defined by cython.locals(...)
1188

1189
    py_func = None
1190
    assmt = None
1191
    needs_closure = False
Vitja Makarov's avatar
Vitja Makarov committed
1192
    needs_outer_scope = False
1193
    is_generator = False
1194
    is_generator_body = False
Robert Bradshaw's avatar
Robert Bradshaw committed
1195
    modifiers = []
1196

1197 1198
    def analyse_default_values(self, env):
        genv = env.global_scope()
1199
        default_seen = 0
1200 1201
        for arg in self.args:
            if arg.default:
1202
                default_seen = 1
1203
                if arg.is_generic:
1204 1205
                    arg.default.analyse_types(env)
                    arg.default = arg.default.coerce_to(arg.type, genv)
1206 1207 1208 1209
                else:
                    error(arg.pos,
                        "This argument cannot have a default value")
                    arg.default = None
1210 1211 1212 1213
            elif arg.kw_only:
                default_seen = 1
            elif default_seen:
                error(arg.pos, "Non-default argument following default argument")
1214

1215 1216 1217 1218 1219 1220 1221 1222
    def align_argument_type(self, env, arg):
        directive_locals = self.directive_locals
        type = arg.type
        if arg.name in directive_locals:
            type_node = directive_locals[arg.name]
            other_type = type_node.analyse_as_type(env)
            if other_type is None:
                error(type_node.pos, "Not a type")
Robert Bradshaw's avatar
Robert Bradshaw committed
1223
            elif (type is not PyrexTypes.py_object_type
1224 1225 1226 1227 1228 1229 1230
                    and not type.same_as(other_type)):
                error(arg.base_type.pos, "Signature does not agree with previous declaration")
                error(type_node.pos, "Previous declaration here")
            else:
                arg.type = other_type
        return arg

1231 1232
    def need_gil_acquisition(self, lenv):
        return 0
1233

1234 1235
    def create_local_scope(self, env):
        genv = env
1236
        while genv.is_py_class_scope or genv.is_c_class_scope:
1237
            genv = genv.outer_scope
1238
        if self.needs_closure:
1239 1240 1241
            lenv = ClosureScope(name=self.entry.name,
                                outer_scope = genv,
                                scope_name=self.entry.cname)
1242
        else:
1243 1244 1245
            lenv = LocalScope(name=self.entry.name,
                              outer_scope=genv,
                              parent_scope=env)
William Stein's avatar
William Stein committed
1246
        lenv.return_type = self.return_type
1247 1248 1249
        type = self.entry.type
        if type.is_cfunction:
            lenv.nogil = type.nogil and not type.with_gil
1250
        self.local_scope = lenv
1251
        lenv.directives = env.directives
1252
        return lenv
1253

1254 1255 1256
    def generate_function_body(self, env, code):
        self.body.generate_execution_code(code)

1257
    def generate_function_definitions(self, env, code):
1258
        import Buffer
1259 1260

        lenv = self.local_scope
Vitja Makarov's avatar
Vitja Makarov committed
1261
        if lenv.is_closure_scope and not lenv.is_passthrough:
1262 1263 1264 1265 1266
            outer_scope_cname = "%s->%s" % (Naming.cur_scope_cname,
                                            Naming.outer_scope_cname)
        else:
            outer_scope_cname = Naming.outer_scope_cname
        lenv.mangle_closure_cnames(outer_scope_cname)
Robert Bradshaw's avatar
Robert Bradshaw committed
1267 1268
        # Generate closure function definitions
        self.body.generate_function_definitions(lenv, code)
Stefan Behnel's avatar
Stefan Behnel committed
1269
        # generate lambda function definitions
1270
        self.generate_lambda_definitions(lenv, code)
1271

1272 1273
        is_getbuffer_slot = (self.entry.name == "__getbuffer__" and
                             self.entry.scope.is_c_class_scope)
1274 1275 1276
        is_releasebuffer_slot = (self.entry.name == "__releasebuffer__" and
                                 self.entry.scope.is_c_class_scope)
        is_buffer_slot = is_getbuffer_slot or is_releasebuffer_slot
1277
        if is_buffer_slot:
1278 1279
            if 'cython_unused' not in self.modifiers:
                self.modifiers = self.modifiers + ['cython_unused']
1280 1281 1282 1283 1284 1285 1286 1287 1288

        preprocessor_guard = None
        if self.entry.is_special and not is_buffer_slot:
            slot = TypeSlots.method_name_to_slot.get(self.entry.name)
            if slot:
                preprocessor_guard = slot.preprocessor_guard_code()
                if (self.entry.name == '__long__' and
                    not self.entry.scope.lookup_here('__int__')):
                    preprocessor_guard = None
1289

1290
        profile = code.globalstate.directives['profile']
1291 1292 1293
        if profile and lenv.nogil:
            warning(self.pos, "Cannot profile nogil function.", 1)
            profile = False
Robert Bradshaw's avatar
Robert Bradshaw committed
1294
        if profile:
1295
            code.globalstate.use_utility_code(profile_utility_code)
1296

1297
        # Generate C code for header and body of function
1298
        code.enter_cfunc_scope()
1299
        code.return_from_error_cleanup_label = code.new_label()
1300

William Stein's avatar
William Stein committed
1301
        # ----- Top-level constants used by this function
1302
        code.mark_pos(self.pos)
1303
        self.generate_cached_builtins_decls(lenv, code)
William Stein's avatar
William Stein committed
1304 1305
        # ----- Function header
        code.putln("")
1306 1307 1308 1309

        if preprocessor_guard:
            code.putln(preprocessor_guard)

1310
        with_pymethdef = self.needs_assignment_synthesis(env, code)
1311
        if self.py_func:
1312
            self.py_func.generate_function_header(code,
Stefan Behnel's avatar
Stefan Behnel committed
1313
                with_pymethdef = with_pymethdef,
1314
                proto_only=True)
William Stein's avatar
William Stein committed
1315
        self.generate_function_header(code,
Stefan Behnel's avatar
Stefan Behnel committed
1316
            with_pymethdef = with_pymethdef)
William Stein's avatar
William Stein committed
1317
        # ----- Local variable declarations
1318 1319 1320 1321
        # Find function scope
        cenv = env
        while cenv.is_py_class_scope or cenv.is_c_class_scope:
            cenv = cenv.outer_scope
Vitja Makarov's avatar
Vitja Makarov committed
1322
        if self.needs_closure:
1323
            code.put(lenv.scope_class.type.declaration_code(Naming.cur_scope_cname))
Robert Bradshaw's avatar
Robert Bradshaw committed
1324
            code.putln(";")
Vitja Makarov's avatar
Vitja Makarov committed
1325 1326 1327 1328
        elif self.needs_outer_scope:
            if lenv.is_passthrough:
                code.put(lenv.scope_class.type.declaration_code(Naming.cur_scope_cname))
                code.putln(";")
1329
            code.put(cenv.scope_class.type.declaration_code(Naming.outer_scope_cname))
1330
            code.putln(";")
William Stein's avatar
William Stein committed
1331
        self.generate_argument_declarations(lenv, code)
1332 1333 1334
        for entry in lenv.var_entries:
            if not entry.in_closure:
                code.put_var_declaration(entry)
William Stein's avatar
William Stein committed
1335 1336
        init = ""
        if not self.return_type.is_void:
1337 1338
            if self.return_type.is_pyobject:
                init = " = NULL"
William Stein's avatar
William Stein committed
1339
            code.putln(
1340
                "%s%s;" %
1341 1342
                    (self.return_type.declaration_code(Naming.retval_cname),
                     init))
1343
        tempvardecl_code = code.insertion_point()
1344 1345
        if not lenv.nogil:
            code.put_declare_refcount_context()
William Stein's avatar
William Stein committed
1346
        self.generate_keyword_list(code)
1347 1348
        if profile:
            code.put_trace_declarations()
William Stein's avatar
William Stein committed
1349 1350
        # ----- Extern library function declarations
        lenv.generate_library_function_declarations(code)
1351
        # ----- GIL acquisition
1352
        acquire_gil = self.acquire_gil
1353
        if acquire_gil:
Stefan Behnel's avatar
Stefan Behnel committed
1354
            env.use_utility_code(force_init_threads_utility_code)
1355
            code.putln("#ifdef WITH_THREAD")
1356
            code.putln("PyGILState_STATE _save = PyGILState_Ensure();")
1357
            code.putln("#endif")
1358
        # ----- set up refnanny
1359 1360
        if not lenv.nogil:
            code.put_setup_refcount_context(self.entry.name)
1361
        # ----- Automatic lead-ins for certain special functions
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1362 1363
        if is_getbuffer_slot:
            self.getbuffer_init(code)
1364
        # ----- Create closure scope object
Robert Bradshaw's avatar
Robert Bradshaw committed
1365
        if self.needs_closure:
1366
            code.putln("%s = (%s)%s->tp_new(%s, %s, NULL);" % (
1367 1368
                Naming.cur_scope_cname,
                lenv.scope_class.type.declaration_code(''),
1369
                lenv.scope_class.type.typeptr_cname,
1370
                lenv.scope_class.type.typeptr_cname,
1371 1372 1373 1374
                Naming.empty_tuple))
            code.putln("if (unlikely(!%s)) {" % Naming.cur_scope_cname)
            if is_getbuffer_slot:
                self.getbuffer_error_cleanup(code)
1375
            if not lenv.nogil:
1376 1377 1378 1379
                code.put_finish_refcount_context()
            # FIXME: what if the error return value is a Python value?
            code.putln("return %s;" % self.error_value())
            code.putln("}")
Robert Bradshaw's avatar
Robert Bradshaw committed
1380
            code.put_gotref(Naming.cur_scope_cname)
Robert Bradshaw's avatar
Robert Bradshaw committed
1381
            # Note that it is unsafe to decref the scope at this point.
Vitja Makarov's avatar
Vitja Makarov committed
1382
        if self.needs_outer_scope:
1383 1384
            code.putln("%s = (%s)%s;" % (
                            outer_scope_cname,
1385
                            cenv.scope_class.type.declaration_code(''),
1386
                            Naming.self_cname))
Vitja Makarov's avatar
Vitja Makarov committed
1387 1388 1389
            if lenv.is_passthrough:
                code.putln("%s = %s;" % (Naming.cur_scope_cname, outer_scope_cname));
            elif self.needs_closure:
1390
                # inner closures own a reference to their outer parent
1391
                code.put_incref(outer_scope_cname, cenv.scope_class.type)
1392
                code.put_giveref(outer_scope_cname)
1393 1394 1395 1396 1397
        # ----- Trace function call
        if profile:
            # this looks a bit late, but if we don't get here due to a
            # fatal error before hand, it's not really worth tracing
            code.put_trace_call(self.entry.name, self.pos)
William Stein's avatar
William Stein committed
1398
        # ----- Fetch arguments
1399
        self.generate_argument_parsing_code(env, code)
1400
        # If an argument is assigned to in the body, we must
Robert Bradshaw's avatar
Robert Bradshaw committed
1401 1402
        # incref it to properly keep track of refcounts.
        for entry in lenv.arg_entries:
1403
            if entry.type.is_pyobject:
1404
                if (acquire_gil or entry.assignments) and not entry.in_closure:
1405
                    code.put_var_incref(entry)
1406
        # ----- Initialise local variables
William Stein's avatar
William Stein committed
1407
        for entry in lenv.var_entries:
1408
            if entry.type.is_pyobject and entry.init_to_none and entry.used:
William Stein's avatar
William Stein committed
1409
                code.put_init_var_to_py_none(entry)
1410 1411
        # ----- Initialise local buffer auxiliary variables
        for entry in lenv.var_entries + lenv.arg_entries:
1412
            if entry.type.is_buffer and entry.buffer_aux.buffer_info_var.used:
1413 1414
                code.putln("%s.buf = NULL;" %
                           entry.buffer_aux.buffer_info_var.cname)
1415
        # ----- Check and convert arguments
William Stein's avatar
William Stein committed
1416
        self.generate_argument_type_tests(code)
1417 1418 1419
        # ----- Acquire buffer arguments
        for entry in lenv.arg_entries:
            if entry.type.is_buffer:
1420 1421 1422 1423 1424
                Buffer.put_acquire_arg_buffer(entry, code, self.pos)

        # -------------------------
        # ----- Function body -----
        # -------------------------
1425
        self.generate_function_body(env, code)
1426

William Stein's avatar
William Stein committed
1427 1428 1429 1430
        # ----- Default return value
        code.putln("")
        if self.return_type.is_pyobject:
            #if self.return_type.is_extension_type:
1431
            #    lhs = "(PyObject *)%s" % Naming.retval_cname
William Stein's avatar
William Stein committed
1432 1433 1434 1435 1436 1437 1438 1439
            #else:
            lhs = Naming.retval_cname
            code.put_init_to_py_none(lhs, self.return_type)
        else:
            val = self.return_type.default_value
            if val:
                code.putln("%s = %s;" % (Naming.retval_cname, val))
        # ----- Error cleanup
1440 1441 1442
        if code.error_label in code.labels_used:
            code.put_goto(code.return_label)
            code.put_label(code.error_label)
1443 1444
            for cname, type in code.funcstate.all_managed_temps():
                code.put_xdecref(cname, type)
1445 1446 1447 1448 1449

            # Clean up buffers -- this calls a Python function
            # so need to save and restore error state
            buffers_present = len(lenv.buffer_entries) > 0
            if buffers_present:
1450
                code.globalstate.use_utility_code(restore_exception_utility_code)
1451
                code.putln("{ PyObject *__pyx_type, *__pyx_value, *__pyx_tb;")
1452
                code.putln("__Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb);")
1453
                for entry in lenv.buffer_entries:
1454
                    Buffer.put_release_buffer_code(code, entry)
1455
                    #code.putln("%s = 0;" % entry.cname)
1456
                code.putln("__Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);}")
1457

1458 1459 1460
            err_val = self.error_value()
            exc_check = self.caller_will_check_exceptions()
            if err_val is not None or exc_check:
1461
                # TODO: Fix exception tracing (though currently unused by cProfile).
Robert Bradshaw's avatar
Robert Bradshaw committed
1462 1463
                # code.globalstate.use_utility_code(get_exception_tuple_utility_code)
                # code.put_trace_exception()
Robert Bradshaw's avatar
Robert Bradshaw committed
1464
                code.putln('__Pyx_AddTraceback("%s");' % self.entry.qualified_name)
1465
            else:
1466 1467
                warning(self.entry.pos, "Unraisable exception in function '%s'." \
                            % self.entry.qualified_name, 0)
1468
                code.putln(
1469
                    '__Pyx_WriteUnraisable("%s");' %
1470 1471
                        self.entry.qualified_name)
                env.use_utility_code(unraisable_exception_utility_code)
1472
                env.use_utility_code(restore_exception_utility_code)
1473 1474 1475 1476
            default_retval = self.return_type.default_value
            if err_val is None and default_retval:
                err_val = default_retval
            if err_val is not None:
1477
                code.putln("%s = %s;" % (Naming.retval_cname, err_val))
1478 1479 1480 1481 1482 1483 1484 1485

            if is_getbuffer_slot:
                self.getbuffer_error_cleanup(code)

            # If we are using the non-error cleanup section we should
            # jump past it if we have an error. The if-test below determine
            # whether this section is used.
            if buffers_present or is_getbuffer_slot:
1486 1487
                code.put_goto(code.return_from_error_cleanup_label)

1488

1489
        # ----- Non-error return cleanup
William Stein's avatar
William Stein committed
1490
        code.put_label(code.return_label)
1491
        for entry in lenv.buffer_entries:
1492
            if entry.used:
1493
                Buffer.put_release_buffer_code(code, entry)
1494 1495
        if is_getbuffer_slot:
            self.getbuffer_normal_cleanup(code)
1496 1497
        # ----- Return cleanup for both error and no-error return
        code.put_label(code.return_from_error_cleanup_label)
Robert Bradshaw's avatar
Robert Bradshaw committed
1498 1499
        if not Options.init_local_none:
            for entry in lenv.var_entries:
Craig Citro's avatar
Craig Citro committed
1500
                if lenv.control_flow.get_state((entry.name, 'initialized')) is not True:
Robert Bradshaw's avatar
Robert Bradshaw committed
1501
                    entry.xdecref_cleanup = 1
1502

1503
        for entry in lenv.var_entries:
1504 1505 1506
            if entry.type.is_pyobject:
                if entry.used and not entry.in_closure:
                    code.put_var_decref(entry)
Robert Bradshaw's avatar
Robert Bradshaw committed
1507
        # Decref any increfed args
1508
        for entry in lenv.arg_entries:
1509
            if entry.type.is_pyobject:
1510
                if (acquire_gil or entry.assignments) and not entry.in_closure:
1511
                    code.put_var_decref(entry)
Robert Bradshaw's avatar
Robert Bradshaw committed
1512 1513
        if self.needs_closure:
            code.put_decref(Naming.cur_scope_cname, lenv.scope_class.type)
1514

1515
        # ----- Return
1516
        # This code is duplicated in ModuleNode.generate_module_init_func
1517 1518 1519 1520 1521 1522 1523
        if not lenv.nogil:
            default_retval = self.return_type.default_value
            err_val = self.error_value()
            if err_val is None and default_retval:
                err_val = default_retval
            if self.return_type.is_pyobject:
                code.put_xgiveref(self.return_type.as_pyobject(Naming.retval_cname))
1524

1525 1526
        if self.entry.is_special and self.entry.name == "__hash__":
            # Returning -1 for __hash__ is supposed to signal an error
1527
            # We do as Python instances and coerce -1 into -2.
1528 1529
            code.putln("if (unlikely(%s == -1) && !PyErr_Occurred()) %s = -2;" % (
                    Naming.retval_cname, Naming.retval_cname))
1530

Robert Bradshaw's avatar
Robert Bradshaw committed
1531 1532 1533 1534 1535
        if profile:
            if self.return_type.is_pyobject:
                code.put_trace_return(Naming.retval_cname)
            else:
                code.put_trace_return("Py_None")
1536 1537
        if not lenv.nogil:
            code.put_finish_refcount_context()
1538

1539
        if acquire_gil:
1540
            code.putln("#ifdef WITH_THREAD")
1541
            code.putln("PyGILState_Release(_save);")
1542
            code.putln("#endif")
1543

William Stein's avatar
William Stein committed
1544
        if not self.return_type.is_void:
1545
            code.putln("return %s;" % Naming.retval_cname)
1546

William Stein's avatar
William Stein committed
1547
        code.putln("}")
1548 1549 1550 1551

        if preprocessor_guard:
            code.putln("#endif /*!(%s)*/" % preprocessor_guard)

1552
        # ----- Go back and insert temp variable declarations
1553
        tempvardecl_code.put_temp_declarations(code.funcstate)
1554
        # ----- Python version
1555
        code.exit_cfunc_scope()
1556
        if self.py_func:
1557
            self.py_func.generate_function_definitions(env, code)
1558
        self.generate_wrapper_functions(code)
William Stein's avatar
William Stein committed
1559 1560 1561 1562 1563 1564 1565 1566

    def declare_argument(self, env, arg):
        if arg.type.is_void:
            error(arg.pos, "Invalid use of 'void'")
        elif not arg.type.is_complete() and not arg.type.is_array:
            error(arg.pos,
                "Argument type '%s' is incomplete" % arg.type)
        return env.declare_arg(arg.name, arg.type, arg.pos)
1567

1568 1569 1570
    def generate_arg_type_test(self, arg, code):
        # Generate type test for one argument.
        if arg.type.typeobj_is_available():
1571
            code.globalstate.use_utility_code(arg_type_test_utility_code)
1572 1573 1574 1575
            typeptr_cname = arg.type.typeptr_cname
            arg_code = "((PyObject *)%s)" % arg.entry.cname
            code.putln(
                'if (unlikely(!__Pyx_ArgTypeTest(%s, %s, %d, "%s", %s))) %s' % (
1576
                    arg_code,
1577 1578 1579 1580 1581 1582 1583 1584
                    typeptr_cname,
                    arg.accept_none,
                    arg.name,
                    arg.type.is_builtin_type,
                    code.error_goto(arg.pos)))
        else:
            error(arg.pos, "Cannot test type of extern C class "
                "without type object name specification")
1585 1586 1587 1588 1589 1590 1591 1592

    def generate_arg_none_check(self, arg, code):
        # Generate None check for one argument.
        code.putln('if (unlikely(((PyObject *)%s) == Py_None)) {' % arg.entry.cname)
        code.putln('''PyErr_Format(PyExc_TypeError, "Argument '%s' must not be None"); %s''' % (
            arg.name,
            code.error_goto(arg.pos)))
        code.putln('}')
1593

1594
    def generate_wrapper_functions(self, code):
William Stein's avatar
William Stein committed
1595 1596 1597
        pass

    def generate_execution_code(self, code):
1598 1599 1600 1601
        # Evaluate and store argument default values
        for arg in self.args:
            default = arg.default
            if default:
1602 1603 1604
                if not default.is_literal:
                    default.generate_evaluation_code(code)
                    default.make_owned_reference(code)
1605
                    result = default.result_as(arg.type)
1606
                    code.putln(
1607
                        "%s = %s;" % (
1608 1609 1610 1611 1612
                            arg.calculate_default_value_code(code),
                            result))
                    if arg.type.is_pyobject:
                        code.put_giveref(default.result())
                    default.generate_post_assignment_code(code)
1613
                    default.free_temps(code)
1614 1615 1616
        # For Python class methods, create and store function object
        if self.assmt:
            self.assmt.generate_execution_code(code)
William Stein's avatar
William Stein committed
1617

1618
    #
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1619
    # Special code for the __getbuffer__ function
1620 1621 1622 1623 1624
    #
    def getbuffer_init(self, code):
        info = self.local_scope.arg_entries[1].cname
        # Python 3.0 betas have a bug in memoryview which makes it call
        # getbuffer with a NULL parameter. For now we work around this;
1625 1626
        # the following block should be removed when this bug is fixed.
        code.putln("if (%s != NULL) {" % info)
1627
        code.putln("%s->obj = Py_None; __Pyx_INCREF(Py_None);" % info)
1628
        code.put_giveref("%s->obj" % info) # Do not refnanny object within structs
1629
        code.putln("}")
1630 1631 1632

    def getbuffer_error_cleanup(self, code):
        info = self.local_scope.arg_entries[1].cname
1633 1634
        code.putln("if (%s != NULL && %s->obj != NULL) {"
                   % (info, info))
1635
        code.put_gotref("%s->obj" % info)
1636 1637 1638
        code.putln("__Pyx_DECREF(%s->obj); %s->obj = NULL;"
                   % (info, info))
        code.putln("}")
1639 1640 1641

    def getbuffer_normal_cleanup(self, code):
        info = self.local_scope.arg_entries[1].cname
1642
        code.putln("if (%s != NULL && %s->obj == Py_None) {" % (info, info))
1643 1644 1645
        code.put_gotref("Py_None")
        code.putln("__Pyx_DECREF(Py_None); %s->obj = NULL;" % info)
        code.putln("}")
William Stein's avatar
William Stein committed
1646 1647 1648 1649

class CFuncDefNode(FuncDefNode):
    #  C function definition.
    #
Robert Bradshaw's avatar
Robert Bradshaw committed
1650
    #  modifiers     ['inline']
William Stein's avatar
William Stein committed
1651 1652 1653 1654
    #  visibility    'private' or 'public' or 'extern'
    #  base_type     CBaseTypeNode
    #  declarator    CDeclaratorNode
    #  body          StatListNode
1655
    #  api           boolean
1656
    #  decorators    [DecoratorNode]        list of decorators
William Stein's avatar
William Stein committed
1657
    #
1658
    #  with_gil      boolean    Acquire GIL around body
William Stein's avatar
William Stein committed
1659
    #  type          CFuncType
1660
    #  py_func       wrapper for calling from Python
1661
    #  overridable   whether or not this is a cpdef function
1662
    #  inline_in_pxd whether this is an inline function in a pxd file
1663

1664
    child_attrs = ["base_type", "declarator", "body", "py_func"]
1665 1666

    inline_in_pxd = False
1667
    decorators = None
1668
    directive_locals = None
1669

William Stein's avatar
William Stein committed
1670 1671
    def unqualified_name(self):
        return self.entry.name
1672

William Stein's avatar
William Stein committed
1673
    def analyse_declarations(self, env):
1674 1675
        if self.directive_locals is None:
            self.directive_locals = {}
1676
        self.directive_locals.update(env.directives['locals'])
William Stein's avatar
William Stein committed
1677
        base_type = self.base_type.analyse(env)
1678
        # The 2 here is because we need both function and argument names.
1679 1680 1681 1682 1683 1684
        if isinstance(self.declarator, CFuncDeclaratorNode):
            name_declarator, type = self.declarator.analyse(base_type, env,
                                                            nonempty = 2 * (self.body is not None),
                                                            directive_locals = self.directive_locals)
        else:
            name_declarator, type = self.declarator.analyse(base_type, env, nonempty = 2 * (self.body is not None))
1685
        if not type.is_cfunction:
1686
            error(self.pos,
1687
                "Suite attached to non-function declaration")
William Stein's avatar
William Stein committed
1688 1689 1690 1691 1692
        # Remember the actual type according to the function header
        # written here, because the type in the symbol table entry
        # may be different if we're overriding a C method inherited
        # from the base type of an extension type.
        self.type = type
1693
        type.is_overridable = self.overridable
1694 1695 1696 1697 1698
        declarator = self.declarator
        while not hasattr(declarator, 'args'):
            declarator = declarator.base
        self.args = declarator.args
        for formal_arg, type_arg in zip(self.args, type.args):
1699
            self.align_argument_type(env, type_arg)
1700
            formal_arg.type = type_arg.type
1701
            formal_arg.name = type_arg.name
1702
            formal_arg.cname = type_arg.cname
1703 1704
            if type_arg.type.is_buffer and 'inline' in self.modifiers:
                warning(formal_arg.pos, "Buffer unpacking not optimized away.", 1)
William Stein's avatar
William Stein committed
1705 1706 1707
        name = name_declarator.name
        cname = name_declarator.cname
        self.entry = env.declare_cfunction(
1708
            name, type, self.pos,
William Stein's avatar
William Stein committed
1709
            cname = cname, visibility = self.visibility,
1710
            defining = self.body is not None,
1711
            api = self.api, modifiers = self.modifiers)
1712
        self.entry.inline_func_in_pxd = self.inline_in_pxd
William Stein's avatar
William Stein committed
1713
        self.return_type = type.return_type
1714 1715 1716
        if self.return_type.is_array and visibility != 'extern':
            error(self.pos,
                "Function cannot return an array")
1717

1718 1719 1720 1721
        if self.overridable and not env.is_module_scope:
            if len(self.args) < 1 or not self.args[0].type.is_pyobject:
                # An error will be produced in the cdef function
                self.overridable = False
1722

1723
        if self.overridable:
1724
            import ExprNodes
1725
            py_func_body = self.call_self_node(is_module_scope = env.is_module_scope)
1726
            self.py_func = DefNode(pos = self.pos,
1727 1728
                                   name = self.entry.name,
                                   args = self.args,
1729 1730
                                   star_arg = None,
                                   starstar_arg = None,
1731
                                   doc = self.doc,
1732 1733
                                   body = py_func_body,
                                   is_wrapper = 1)
1734
            self.py_func.is_module_scope = env.is_module_scope
1735
            self.py_func.analyse_declarations(env)
1736
            self.entry.as_variable = self.py_func.entry
1737 1738
            # Reset scope entry the above cfunction
            env.entries[name] = self.entry
1739 1740 1741
            if not env.is_module_scope or Options.lookup_module_cpdef:
                self.override = OverrideCheckNode(self.pos, py_func = self.py_func)
                self.body = StatListNode(self.pos, stats=[self.override, self.body])
1742
        self.create_local_scope(env)
1743

1744
    def call_self_node(self, omit_optional_args=0, is_module_scope=0):
1745 1746 1747 1748 1749
        import ExprNodes
        args = self.type.args
        if omit_optional_args:
            args = args[:len(args) - self.type.optional_arg_count]
        arg_names = [arg.name for arg in args]
1750
        if is_module_scope:
1751
            cfunc = ExprNodes.NameNode(self.pos, name=self.entry.name)
1752 1753
        else:
            self_arg = ExprNodes.NameNode(self.pos, name=arg_names[0])
1754
            cfunc = ExprNodes.AttributeNode(self.pos, obj=self_arg, attribute=self.entry.name)
1755 1756
        skip_dispatch = not is_module_scope or Options.lookup_module_cpdef
        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)
1757
        return ReturnStatNode(pos=self.pos, return_type=PyrexTypes.py_object_type, value=c_call)
1758

William Stein's avatar
William Stein committed
1759 1760 1761 1762 1763
    def declare_arguments(self, env):
        for arg in self.type.args:
            if not arg.name:
                error(arg.pos, "Missing argument name")
            self.declare_argument(env, arg)
1764

1765
    def need_gil_acquisition(self, lenv):
1766 1767
        return self.type.with_gil

1768
    def nogil_check(self, env):
1769
        type = self.type
1770
        with_gil = type.with_gil
1771 1772 1773 1774
        if type.nogil and not with_gil:
            if type.return_type.is_pyobject:
                error(self.pos,
                      "Function with Python return type cannot be declared nogil")
1775
            for entry in self.local_scope.var_entries:
1776 1777 1778
                if entry.type.is_pyobject:
                    error(self.pos, "Function declared nogil has Python locals or temporaries")

1779
    def analyse_expressions(self, env):
1780
        self.local_scope.directives = env.directives
1781
        if self.py_func is not None:
1782
            # this will also analyse the default values
1783
            self.py_func.analyse_expressions(env)
1784 1785
        else:
            self.analyse_default_values(env)
1786
        self.acquire_gil = self.need_gil_acquisition(self.local_scope)
1787

Robert Bradshaw's avatar
Robert Bradshaw committed
1788 1789 1790
    def needs_assignment_synthesis(self, env, code=None):
        return False

1791
    def generate_function_header(self, code, with_pymethdef, with_opt_args = 1, with_dispatch = 1, cname = None):
William Stein's avatar
William Stein committed
1792 1793
        arg_decls = []
        type = self.type
1794
        for arg in type.args[:len(type.args)-type.optional_arg_count]:
William Stein's avatar
William Stein committed
1795
            arg_decls.append(arg.declaration_code())
1796 1797
        if with_dispatch and self.overridable:
            arg_decls.append(PyrexTypes.c_int_type.declaration_code(Naming.skip_dispatch_cname))
1798 1799
        if type.optional_arg_count and with_opt_args:
            arg_decls.append(type.op_arg_struct.declaration_code(Naming.optional_args_cname))
William Stein's avatar
William Stein committed
1800 1801 1802 1803
        if type.has_varargs:
            arg_decls.append("...")
        if not arg_decls:
            arg_decls = ["void"]
1804 1805
        if cname is None:
            cname = self.entry.func_cname
1806
        entity = type.function_header_code(cname, ', '.join(arg_decls))
1807 1808
        if self.entry.visibility == 'private':
            storage_class = "static "
William Stein's avatar
William Stein committed
1809
        else:
1810
            storage_class = ""
1811 1812
        dll_linkage = None
        modifiers = ""
1813 1814
        if 'inline' in self.modifiers:
            self.modifiers[self.modifiers.index('inline')] = 'cython_inline'
1815 1816
        if self.modifiers:
            modifiers = "%s " % ' '.join(self.modifiers).upper()
Robert Bradshaw's avatar
Robert Bradshaw committed
1817

1818 1819 1820
        header = self.return_type.declaration_code(entity, dll_linkage=dll_linkage)
        #print (storage_class, modifiers, header)
        code.putln("%s%s%s {" % (storage_class, modifiers, header))
William Stein's avatar
William Stein committed
1821 1822

    def generate_argument_declarations(self, env, code):
1823
        for arg in self.args:
1824
            if arg.default:
1825
                result = arg.calculate_default_value_code(code)
1826
                code.putln('%s = %s;' % (
1827
                    arg.type.declaration_code(arg.cname), result))
1828

William Stein's avatar
William Stein committed
1829 1830
    def generate_keyword_list(self, code):
        pass
1831

1832
    def generate_argument_parsing_code(self, env, code):
1833
        i = 0
1834 1835
        if self.type.optional_arg_count:
            code.putln('if (%s) {' % Naming.optional_args_cname)
1836
            for arg in self.args:
1837
                if arg.default:
1838
                    code.putln('if (%s->%sn > %s) {' % (Naming.optional_args_cname, Naming.pyrex_prefix, i))
1839 1840 1841
                    declarator = arg.declarator
                    while not hasattr(declarator, 'name'):
                        declarator = declarator.base
1842
                    code.putln('%s = %s->%s;' % (arg.cname, Naming.optional_args_cname, self.type.opt_arg_cname(declarator.name)))
1843 1844 1845
                    i += 1
            for _ in range(self.type.optional_arg_count):
                code.putln('}')
1846
            code.putln('}')
1847

William Stein's avatar
William Stein committed
1848 1849
    def generate_argument_conversion_code(self, code):
        pass
1850

William Stein's avatar
William Stein committed
1851
    def generate_argument_type_tests(self, code):
1852 1853 1854 1855 1856
        # Generate type tests for args whose type in a parent
        # class is a supertype of the declared type.
        for arg in self.type.args:
            if arg.needs_type_test:
                self.generate_arg_type_test(arg, code)
1857 1858
            elif arg.type.is_pyobject and not arg.accept_none:
                self.generate_arg_none_check(arg, code)
1859

William Stein's avatar
William Stein committed
1860 1861 1862 1863
    def error_value(self):
        if self.return_type.is_pyobject:
            return "0"
        else:
1864 1865
            #return None
            return self.entry.type.exception_value
1866

William Stein's avatar
William Stein committed
1867
    def caller_will_check_exceptions(self):
1868
        return self.entry.type.exception_check
1869

1870 1871
    def generate_wrapper_functions(self, code):
        # If the C signature of a function has changed, we need to generate
1872
        # wrappers to put in the slots here.
1873 1874 1875 1876 1877 1878 1879
        k = 0
        entry = self.entry
        func_type = entry.type
        while entry.prev_entry is not None:
            k += 1
            entry = entry.prev_entry
            entry.func_cname = "%s%swrap_%s" % (self.entry.func_cname, Naming.pyrex_prefix, k)
1880
            code.putln()
1881
            self.generate_function_header(code,
1882
                                          0,
1883 1884
                                          with_dispatch = entry.type.is_overridable,
                                          with_opt_args = entry.type.optional_arg_count,
1885
                                          cname = entry.func_cname)
1886 1887 1888 1889
            if not self.return_type.is_void:
                code.put('return ')
            args = self.type.args
            arglist = [arg.cname for arg in args[:len(args)-self.type.optional_arg_count]]
1890 1891 1892 1893 1894 1895 1896 1897
            if entry.type.is_overridable:
                arglist.append(Naming.skip_dispatch_cname)
            elif func_type.is_overridable:
                arglist.append('0')
            if entry.type.optional_arg_count:
                arglist.append(Naming.optional_args_cname)
            elif func_type.optional_arg_count:
                arglist.append('NULL')
1898 1899
            code.putln('%s(%s);' % (self.entry.func_cname, ', '.join(arglist)))
            code.putln('}')
1900

William Stein's avatar
William Stein committed
1901 1902 1903 1904 1905

class PyArgDeclNode(Node):
    # Argument which must be a Python object (used
    # for * and ** arguments).
    #
1906 1907 1908
    # name        string
    # entry       Symtab.Entry
    # annotation  ExprNode or None   Py3 argument annotation
1909
    child_attrs = []
1910 1911 1912

    def generate_function_definitions(self, env, code):
        self.entry.generate_function_definitions(env, code)
1913 1914 1915 1916

class DecoratorNode(Node):
    # A decorator
    #
1917
    # decorator    NameNode or CallNode or AttributeNode
1918 1919
    child_attrs = ['decorator']

William Stein's avatar
William Stein committed
1920 1921 1922 1923 1924

class DefNode(FuncDefNode):
    # A Python function definition.
    #
    # name          string                 the Python name of the function
Stefan Behnel's avatar
Stefan Behnel committed
1925
    # lambda_name   string                 the internal name of a lambda 'function'
1926
    # decorators    [DecoratorNode]        list of decorators
William Stein's avatar
William Stein committed
1927 1928 1929
    # args          [CArgDeclNode]         formal arguments
    # star_arg      PyArgDeclNode or None  * argument
    # starstar_arg  PyArgDeclNode or None  ** argument
1930
    # doc           EncodedString or None
William Stein's avatar
William Stein committed
1931
    # body          StatListNode
1932 1933
    # return_type_annotation
    #               ExprNode or None       the Py3 return type annotation
William Stein's avatar
William Stein committed
1934 1935 1936 1937 1938
    #
    #  The following subnode is constructed internally
    #  when the def statement is inside a Python class definition.
    #
    #  assmt   AssignmentNode   Function construction/assignment
1939

1940
    child_attrs = ["args", "star_arg", "starstar_arg", "body", "decorators"]
1941

Stefan Behnel's avatar
Stefan Behnel committed
1942
    lambda_name = None
William Stein's avatar
William Stein committed
1943
    assmt = None
1944
    num_kwonly_args = 0
1945
    num_required_kw_args = 0
1946
    reqd_kw_flags_cname = "0"
1947
    is_wrapper = 0
1948
    no_assignment_synthesis = 0
1949
    decorators = None
1950
    return_type_annotation = None
1951
    entry = None
Robert Bradshaw's avatar
Robert Bradshaw committed
1952
    acquire_gil = 0
1953
    self_in_stararg = 0
1954 1955 1956
    star_arg = None
    starstar_arg = None
    doc = None
1957

1958 1959
    def __init__(self, pos, **kwds):
        FuncDefNode.__init__(self, pos, **kwds)
1960
        k = rk = r = 0
1961 1962
        for arg in self.args:
            if arg.kw_only:
1963
                k += 1
1964
                if not arg.default:
1965 1966 1967 1968 1969 1970
                    rk += 1
            if not arg.default:
                r += 1
        self.num_kwonly_args = k
        self.num_required_kw_args = rk
        self.num_required_args = r
1971

1972
    def as_cfunction(self, cfunc=None, scope=None):
1973 1974 1975 1976
        if self.star_arg:
            error(self.star_arg.pos, "cdef function cannot have star argument")
        if self.starstar_arg:
            error(self.starstar_arg.pos, "cdef function cannot have starstar argument")
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
        if cfunc is None:
            cfunc_args = []
            for formal_arg in self.args:
                name_declarator, type = formal_arg.analyse(scope, nonempty=1)
                cfunc_args.append(PyrexTypes.CFuncTypeArg(name = name_declarator.name,
                                                          cname = None,
                                                          type = py_object_type,
                                                          pos = formal_arg.pos))
            cfunc_type = PyrexTypes.CFuncType(return_type = py_object_type,
                                              args = cfunc_args,
                                              has_varargs = False,
                                              exception_value = None,
                                              exception_check = False,
                                              nogil = False,
                                              with_gil = False,
                                              is_overridable = True)
1993
            cfunc = CVarDefNode(self.pos, type=cfunc_type)
1994
        else:
1995 1996
            if scope is None:
                scope = cfunc.scope
1997 1998 1999
            cfunc_type = cfunc.type
            if len(self.args) != len(cfunc_type.args) or cfunc_type.has_varargs:
                error(self.pos, "wrong number of arguments")
Stefan Behnel's avatar
Stefan Behnel committed
2000
                error(cfunc.pos, "previous declaration here")
2001 2002 2003
            for i, (formal_arg, type_arg) in enumerate(zip(self.args, cfunc_type.args)):
                name_declarator, type = formal_arg.analyse(scope, nonempty=1,
                                                           is_self_arg = (i == 0 and scope.is_c_class_scope))
Stefan Behnel's avatar
Stefan Behnel committed
2004
                if type is None or type is PyrexTypes.py_object_type:
2005 2006
                    formal_arg.type = type_arg.type
                    formal_arg.name_declarator = name_declarator
2007
        import ExprNodes
2008
        if cfunc_type.exception_value is None:
2009 2010
            exception_value = None
        else:
2011
            exception_value = ExprNodes.ConstNode(self.pos, value=cfunc_type.exception_value, type=cfunc_type.return_type)
2012
        declarator = CFuncDeclaratorNode(self.pos,
2013 2014 2015
                                         base = CNameDeclaratorNode(self.pos, name=self.name, cname=None),
                                         args = self.args,
                                         has_varargs = False,
2016
                                         exception_check = cfunc_type.exception_check,
2017
                                         exception_value = exception_value,
2018 2019
                                         with_gil = cfunc_type.with_gil,
                                         nogil = cfunc_type.nogil)
2020
        return CFuncDefNode(self.pos,
2021
                            modifiers = [],
2022
                            base_type = CAnalysedBaseTypeNode(self.pos, type=cfunc_type.return_type),
2023 2024 2025
                            declarator = declarator,
                            body = self.body,
                            doc = self.doc,
2026 2027 2028 2029
                            overridable = cfunc_type.is_overridable,
                            type = cfunc_type,
                            with_gil = cfunc_type.with_gil,
                            nogil = cfunc_type.nogil,
2030
                            visibility = 'private',
2031
                            api = False,
2032
                            directive_locals = getattr(cfunc, 'directive_locals', {}))
2033

2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
    def is_cdef_func_compatible(self):
        """Determines if the function's signature is compatible with a
        cdef function.  This can be used before calling
        .as_cfunction() to see if that will be successful.
        """
        if self.needs_closure:
            return False
        if self.star_arg or self.starstar_arg:
            return False
        return True

William Stein's avatar
William Stein committed
2045
    def analyse_declarations(self, env):
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
        self.is_classmethod = self.is_staticmethod = False
        if self.decorators:
            for decorator in self.decorators:
                func = decorator.decorator
                if func.is_name:
                    self.is_classmethod |= func.name == 'classmethod'
                    self.is_staticmethod |= func.name == 'staticmethod'

        if self.is_classmethod and env.lookup_here('classmethod'):
            # classmethod() was overridden - not much we can do here ...
            self.is_classmethod = False
        if self.is_staticmethod and env.lookup_here('staticmethod'):
            # staticmethod() was overridden - not much we can do here ...
            self.is_staticmethod = False

2061
        if self.name == '__new__' and env.is_py_class_scope:
Vitja Makarov's avatar
Vitja Makarov committed
2062 2063
            self.is_staticmethod = 1

2064
        self.analyse_argument_types(env)
2065 2066 2067 2068
        if self.name == '<lambda>':
            self.declare_lambda_function(env)
        else:
            self.declare_pyfunction(env)
2069 2070 2071 2072 2073
        self.analyse_signature(env)
        self.return_type = self.entry.signature.return_type()
        self.create_local_scope(env)

    def analyse_argument_types(self, env):
2074
        directive_locals = self.directive_locals = env.directives['locals']
2075
        allow_none_for_extension_args = env.directives['allow_none_for_extension_args']
William Stein's avatar
William Stein committed
2076
        for arg in self.args:
2077 2078 2079 2080 2081 2082 2083
            if hasattr(arg, 'name'):
                name_declarator = None
            else:
                base_type = arg.base_type.analyse(env)
                name_declarator, type = \
                    arg.declarator.analyse(base_type, env)
                arg.name = name_declarator.name
2084 2085
                arg.type = type
            self.align_argument_type(env, arg)
2086
            if name_declarator and name_declarator.cname:
William Stein's avatar
William Stein committed
2087 2088
                error(self.pos,
                    "Python function argument cannot have C name specification")
2089
            arg.type = arg.type.as_argument_type()
William Stein's avatar
William Stein committed
2090 2091 2092 2093
            arg.hdr_type = None
            arg.needs_conversion = 0
            arg.needs_type_test = 0
            arg.is_generic = 1
2094
            if arg.type.is_pyobject:
2095 2096 2097 2098
                if arg.or_none:
                    arg.accept_none = True
                elif arg.not_none:
                    arg.accept_none = False
2099
                elif arg.type.is_extension_type or arg.type.is_builtin_type:
2100 2101 2102 2103 2104 2105
                    if arg.default and arg.default.constant_result is None:
                        # special case: def func(MyType obj = None)
                        arg.accept_none = True
                    else:
                        # default depends on compiler directive
                        arg.accept_none = allow_none_for_extension_args
2106 2107 2108
                else:
                    # probably just a plain 'object'
                    arg.accept_none = True
2109
            else:
2110
                arg.accept_none = True # won't be used, but must be there
2111
                if arg.not_none:
2112
                    error(arg.pos, "Only Python type arguments can have 'not None'")
2113
                if arg.or_none:
2114
                    error(arg.pos, "Only Python type arguments can have 'or None'")
2115

William Stein's avatar
William Stein committed
2116
    def analyse_signature(self, env):
2117
        if self.entry.is_special:
2118
            if self.decorators:
2119
                error(self.pos, "special functions of cdef classes cannot have decorators")
2120 2121 2122 2123
            self.entry.trivial_signature = len(self.args) == 1 and not (self.star_arg or self.starstar_arg)
        elif not env.directives['always_allow_keywords'] and not (self.star_arg or self.starstar_arg):
            # Use the simpler calling signature for zero- and one-argument functions.
            if self.entry.signature is TypeSlots.pyfunction_signature:
2124 2125
                if len(self.args) == 0:
                    self.entry.signature = TypeSlots.pyfunction_noargs
2126 2127 2128
                elif len(self.args) == 1:
                    if self.args[0].default is None and not self.args[0].kw_only:
                        self.entry.signature = TypeSlots.pyfunction_onearg
2129 2130 2131
            elif self.entry.signature is TypeSlots.pymethod_signature:
                if len(self.args) == 1:
                    self.entry.signature = TypeSlots.unaryfunc
2132 2133 2134
                elif len(self.args) == 2:
                    if self.args[1].default is None and not self.args[1].kw_only:
                        self.entry.signature = TypeSlots.ibinaryfunc
2135

William Stein's avatar
William Stein committed
2136 2137
        sig = self.entry.signature
        nfixed = sig.num_fixed_args()
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
        if sig is TypeSlots.pymethod_signature and nfixed == 1 \
               and len(self.args) == 0 and self.star_arg:
            # this is the only case where a diverging number of
            # arguments is not an error - when we have no explicit
            # 'self' parameter as in method(*args)
            sig = self.entry.signature = TypeSlots.pyfunction_signature # self is not 'really' used
            self.self_in_stararg = 1
            nfixed = 0

        for i in range(min(nfixed, len(self.args))):
            arg = self.args[i]
            arg.is_generic = 0
            if sig.is_self_arg(i) and not self.is_staticmethod:
                if self.is_classmethod:
                    arg.is_type_arg = 1
                    arg.hdr_type = arg.type = Builtin.type_type
William Stein's avatar
William Stein committed
2154
                else:
2155 2156 2157
                    arg.is_self_arg = 1
                    arg.hdr_type = arg.type = env.parent_type
                arg.needs_conversion = 0
William Stein's avatar
William Stein committed
2158
            else:
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
                arg.hdr_type = sig.fixed_arg_type(i)
                if not arg.type.same_as(arg.hdr_type):
                    if arg.hdr_type.is_pyobject and arg.type.is_pyobject:
                        arg.needs_type_test = 1
                    else:
                        arg.needs_conversion = 1
            if arg.needs_conversion:
                arg.hdr_cname = Naming.arg_prefix + arg.name
            else:
                arg.hdr_cname = Naming.var_prefix + arg.name

        if nfixed > len(self.args):
            self.bad_signature()
            return
        elif nfixed < len(self.args):
William Stein's avatar
William Stein committed
2174 2175 2176
            if not sig.has_generic_args:
                self.bad_signature()
            for arg in self.args:
Robert Bradshaw's avatar
Robert Bradshaw committed
2177 2178
                if arg.is_generic and \
                        (arg.type.is_extension_type or arg.type.is_builtin_type):
William Stein's avatar
William Stein committed
2179
                    arg.needs_type_test = 1
2180

William Stein's avatar
William Stein committed
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
    def bad_signature(self):
        sig = self.entry.signature
        expected_str = "%d" % sig.num_fixed_args()
        if sig.has_generic_args:
            expected_str = expected_str + " or more"
        name = self.name
        if name.startswith("__") and name.endswith("__"):
            desc = "Special method"
        else:
            desc = "Method"
        error(self.pos,
            "%s %s has wrong number of arguments "
            "(%d declared, %s expected)" % (
                desc, self.name, len(self.args), expected_str))
2195 2196 2197

    def signature_has_nongeneric_args(self):
        argcount = len(self.args)
2198 2199 2200
        if argcount == 0 or (
                argcount == 1 and (self.args[0].is_self_arg or
                                   self.args[0].is_type_arg)):
2201 2202 2203 2204 2205
            return 0
        return 1

    def signature_has_generic_args(self):
        return self.entry.signature.has_generic_args
2206

William Stein's avatar
William Stein committed
2207
    def declare_pyfunction(self, env):
2208 2209
        #print "DefNode.declare_pyfunction:", self.name, "in", env ###
        name = self.name
Stefan Behnel's avatar
Stefan Behnel committed
2210
        entry = env.lookup_here(name)
2211 2212
        if entry and entry.type.is_cfunction and not self.is_wrapper:
            warning(self.pos, "Overriding cdef method with def method.", 5)
2213
        entry = env.declare_pyfunction(name, self.pos, allow_redefine=not self.is_wrapper)
2214
        self.entry = entry
2215 2216
        prefix = env.next_id(env.scope_prefix)

2217
        entry.func_cname = \
2218
            Naming.pyfunc_prefix + prefix + name
2219 2220
        entry.pymethdef_cname = \
            Naming.pymethdef_prefix + prefix + name
2221 2222
        if Options.docstrings:
            entry.doc = embed_position(self.pos, self.doc)
2223 2224
            entry.doc_cname = \
                Naming.funcdoc_prefix + prefix + name
2225
            if entry.is_special:
2226
                if entry.name in TypeSlots.invisible or not entry.doc or (entry.name in '__getattr__' and env.directives['fast_getattr']):
2227 2228 2229
                    entry.wrapperbase_cname = None
                else:
                    entry.wrapperbase_cname = Naming.wrapperbase_prefix + prefix + name
2230 2231
        else:
            entry.doc = None
2232

Stefan Behnel's avatar
Stefan Behnel committed
2233
    def declare_lambda_function(self, env):
2234
        entry = env.declare_lambda_function(self.lambda_name, self.pos)
Stefan Behnel's avatar
Stefan Behnel committed
2235 2236 2237
        entry.doc = None
        self.entry = entry

William Stein's avatar
William Stein committed
2238 2239 2240 2241
    def declare_arguments(self, env):
        for arg in self.args:
            if not arg.name:
                error(arg.pos, "Missing argument name")
Robert Bradshaw's avatar
Robert Bradshaw committed
2242
            else:
2243
                env.control_flow.set_state((), (arg.name, 'source'), 'arg')
Craig Citro's avatar
Craig Citro committed
2244
                env.control_flow.set_state((), (arg.name, 'initialized'), True)
William Stein's avatar
William Stein committed
2245 2246 2247 2248 2249 2250 2251
            if arg.needs_conversion:
                arg.entry = env.declare_var(arg.name, arg.type, arg.pos)
                if arg.type.is_pyobject:
                    arg.entry.init = "0"
                arg.entry.init_to_none = 0
            else:
                arg.entry = self.declare_argument(env, arg)
2252
            arg.entry.used = 1
William Stein's avatar
William Stein committed
2253 2254
            arg.entry.is_self_arg = arg.is_self_arg
            if arg.hdr_type:
2255
                if arg.is_self_arg or arg.is_type_arg or \
William Stein's avatar
William Stein committed
2256 2257 2258 2259 2260 2261 2262
                    (arg.type.is_extension_type and not arg.hdr_type.is_extension_type):
                        arg.entry.is_declared_generic = 1
        self.declare_python_arg(env, self.star_arg)
        self.declare_python_arg(env, self.starstar_arg)

    def declare_python_arg(self, env, arg):
        if arg:
2263
            if env.directives['infer_types'] != False:
2264 2265 2266 2267
                type = PyrexTypes.unspecified_type
            else:
                type = py_object_type
            entry = env.declare_var(arg.name, type, arg.pos)
2268 2269 2270 2271 2272
            entry.used = 1
            entry.init = "0"
            entry.init_to_none = 0
            entry.xdecref_cleanup = 1
            arg.entry = entry
Craig Citro's avatar
Craig Citro committed
2273
            env.control_flow.set_state((), (arg.name, 'initialized'), True)
2274

William Stein's avatar
William Stein committed
2275
    def analyse_expressions(self, env):
2276
        self.local_scope.directives = env.directives
William Stein's avatar
William Stein committed
2277
        self.analyse_default_values(env)
2278
        if self.needs_assignment_synthesis(env):
Robert Bradshaw's avatar
Robert Bradshaw committed
2279
            # Shouldn't we be doing this at the module level too?
William Stein's avatar
William Stein committed
2280
            self.synthesize_assignment_node(env)
2281

2282
    def needs_assignment_synthesis(self, env, code=None):
2283 2284
        if self.no_assignment_synthesis:
            return False
2285
        # Should enable for module level as well, that will require more testing...
2286
        if self.entry.is_anonymous:
2287
            return True
2288 2289 2290 2291 2292 2293 2294
        if env.is_module_scope:
            if code is None:
                return env.directives['binding']
            else:
                return code.globalstate.directives['binding']
        return env.is_py_class_scope or env.is_closure_scope

William Stein's avatar
William Stein committed
2295 2296
    def synthesize_assignment_node(self, env):
        import ExprNodes
2297 2298 2299
        genv = env
        while genv.is_py_class_scope or genv.is_c_class_scope:
            genv = genv.outer_scope
Vitja Makarov's avatar
Vitja Makarov committed
2300

2301
        if genv.is_closure_scope:
Stefan Behnel's avatar
Stefan Behnel committed
2302 2303
            rhs = ExprNodes.InnerFunctionNode(
                self.pos, pymethdef_cname = self.entry.pymethdef_cname)
Robert Bradshaw's avatar
Robert Bradshaw committed
2304 2305
        else:
            rhs = ExprNodes.PyCFunctionNode(
2306
                self.pos, pymethdef_cname = self.entry.pymethdef_cname, binding = env.directives['binding'])
2307 2308 2309 2310 2311

        if env.is_py_class_scope:
            if not self.is_staticmethod and not self.is_classmethod:
                rhs.binding = True

Robert Bradshaw's avatar
Robert Bradshaw committed
2312 2313 2314
        self.assmt = SingleAssignmentNode(self.pos,
            lhs = ExprNodes.NameNode(self.pos, name = self.name),
            rhs = rhs)
William Stein's avatar
William Stein committed
2315 2316
        self.assmt.analyse_declarations(env)
        self.assmt.analyse_expressions(env)
2317

2318
    def generate_function_header(self, code, with_pymethdef, proto_only=0):
William Stein's avatar
William Stein committed
2319 2320
        arg_code_list = []
        sig = self.entry.signature
2321
        if sig.has_dummy_arg or self.self_in_stararg:
William Stein's avatar
William Stein committed
2322 2323 2324 2325
            arg_code_list.append(
                "PyObject *%s" % Naming.self_cname)
        for arg in self.args:
            if not arg.is_generic:
2326
                if arg.is_self_arg or arg.is_type_arg:
William Stein's avatar
William Stein committed
2327 2328 2329 2330
                    arg_code_list.append("PyObject *%s" % arg.hdr_cname)
                else:
                    arg_code_list.append(
                        arg.hdr_type.declaration_code(arg.hdr_cname))
2331
        if not self.entry.is_special and sig.method_flags() == [TypeSlots.method_noargs]:
2332
            arg_code_list.append("CYTHON_UNUSED PyObject *unused")
Lisandro Dalcin's avatar
Lisandro Dalcin committed
2333 2334
        if (self.entry.scope.is_c_class_scope and self.entry.name == "__ipow__"):
            arg_code_list.append("CYTHON_UNUSED PyObject *unused")
William Stein's avatar
William Stein committed
2335 2336 2337 2338 2339 2340
        if sig.has_generic_args:
            arg_code_list.append(
                "PyObject *%s, PyObject *%s"
                    % (Naming.args_cname, Naming.kwds_cname))
        arg_code = ", ".join(arg_code_list)
        dc = self.return_type.declaration_code(self.entry.func_cname)
2341 2342 2343
        mf = " ".join(self.modifiers).upper()
        if mf: mf += " "
        header = "static %s%s(%s)" % (mf, dc, arg_code)
William Stein's avatar
William Stein committed
2344
        code.putln("%s; /*proto*/" % header)
2345 2346
        if proto_only:
            return
2347
        if (Options.docstrings and self.entry.doc and
2348 2349
                not self.entry.scope.is_property_scope and
                (not self.entry.is_special or self.entry.wrapperbase_cname)):
2350
            docstr = self.entry.doc
Stefan Behnel's avatar
Stefan Behnel committed
2351
            if docstr.is_unicode:
2352
                docstr = docstr.utf8encode()
William Stein's avatar
William Stein committed
2353 2354 2355
            code.putln(
                'static char %s[] = "%s";' % (
                    self.entry.doc_cname,
2356
                    split_string_literal(escape_byte_string(docstr))))
2357 2358 2359
            if self.entry.is_special:
                code.putln(
                    "struct wrapperbase %s;" % self.entry.wrapperbase_cname)
William Stein's avatar
William Stein committed
2360 2361
        if with_pymethdef:
            code.put(
2362
                "static PyMethodDef %s = " %
William Stein's avatar
William Stein committed
2363
                    self.entry.pymethdef_cname)
2364
            code.put_pymethoddef(self.entry, ";", allow_skip=False)
William Stein's avatar
William Stein committed
2365 2366 2367 2368 2369
        code.putln("%s {" % header)

    def generate_argument_declarations(self, env, code):
        for arg in self.args:
            if arg.is_generic: # or arg.needs_conversion:
2370 2371
                if arg.needs_conversion:
                    code.putln("PyObject *%s = 0;" % arg.hdr_cname)
Robert Bradshaw's avatar
Robert Bradshaw committed
2372
                elif not arg.entry.in_closure:
2373
                    code.put_var_declaration(arg.entry)
2374

William Stein's avatar
William Stein committed
2375
    def generate_keyword_list(self, code):
2376 2377
        if self.signature_has_generic_args() and \
                self.signature_has_nongeneric_args():
William Stein's avatar
William Stein committed
2378
            code.put(
2379 2380
                "static PyObject **%s[] = {" %
                    Naming.pykwdlist_cname)
William Stein's avatar
William Stein committed
2381 2382
            for arg in self.args:
                if arg.is_generic:
2383 2384
                    pystring_cname = code.intern_identifier(arg.name)
                    code.put('&%s,' % pystring_cname)
2385
            code.putln("0};")
2386

2387
    def generate_argument_parsing_code(self, env, code):
Stefan Behnel's avatar
Stefan Behnel committed
2388 2389
        # Generate fast equivalent of PyArg_ParseTuple call for
        # generic arguments, if any, including args/kwargs
2390
        if self.entry.signature.has_dummy_arg and not self.self_in_stararg:
2391 2392 2393
            # get rid of unused argument warning
            code.putln("%s = %s;" % (Naming.self_cname, Naming.self_cname))

2394 2395
        old_error_label = code.new_error_label()
        our_error_label = code.error_label
Stefan Behnel's avatar
Stefan Behnel committed
2396
        end_label = code.new_label("argument_unpacking_done")
2397

2398 2399 2400
        has_kwonly_args = self.num_kwonly_args > 0
        has_star_or_kw_args = self.star_arg is not None \
            or self.starstar_arg is not None or has_kwonly_args
2401

2402
        for arg in self.args:
2403 2404 2405
            if not arg.type.is_pyobject:
                done = arg.type.create_from_py_utility_code(env)
                if not done: pass # will fail later
2406

2407
        if not self.signature_has_generic_args():
2408 2409
            if has_star_or_kw_args:
                error(self.pos, "This method cannot have * or keyword arguments")
2410
            self.generate_argument_conversion_code(code)
2411

2412 2413
        elif not self.signature_has_nongeneric_args():
            # func(*args) or func(**kw) or func(*args, **kw)
2414
            self.generate_stararg_copy_code(code)
2415

2416
        else:
2417
            positional_args = []
2418
            kw_only_args = []
William Stein's avatar
William Stein committed
2419 2420 2421 2422
            for arg in self.args:
                arg_entry = arg.entry
                if arg.is_generic:
                    if arg.default:
2423
                        if not arg.is_self_arg and not arg.is_type_arg:
2424 2425 2426 2427
                            if arg.kw_only:
                                kw_only_args.append(arg)
                            else:
                                positional_args.append(arg)
2428
                    elif arg.kw_only:
2429
                        kw_only_args.append(arg)
2430
                    elif not arg.is_self_arg and not arg.is_type_arg:
2431
                        positional_args.append(arg)
2432

2433
            self.generate_tuple_and_keyword_parsing_code(
2434
                positional_args, kw_only_args, end_label, code)
2435

2436 2437
        code.error_label = old_error_label
        if code.label_used(our_error_label):
2438 2439
            if not code.label_used(end_label):
                code.put_goto(end_label)
2440 2441 2442 2443 2444
            code.put_label(our_error_label)
            if has_star_or_kw_args:
                self.generate_arg_decref(self.star_arg, code)
                if self.starstar_arg:
                    if self.starstar_arg.entry.xdecref_cleanup:
2445
                        code.put_var_xdecref_clear(self.starstar_arg.entry)
2446
                    else:
2447
                        code.put_var_decref_clear(self.starstar_arg.entry)
2448
            code.putln('__Pyx_AddTraceback("%s");' % self.entry.qualified_name)
2449 2450 2451 2452 2453
            # The arguments are put into the closure one after the
            # other, so when type errors are found, all references in
            # the closure instance must be properly ref-counted to
            # facilitate generic closure instance deallocation.  In
            # the case of an argument type error, it's best to just
Stefan Behnel's avatar
Stefan Behnel committed
2454 2455
            # DECREF+clear the already handled references, as this
            # frees their references as early as possible.
2456 2457 2458 2459 2460 2461
            for arg in self.args:
                if arg.type.is_pyobject and arg.entry.in_closure:
                    code.put_var_xdecref_clear(arg.entry)
            if self.needs_closure:
                code.put_decref(Naming.cur_scope_cname, self.local_scope.scope_class.type)
            code.put_finish_refcount_context()
2462
            code.putln("return %s;" % self.error_value())
2463
        if code.label_used(end_label):
2464 2465
            code.put_label(end_label)

2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
        # fix refnanny view on closure variables here, instead of
        # doing it separately for each arg parsing special case
        if self.star_arg and self.star_arg.entry.in_closure:
            code.put_var_giveref(self.star_arg.entry)
        if self.starstar_arg and self.starstar_arg.entry.in_closure:
            code.put_var_giveref(self.starstar_arg.entry)
        for arg in self.args:
            if arg.type.is_pyobject and arg.entry.in_closure:
                code.put_var_giveref(arg.entry)

2476 2477 2478 2479
    def generate_arg_assignment(self, arg, item, code):
        if arg.type.is_pyobject:
            if arg.is_generic:
                item = PyrexTypes.typecast(arg.type, PyrexTypes.py_object_type, item)
2480 2481
            entry = arg.entry
            if entry.in_closure:
2482 2483
                code.put_incref(item, PyrexTypes.py_object_type)
            code.putln("%s = %s;" % (entry.cname, item))
2484 2485 2486 2487 2488 2489 2490 2491
        else:
            func = arg.type.from_py_function
            if func:
                code.putln("%s = %s(%s); %s" % (
                    arg.entry.cname,
                    func,
                    item,
                    code.error_goto_if(arg.type.error_condition(arg.entry.cname), arg.pos)))
2492
            else:
2493
                error(arg.pos, "Cannot convert Python object argument to type '%s'" % arg.type)
2494

William Stein's avatar
William Stein committed
2495 2496
    def generate_arg_xdecref(self, arg, code):
        if arg:
2497
            code.put_var_xdecref_clear(arg.entry)
2498

2499 2500
    def generate_arg_decref(self, arg, code):
        if arg:
2501
            code.put_var_decref_clear(arg.entry)
William Stein's avatar
William Stein committed
2502

2503 2504
    def generate_stararg_copy_code(self, code):
        if not self.star_arg:
2505 2506 2507 2508
            code.globalstate.use_utility_code(raise_argtuple_invalid_utility_code)
            code.putln("if (unlikely(PyTuple_GET_SIZE(%s) > 0)) {" %
                       Naming.args_cname)
            code.put('__Pyx_RaiseArgtupleInvalid("%s", 1, 0, 0, PyTuple_GET_SIZE(%s)); return %s;' % (
Stefan Behnel's avatar
Stefan Behnel committed
2509
                    self.name, Naming.args_cname, self.error_value()))
2510
            code.putln("}")
2511

2512 2513 2514 2515 2516 2517 2518 2519
        if self.starstar_arg:
            if self.star_arg:
                kwarg_check = "unlikely(%s)" % Naming.kwds_cname
            else:
                kwarg_check = "%s" % Naming.kwds_cname
        else:
            kwarg_check = "unlikely(%s) && unlikely(PyDict_Size(%s) > 0)" % (
                Naming.kwds_cname, Naming.kwds_cname)
2520
        code.globalstate.use_utility_code(keyword_string_check_utility_code)
2521
        code.putln(
2522 2523
            "if (%s && unlikely(!__Pyx_CheckKeywordStrings(%s, \"%s\", %d))) return %s;" % (
                kwarg_check, Naming.kwds_cname, self.name,
2524
                bool(self.starstar_arg), self.error_value()))
2525

2526
        if self.starstar_arg:
2527
            code.putln("%s = (%s) ? PyDict_Copy(%s) : PyDict_New();" % (
2528 2529 2530
                    self.starstar_arg.entry.cname,
                    Naming.kwds_cname,
                    Naming.kwds_cname))
2531 2532
            code.putln("if (unlikely(!%s)) return %s;" % (
                    self.starstar_arg.entry.cname, self.error_value()))
2533
            self.starstar_arg.entry.xdecref_cleanup = 0
2534
            code.put_gotref(self.starstar_arg.entry.cname)
2535

2536 2537 2538 2539 2540 2541 2542 2543
        if self.self_in_stararg:
            # need to create a new tuple with 'self' inserted as first item
            code.put("%s = PyTuple_New(PyTuple_GET_SIZE(%s)+1); if (unlikely(!%s)) " % (
                    self.star_arg.entry.cname,
                    Naming.args_cname,
                    self.star_arg.entry.cname))
            if self.starstar_arg:
                code.putln("{")
2544
                code.put_decref_clear(self.starstar_arg.entry.cname, py_object_type)
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
                code.putln("return %s;" % self.error_value())
                code.putln("}")
            else:
                code.putln("return %s;" % self.error_value())
            code.put_gotref(self.star_arg.entry.cname)
            code.put_incref(Naming.self_cname, py_object_type)
            code.put_giveref(Naming.self_cname)
            code.putln("PyTuple_SET_ITEM(%s, 0, %s);" % (
                self.star_arg.entry.cname, Naming.self_cname))
            temp = code.funcstate.allocate_temp(PyrexTypes.c_py_ssize_t_type, manage_ref=False)
            code.putln("for (%s=0; %s < PyTuple_GET_SIZE(%s); %s++) {" % (
                temp, temp, Naming.args_cname, temp))
            code.putln("PyObject* item = PyTuple_GET_ITEM(%s, %s);" % (
                Naming.args_cname, temp))
            code.put_incref("item", py_object_type)
            code.put_giveref("item")
            code.putln("PyTuple_SET_ITEM(%s, %s+1, item);" % (
                self.star_arg.entry.cname, temp))
            code.putln("}")
            code.funcstate.release_temp(temp)
            self.star_arg.entry.xdecref_cleanup = 0
        elif self.star_arg:
2567 2568 2569 2570 2571 2572
            code.put_incref(Naming.args_cname, py_object_type)
            code.putln("%s = %s;" % (
                    self.star_arg.entry.cname,
                    Naming.args_cname))
            self.star_arg.entry.xdecref_cleanup = 0

2573
    def generate_tuple_and_keyword_parsing_code(self, positional_args,
2574 2575
                                                kw_only_args, success_label, code):
        argtuple_error_label = code.new_label("argtuple_error")
2576

2577
        min_positional_args = self.num_required_args - self.num_required_kw_args
2578
        if len(self.args) > 0 and (self.args[0].is_self_arg or self.args[0].is_type_arg):
2579 2580
            min_positional_args -= 1
        max_positional_args = len(positional_args)
2581 2582
        has_fixed_positional_count = not self.star_arg and \
            min_positional_args == max_positional_args
2583

Stefan Behnel's avatar
Stefan Behnel committed
2584 2585 2586
        if self.num_required_kw_args:
            code.globalstate.use_utility_code(raise_keyword_required_utility_code)

2587 2588 2589 2590 2591
        if self.starstar_arg or self.star_arg:
            self.generate_stararg_init_code(max_positional_args, code)

        # --- optimised code when we receive keyword arguments
        if self.num_required_kw_args:
2592
            likely_hint = "likely"
2593
        else:
2594 2595
            likely_hint = "unlikely"
        code.putln("if (%s(%s)) {" % (likely_hint, Naming.kwds_cname))
2596 2597
        self.generate_keyword_unpacking_code(
            min_positional_args, max_positional_args,
2598
            has_fixed_positional_count,
2599 2600 2601
            positional_args, kw_only_args, argtuple_error_label, code)

        # --- optimised code when we do not receive any keyword arguments
2602
        if (self.num_required_kw_args and min_positional_args > 0) or min_positional_args == max_positional_args:
2603 2604 2605 2606 2607 2608 2609 2610 2611
            # Python raises arg tuple related errors first, so we must
            # check the length here
            if min_positional_args == max_positional_args and not self.star_arg:
                compare = '!='
            else:
                compare = '<'
            code.putln('} else if (PyTuple_GET_SIZE(%s) %s %d) {' % (
                    Naming.args_cname, compare, min_positional_args))
            code.put_goto(argtuple_error_label)
2612

2613 2614 2615 2616 2617 2618 2619 2620 2621
        if self.num_required_kw_args:
            # pure error case: keywords required but not passed
            if max_positional_args > min_positional_args and not self.star_arg:
                code.putln('} else if (PyTuple_GET_SIZE(%s) > %d) {' % (
                        Naming.args_cname, max_positional_args))
                code.put_goto(argtuple_error_label)
            code.putln('} else {')
            for i, arg in enumerate(kw_only_args):
                if not arg.default:
2622
                    pystring_cname = code.intern_identifier(arg.name)
2623
                    # required keyword-only argument missing
2624
                    code.put('__Pyx_RaiseKeywordRequired("%s", %s); ' % (
Stefan Behnel's avatar
Stefan Behnel committed
2625
                            self.name,
2626
                            pystring_cname))
2627 2628
                    code.putln(code.error_goto(self.pos))
                    break
2629

2630 2631 2632
        elif min_positional_args == max_positional_args:
            # parse the exact number of positional arguments from the
            # args tuple
2633 2634 2635 2636 2637
            code.putln('} else {')
            for i, arg in enumerate(positional_args):
                item = "PyTuple_GET_ITEM(%s, %d)" % (Naming.args_cname, i)
                self.generate_arg_assignment(arg, item, code)
            self.generate_arg_default_assignments(code)
2638

2639 2640 2641 2642
        else:
            # parse the positional arguments from the variable length
            # args tuple
            code.putln('} else {')
2643
            self.generate_arg_default_assignments(code)
2644
            code.putln('switch (PyTuple_GET_SIZE(%s)) {' % Naming.args_cname)
2645 2646
            if self.star_arg:
                code.putln('default:')
2647 2648 2649 2650 2651 2652 2653 2654 2655
            reversed_args = list(enumerate(positional_args))[::-1]
            for i, arg in reversed_args:
                if i >= min_positional_args-1:
                    if min_positional_args > 1:
                        code.putln('case %2d:' % (i+1)) # pure code beautification
                    else:
                        code.put('case %2d: ' % (i+1))
                item = "PyTuple_GET_ITEM(%s, %d)" % (Naming.args_cname, i)
                self.generate_arg_assignment(arg, item, code)
Robert Bradshaw's avatar
Robert Bradshaw committed
2656 2657 2658
            if min_positional_args == 0:
                code.put('case  0: ')
            code.putln('break;')
2659 2660 2661 2662 2663 2664
            if self.star_arg:
                if min_positional_args:
                    for i in range(min_positional_args-1, -1, -1):
                        code.putln('case %2d:' % i)
                    code.put_goto(argtuple_error_label)
            else:
2665 2666 2667 2668 2669 2670 2671 2672 2673
                code.put('default: ')
                code.put_goto(argtuple_error_label)
            code.putln('}')

        code.putln('}')

        if code.label_used(argtuple_error_label):
            code.put_goto(success_label)
            code.put_label(argtuple_error_label)
2674
            code.globalstate.use_utility_code(raise_argtuple_invalid_utility_code)
2675
            code.put('__Pyx_RaiseArgtupleInvalid("%s", %d, %d, %d, PyTuple_GET_SIZE(%s)); ' % (
Stefan Behnel's avatar
Stefan Behnel committed
2676
                    self.name, has_fixed_positional_count,
2677 2678 2679 2680
                    min_positional_args, max_positional_args,
                    Naming.args_cname))
            code.putln(code.error_goto(self.pos))

2681 2682 2683 2684 2685 2686
    def generate_arg_default_assignments(self, code):
        for arg in self.args:
            if arg.is_generic and arg.default:
                code.putln(
                    "%s = %s;" % (
                        arg.entry.cname,
2687
                        arg.calculate_default_value_code(code)))
2688

2689
    def generate_stararg_init_code(self, max_positional_args, code):
2690
        if self.starstar_arg:
2691
            self.starstar_arg.entry.xdecref_cleanup = 0
Stefan Behnel's avatar
Stefan Behnel committed
2692 2693 2694 2695
            code.putln('%s = PyDict_New(); if (unlikely(!%s)) return %s;' % (
                    self.starstar_arg.entry.cname,
                    self.starstar_arg.entry.cname,
                    self.error_value()))
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2696
            code.put_gotref(self.starstar_arg.entry.cname)
Stefan Behnel's avatar
Stefan Behnel committed
2697 2698 2699 2700 2701
        if self.star_arg:
            self.star_arg.entry.xdecref_cleanup = 0
            code.putln('if (PyTuple_GET_SIZE(%s) > %d) {' % (
                    Naming.args_cname,
                    max_positional_args))
2702
            code.putln('%s = PyTuple_GetSlice(%s, %d, PyTuple_GET_SIZE(%s));' % (
Stefan Behnel's avatar
Stefan Behnel committed
2703 2704
                    self.star_arg.entry.cname, Naming.args_cname,
                    max_positional_args, Naming.args_cname))
2705
            code.putln("if (unlikely(!%s)) {" % self.star_arg.entry.cname)
Stefan Behnel's avatar
Stefan Behnel committed
2706
            if self.starstar_arg:
2707
                code.put_decref_clear(self.starstar_arg.entry.cname, py_object_type)
2708 2709
            if self.needs_closure:
                code.put_decref(Naming.cur_scope_cname, self.local_scope.scope_class.type)
2710 2711 2712 2713
            code.put_finish_refcount_context()
            code.putln('return %s;' % self.error_value())
            code.putln('}')
            code.put_gotref(self.star_arg.entry.cname)
Stefan Behnel's avatar
Stefan Behnel committed
2714 2715 2716 2717
            code.putln('} else {')
            code.put("%s = %s; " % (self.star_arg.entry.cname, Naming.empty_tuple))
            code.put_incref(Naming.empty_tuple, py_object_type)
            code.putln('}')
2718

2719
    def generate_keyword_unpacking_code(self, min_positional_args, max_positional_args,
2720 2721
                                        has_fixed_positional_count, positional_args,
                                        kw_only_args, argtuple_error_label, code):
2722 2723 2724
        all_args = tuple(positional_args) + tuple(kw_only_args)
        max_args = len(all_args)

2725 2726
        code.putln("Py_ssize_t kw_args = PyDict_Size(%s);" %
                   Naming.kwds_cname)
Stefan Behnel's avatar
Stefan Behnel committed
2727 2728
        # the 'values' array collects borrowed references to arguments
        # before doing any type coercion etc.
2729
        code.putln("PyObject* values[%d] = {%s};" % (
Stefan Behnel's avatar
Stefan Behnel committed
2730
            max_args, ','.join('0'*max_args)))
2731

2732 2733 2734 2735 2736 2737 2738 2739
        # assign borrowed Python default values to the values array,
        # so that they can be overwritten by received arguments below
        for i, arg in enumerate(all_args):
            if arg.default and arg.type.is_pyobject:
                default_value = arg.calculate_default_value_code(code)
                code.putln('values[%d] = %s;' % (i, arg.type.as_pyobject(default_value)))

        # parse the args tuple and check that it's not too long
2740
        code.putln('switch (PyTuple_GET_SIZE(%s)) {' % Naming.args_cname)
Stefan Behnel's avatar
Stefan Behnel committed
2741 2742
        if self.star_arg:
            code.putln('default:')
2743
        for i in range(max_positional_args-1, -1, -1):
2744
            code.put('case %2d: ' % (i+1))
2745 2746
            code.putln("values[%d] = PyTuple_GET_ITEM(%s, %d);" % (
                    i, Naming.args_cname, i))
2747
        code.putln('case  0: break;')
2748
        if not self.star_arg:
Stefan Behnel's avatar
Stefan Behnel committed
2749
            code.put('default: ') # more arguments than allowed
2750
            code.put_goto(argtuple_error_label)
2751 2752
        code.putln('}')

Stefan Behnel's avatar
Stefan Behnel committed
2753 2754
        # now fill up the positional/required arguments with values
        # from the kw dict
2755
        if self.num_required_args or max_positional_args > 0:
Stefan Behnel's avatar
Stefan Behnel committed
2756 2757 2758 2759
            last_required_arg = -1
            for i, arg in enumerate(all_args):
                if not arg.default:
                    last_required_arg = i
2760 2761 2762
            if last_required_arg < max_positional_args:
                last_required_arg = max_positional_args-1
            num_required_args = self.num_required_args
Stefan Behnel's avatar
Stefan Behnel committed
2763 2764
            if max_positional_args > 0:
                code.putln('switch (PyTuple_GET_SIZE(%s)) {' % Naming.args_cname)
2765
            for i, arg in enumerate(all_args[:last_required_arg+1]):
Stefan Behnel's avatar
Stefan Behnel committed
2766
                if max_positional_args > 0 and i <= max_positional_args:
2767 2768 2769 2770
                    if self.star_arg and i == max_positional_args:
                        code.putln('default:')
                    else:
                        code.putln('case %2d:' % i)
2771
                pystring_cname = code.intern_identifier(arg.name)
2772
                if arg.default:
2773 2774 2775
                    if arg.kw_only:
                        # handled separately below
                        continue
2776
                    code.putln('if (kw_args > 0) {')
2777
                    code.putln('PyObject* value = PyDict_GetItem(%s, %s);' % (
2778
                        Naming.kwds_cname, pystring_cname))
2779
                    code.putln('if (value) { values[%d] = value; kw_args--; }' % i)
2780 2781 2782 2783
                    code.putln('}')
                else:
                    num_required_args -= 1
                    code.putln('values[%d] = PyDict_GetItem(%s, %s);' % (
2784
                        i, Naming.kwds_cname, pystring_cname))
2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795
                    code.putln('if (likely(values[%d])) kw_args--;' % i);
                    if i < min_positional_args:
                        if i == 0:
                            # special case: we know arg 0 is missing
                            code.put('else ')
                            code.put_goto(argtuple_error_label)
                        else:
                            # print the correct number of values (args or
                            # kwargs) that were passed into positional
                            # arguments up to this point
                            code.putln('else {')
2796
                            code.globalstate.use_utility_code(raise_argtuple_invalid_utility_code)
2797
                            code.put('__Pyx_RaiseArgtupleInvalid("%s", %d, %d, %d, %d); ' % (
Stefan Behnel's avatar
Stefan Behnel committed
2798
                                    self.name, has_fixed_positional_count,
2799 2800 2801 2802
                                    min_positional_args, max_positional_args, i))
                            code.putln(code.error_goto(self.pos))
                            code.putln('}')
                    elif arg.kw_only:
2803
                        code.putln('else {')
2804
                        code.put('__Pyx_RaiseKeywordRequired("%s", %s); ' %(
Stefan Behnel's avatar
Stefan Behnel committed
2805
                                self.name, pystring_cname))
2806 2807
                        code.putln(code.error_goto(self.pos))
                        code.putln('}')
Stefan Behnel's avatar
Stefan Behnel committed
2808 2809
            if max_positional_args > 0:
                code.putln('}')
2810

2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
        if kw_only_args and not self.starstar_arg:
            # unpack optional keyword-only arguments
            # checking for interned strings in a dict is faster than iterating
            # but it's too likely that we must iterate if we expect **kwargs
            optional_args = []
            for i, arg in enumerate(all_args[max_positional_args:]):
                if not arg.kw_only or not arg.default:
                    continue
                optional_args.append((i+max_positional_args, arg))
            if optional_args:
                # this mimics an unrolled loop so that we can "break" out of it
                code.putln('while (kw_args > 0) {')
                code.putln('PyObject* value;')
                for i, arg in optional_args:
2825
                    pystring_cname = code.intern_identifier(arg.name)
2826 2827
                    code.putln(
                        'value = PyDict_GetItem(%s, %s);' % (
2828
                        Naming.kwds_cname, pystring_cname))
2829 2830 2831 2832 2833
                    code.putln(
                        'if (value) { values[%d] = value; if (!(--kw_args)) break; }' % i)
                code.putln('break;')
                code.putln('}')

2834
        code.putln('if (unlikely(kw_args > 0)) {')
2835 2836
        # non-positional/-required kw args left in dict: default args,
        # kw-only args, **kwargs or error
Stefan Behnel's avatar
Stefan Behnel committed
2837 2838 2839 2840 2841
        #
        # This is sort of a catch-all: except for checking required
        # arguments, this will always do the right thing for unpacking
        # keyword arguments, so that we can concentrate on optimising
        # common cases above.
2842 2843 2844
        if max_positional_args == 0:
            pos_arg_count = "0"
        elif self.star_arg:
Stefan Behnel's avatar
Stefan Behnel committed
2845 2846 2847 2848 2849 2850
            code.putln("const Py_ssize_t used_pos_args = (PyTuple_GET_SIZE(%s) < %d) ? PyTuple_GET_SIZE(%s) : %d;" % (
                    Naming.args_cname, max_positional_args,
                    Naming.args_cname, max_positional_args))
            pos_arg_count = "used_pos_args"
        else:
            pos_arg_count = "PyTuple_GET_SIZE(%s)" % Naming.args_cname
2851
        code.globalstate.use_utility_code(parse_keywords_utility_code)
Stefan Behnel's avatar
Stefan Behnel committed
2852
        code.put(
2853
            'if (unlikely(__Pyx_ParseOptionalKeywords(%s, %s, %s, values, %s, "%s") < 0)) ' % (
Stefan Behnel's avatar
Stefan Behnel committed
2854 2855 2856 2857
                Naming.kwds_cname,
                Naming.pykwdlist_cname,
                self.starstar_arg and self.starstar_arg.entry.cname or '0',
                pos_arg_count,
Stefan Behnel's avatar
Stefan Behnel committed
2858
                self.name))
2859
        code.putln(code.error_goto(self.pos))
2860
        code.putln('}')
2861

2862
        # convert arg values to their final type and assign them
2863
        for i, arg in enumerate(all_args):
2864
            if arg.default and not arg.type.is_pyobject:
2865 2866
                code.putln("if (values[%d]) {" % i)
            self.generate_arg_assignment(arg, "values[%d]" % i, code)
2867
            if arg.default and not arg.type.is_pyobject:
2868 2869 2870 2871
                code.putln('} else {')
                code.putln(
                    "%s = %s;" % (
                        arg.entry.cname,
2872
                        arg.calculate_default_value_code(code)))
2873
                code.putln('}')
2874

William Stein's avatar
William Stein committed
2875
    def generate_argument_conversion_code(self, code):
2876 2877 2878
        # Generate code to convert arguments from signature type to
        # declared type, if needed.  Also copies signature arguments
        # into closure fields.
William Stein's avatar
William Stein committed
2879 2880 2881
        for arg in self.args:
            if arg.needs_conversion:
                self.generate_arg_conversion(arg, code)
2882
            elif arg.entry.in_closure:
2883
                if arg.type.is_pyobject:
Stefan Behnel's avatar
Stefan Behnel committed
2884 2885
                    code.put_incref(arg.hdr_cname, py_object_type)
                code.putln('%s = %s;' % (arg.entry.cname, arg.hdr_cname))
William Stein's avatar
William Stein committed
2886 2887 2888 2889 2890 2891

    def generate_arg_conversion(self, arg, code):
        # Generate conversion code for one argument.
        old_type = arg.hdr_type
        new_type = arg.type
        if old_type.is_pyobject:
Robert Bradshaw's avatar
Robert Bradshaw committed
2892 2893 2894 2895
            if arg.default:
                code.putln("if (%s) {" % arg.hdr_cname)
            else:
                code.putln("assert(%s); {" % arg.hdr_cname)
William Stein's avatar
William Stein committed
2896
            self.generate_arg_conversion_from_pyobject(arg, code)
Robert Bradshaw's avatar
Robert Bradshaw committed
2897
            code.putln("}")
William Stein's avatar
William Stein committed
2898 2899 2900 2901 2902 2903 2904 2905
        elif new_type.is_pyobject:
            self.generate_arg_conversion_to_pyobject(arg, code)
        else:
            if new_type.assignable_from(old_type):
                code.putln(
                    "%s = %s;" % (arg.entry.cname, arg.hdr_cname))
            else:
                error(arg.pos,
2906
                    "Cannot convert 1 argument from '%s' to '%s'" %
William Stein's avatar
William Stein committed
2907
                        (old_type, new_type))
2908

William Stein's avatar
William Stein committed
2909 2910 2911
    def generate_arg_conversion_from_pyobject(self, arg, code):
        new_type = arg.type
        func = new_type.from_py_function
2912
        # copied from CoerceFromPyTypeNode
William Stein's avatar
William Stein committed
2913
        if func:
2914 2915 2916 2917 2918
            lhs = arg.entry.cname
            rhs = "%s(%s)" % (func, arg.hdr_cname)
            if new_type.is_enum:
                rhs = PyrexTypes.typecast(new_type, PyrexTypes.c_long_type, rhs)
            code.putln("%s = %s; %s" % (
2919
                lhs,
2920
                rhs,
2921
                code.error_goto_if(new_type.error_condition(arg.entry.cname), arg.pos)))
William Stein's avatar
William Stein committed
2922
        else:
2923 2924
            error(arg.pos,
                "Cannot convert Python object argument to type '%s'"
William Stein's avatar
William Stein committed
2925
                    % new_type)
2926

William Stein's avatar
William Stein committed
2927 2928 2929 2930
    def generate_arg_conversion_to_pyobject(self, arg, code):
        old_type = arg.hdr_type
        func = old_type.to_py_function
        if func:
Robert Bradshaw's avatar
Robert Bradshaw committed
2931
            code.putln("%s = %s(%s); %s" % (
William Stein's avatar
William Stein committed
2932 2933 2934
                arg.entry.cname,
                func,
                arg.hdr_cname,
Robert Bradshaw's avatar
Robert Bradshaw committed
2935
                code.error_goto_if_null(arg.entry.cname, arg.pos)))
2936
            code.put_var_gotref(arg.entry)
William Stein's avatar
William Stein committed
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
        else:
            error(arg.pos,
                "Cannot convert argument of type '%s' to Python object"
                    % old_type)

    def generate_argument_type_tests(self, code):
        # Generate type tests for args whose signature
        # type is PyObject * and whose declared type is
        # a subtype thereof.
        for arg in self.args:
            if arg.needs_type_test:
                self.generate_arg_type_test(arg, code)
2949 2950 2951
            elif not arg.accept_none and arg.type.is_pyobject:
                self.generate_arg_none_check(arg, code)

William Stein's avatar
William Stein committed
2952 2953
    def error_value(self):
        return self.entry.signature.error_value
2954

William Stein's avatar
William Stein committed
2955 2956
    def caller_will_check_exceptions(self):
        return 1
2957

2958 2959 2960 2961 2962 2963 2964 2965 2966 2967

class GeneratorDefNode(DefNode):
    # Generator DefNode.
    #
    # gbody          GeneratorBodyDefNode
    #

    is_generator = True
    needs_closure = True

Stefan Behnel's avatar
Stefan Behnel committed
2968
    child_attrs = DefNode.child_attrs + ["gbody"]
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001

    def __init__(self, **kwargs):
        # XXX: don't actually needs a body
        kwargs['body'] = StatListNode(kwargs['pos'], stats=[])
        super(GeneratorDefNode, self).__init__(**kwargs)

    def analyse_declarations(self, env):
        super(GeneratorDefNode, self).analyse_declarations(env)
        self.gbody.local_scope = self.local_scope
        self.gbody.analyse_declarations(env)

    def generate_function_body(self, env, code):
        body_cname = self.gbody.entry.func_cname
        generator_cname = '%s->%s' % (Naming.cur_scope_cname, Naming.obj_base_cname)

        code.putln('%s.resume_label = 0;' % generator_cname)
        code.putln('%s.body = (__pyx_generator_body_t) %s;' % (generator_cname, body_cname))
        code.put_giveref(Naming.cur_scope_cname)
        code.put_finish_refcount_context()
        code.putln("return (PyObject *) %s;" % Naming.cur_scope_cname);

    def generate_function_definitions(self, env, code):
        self.gbody.generate_function_header(code, proto=True)
        super(GeneratorDefNode, self).generate_function_definitions(env, code)
        self.gbody.generate_function_definitions(env, code)


class GeneratorBodyDefNode(DefNode):
    # Generator body DefNode.
    #

    is_generator_body = True

3002
    def __init__(self, pos=None, name=None, body=None):
3003 3004 3005 3006
        super(GeneratorBodyDefNode, self).__init__(pos=pos, body=body, name=name, doc=None,
                                                   args=[],
                                                   star_arg=None, starstar_arg=None)

3007 3008
    def declare_generator_body(self, env):
        prefix = env.next_id(env.scope_prefix)
Vitja Makarov's avatar
Vitja Makarov committed
3009 3010 3011
        name = env.next_id('generator')
        entry = env.declare_var(prefix + name, py_object_type, self.pos, visibility='private')
        entry.func_cname = Naming.genbody_prefix + prefix + name
3012 3013 3014 3015 3016 3017
        entry.qualified_name = EncodedString(self.name)
        self.entry = entry

    def analyse_declarations(self, env):
        self.analyse_argument_types(env)
        self.declare_generator_body(env)
3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072

    def generate_function_header(self, code, proto=False):
        header = "static PyObject *%s(%s, PyObject *%s)" % (
            self.entry.func_cname,
            self.local_scope.scope_class.type.declaration_code(Naming.cur_scope_cname),
            Naming.sent_value_cname)
        if proto:
            code.putln('%s; /* proto */' % header)
        else:
            code.putln('%s /* generator body */\n{' % header);

    def generate_function_definitions(self, env, code):
        lenv = self.local_scope

        # Generate closure function definitions
        self.body.generate_function_definitions(lenv, code)

        # Generate C code for header and body of function
        code.enter_cfunc_scope()
        code.return_from_error_cleanup_label = code.new_label()

        # ----- Top-level constants used by this function
        code.mark_pos(self.pos)
        self.generate_cached_builtins_decls(lenv, code)
        # ----- Function header
        code.putln("")
        self.generate_function_header(code)
        # ----- Local variables
        code.putln("PyObject *%s = NULL;" % Naming.retval_cname)
        tempvardecl_code = code.insertion_point()
        code.put_declare_refcount_context()
        code.put_setup_refcount_context(self.entry.name)

        # ----- Resume switch point.
        code.funcstate.init_closure_temps(lenv.scope_class.type.scope)
        resume_code = code.insertion_point()
        first_run_label = code.new_label('first_run')
        code.use_label(first_run_label)
        code.put_label(first_run_label)
        code.putln('%s' %
                   (code.error_goto_if_null(Naming.sent_value_cname, self.pos)))

        # ----- Function body
        self.generate_function_body(env, code)
        code.putln('PyErr_SetNone(PyExc_StopIteration); %s' % code.error_goto(self.pos))
        # ----- Error cleanup
        if code.error_label in code.labels_used:
            code.put_goto(code.return_label)
            code.put_label(code.error_label)
            for cname, type in code.funcstate.all_managed_temps():
                code.put_xdecref(cname, type)
            code.putln('__Pyx_AddTraceback("%s");' % self.entry.qualified_name)

        # ----- Non-error return cleanup
        code.put_label(code.return_label)
3073
        code.put_xdecref(Naming.retval_cname, py_object_type)
3074 3075 3076 3077 3078 3079 3080 3081 3082 3083
        code.putln('%s->%s.resume_label = -1;' % (Naming.cur_scope_cname, Naming.obj_base_cname))
        code.put_finish_refcount_context()
        code.putln('return NULL;');
        code.putln("}")

        # ----- Go back and insert temp variable declarations
        tempvardecl_code.put_temp_declarations(code.funcstate)
        # ----- Generator resume code
        resume_code.putln("switch (%s->%s.resume_label) {" % (Naming.cur_scope_cname, Naming.obj_base_cname));
        resume_code.putln("case 0: goto %s;" % first_run_label)
3084 3085 3086 3087 3088

        from ParseTreeTransforms import YieldNodeCollector
        collector = YieldNodeCollector()
        collector.visitchildren(self)
        for yield_expr in collector.yields:
3089 3090 3091 3092 3093 3094 3095 3096 3097
            resume_code.putln("case %d: goto %s;" % (yield_expr.label_num, yield_expr.label_name));
        resume_code.putln("default: /* CPython raises the right error here */");
        resume_code.put_finish_refcount_context()
        resume_code.putln("return NULL;");
        resume_code.putln("}");

        code.exit_cfunc_scope()


3098 3099
class OverrideCheckNode(StatNode):
    # A Node for dispatching to the def method if it
3100
    # is overriden.
3101 3102 3103 3104 3105 3106
    #
    #  py_func
    #
    #  args
    #  func_temp
    #  body
3107

Robert Bradshaw's avatar
Robert Bradshaw committed
3108
    child_attrs = ['body']
3109

3110
    body = None
Robert Bradshaw's avatar
Robert Bradshaw committed
3111

3112 3113
    def analyse_expressions(self, env):
        self.args = env.arg_entries
3114 3115 3116 3117
        if self.py_func.is_module_scope:
            first_arg = 0
        else:
            first_arg = 1
3118
        import ExprNodes
3119
        self.func_node = ExprNodes.RawCNameExprNode(self.pos, py_object_type)
3120
        call_tuple = ExprNodes.TupleNode(self.pos, args=[ExprNodes.NameNode(self.pos, name=arg.name) for arg in self.args[first_arg:]])
3121
        call_node = ExprNodes.SimpleCallNode(self.pos,
3122
                                             function=self.func_node,
3123
                                             args=[ExprNodes.NameNode(self.pos, name=arg.name) for arg in self.args[first_arg:]])
3124 3125
        self.body = ReturnStatNode(self.pos, value=call_node)
        self.body.analyse_expressions(env)
3126

3127
    def generate_execution_code(self, code):
3128
        interned_attr_cname = code.intern_identifier(self.py_func.entry.name)
3129
        # Check to see if we are an extension type
3130 3131 3132 3133
        if self.py_func.is_module_scope:
            self_arg = "((PyObject *)%s)" % Naming.module_cname
        else:
            self_arg = "((PyObject *)%s)" % self.args[0].cname
3134
        code.putln("/* Check if called by wrapper */")
3135
        code.putln("if (unlikely(%s)) ;" % Naming.skip_dispatch_cname)
3136
        code.putln("/* Check if overriden in Python */")
3137 3138 3139
        if self.py_func.is_module_scope:
            code.putln("else {")
        else:
3140
            code.putln("else if (unlikely(Py_TYPE(%s)->tp_dictoffset != 0)) {" % self_arg)
3141 3142
        func_node_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
        self.func_node.set_cname(func_node_temp)
3143
        # need to get attribute manually--scope would return cdef method
3144
        err = code.error_goto_if_null(func_node_temp, self.pos)
3145
        code.putln("%s = PyObject_GetAttr(%s, %s); %s" % (
3146 3147 3148
            func_node_temp, self_arg, interned_attr_cname, err))
        code.put_gotref(func_node_temp)
        is_builtin_function_or_method = "PyCFunction_Check(%s)" % func_node_temp
Robert Bradshaw's avatar
Robert Bradshaw committed
3149
        is_overridden = "(PyCFunction_GET_FUNCTION(%s) != (void *)&%s)" % (
3150
            func_node_temp, self.py_func.entry.func_cname)
Robert Bradshaw's avatar
Robert Bradshaw committed
3151
        code.putln("if (!%s || %s) {" % (is_builtin_function_or_method, is_overridden))
3152 3153
        self.body.generate_execution_code(code)
        code.putln("}")
3154 3155
        code.put_decref_clear(func_node_temp, PyrexTypes.py_object_type)
        code.funcstate.release_temp(func_node_temp)
Robert Bradshaw's avatar
Robert Bradshaw committed
3156
        code.putln("}")
3157

Robert Bradshaw's avatar
Robert Bradshaw committed
3158 3159
class ClassDefNode(StatNode, BlockNode):
    pass
3160

Robert Bradshaw's avatar
Robert Bradshaw committed
3161
class PyClassDefNode(ClassDefNode):
William Stein's avatar
William Stein committed
3162 3163
    #  A Python class definition.
    #
Stefan Behnel's avatar
Stefan Behnel committed
3164
    #  name     EncodedString   Name of the class
William Stein's avatar
William Stein committed
3165 3166 3167 3168
    #  doc      string or None
    #  body     StatNode        Attribute definition code
    #  entry    Symtab.Entry
    #  scope    PyClassScope
3169
    #  decorators    [DecoratorNode]        list of decorators or None
William Stein's avatar
William Stein committed
3170 3171 3172
    #
    #  The following subnodes are constructed internally:
    #
3173
    #  dict     DictNode   Class dictionary or Py3 namespace
William Stein's avatar
William Stein committed
3174 3175
    #  classobj ClassNode  Class object
    #  target   NameNode   Variable to assign class object to
3176

3177
    child_attrs = ["body", "dict", "metaclass", "mkw", "bases", "classobj", "target"]
3178
    decorators = None
Stefan Behnel's avatar
Stefan Behnel committed
3179
    py3_style_class = False # Python3 style class (bases+kwargs)
3180

3181 3182
    def __init__(self, pos, name, bases, doc, body, decorators = None,
                 keyword_args = None, starstar_arg = None):
William Stein's avatar
William Stein committed
3183 3184 3185 3186
        StatNode.__init__(self, pos)
        self.name = name
        self.doc = doc
        self.body = body
3187
        self.decorators = decorators
William Stein's avatar
William Stein committed
3188
        import ExprNodes
3189
        if self.doc and Options.docstrings:
3190
            doc = embed_position(self.pos, self.doc)
3191
            doc_node = ExprNodes.StringNode(pos, value = doc)
William Stein's avatar
William Stein committed
3192 3193
        else:
            doc_node = None
3194 3195
        if keyword_args or starstar_arg:
            self.py3_style_class = True
3196
            self.bases = bases
3197
            self.metaclass = None
3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
            if keyword_args and not starstar_arg:
                for i, item in list(enumerate(keyword_args.key_value_pairs))[::-1]:
                    if item.key.value == 'metaclass':
                        if self.metaclass is not None:
                            error(item.pos, "keyword argument 'metaclass' passed multiple times")
                        # special case: we already know the metaclass,
                        # so we don't need to do the "build kwargs,
                        # find metaclass" dance at runtime
                        self.metaclass = item.value
                        del keyword_args.key_value_pairs[i]
            if starstar_arg or (keyword_args and keyword_args.key_value_pairs):
3209 3210
                self.mkw = ExprNodes.KeywordArgsNode(
                    pos, keyword_args = keyword_args, starstar_arg = starstar_arg)
3211 3212 3213
            else:
                self.mkw = ExprNodes.NullNode(pos)
            if self.metaclass is None:
3214 3215
                self.metaclass = ExprNodes.PyClassMetaclassNode(
                    pos, mkw = self.mkw, bases = self.bases)
3216 3217
            self.dict = ExprNodes.PyClassNamespaceNode(pos, name = name,
                        doc = doc_node, metaclass = self.metaclass, bases = self.bases,
3218
                        mkw = self.mkw)
3219 3220 3221 3222 3223 3224 3225 3226 3227 3228
            self.classobj = ExprNodes.Py3ClassNode(pos, name = name,
                    bases = self.bases, dict = self.dict, doc = doc_node,
                    metaclass = self.metaclass, mkw = self.mkw)
        else:
            self.dict = ExprNodes.DictNode(pos, key_value_pairs = [])
            self.metaclass = None
            self.mkw = None
            self.bases = None
            self.classobj = ExprNodes.ClassNode(pos, name = name,
                    bases = bases, dict = self.dict, doc = doc_node)
William Stein's avatar
William Stein committed
3229
        self.target = ExprNodes.NameNode(pos, name = name)
3230

3231 3232
    def as_cclass(self):
        """
3233
        Return this node as if it were declared as an extension class
3234
        """
3235 3236 3237
        if self.py3_style_class:
            error(self.classobj.pos, "Python3 style class could not be represented as C class")
            return
3238 3239 3240 3241 3242 3243 3244
        bases = self.classobj.bases.args
        if len(bases) == 0:
            base_class_name = None
            base_class_module = None
        elif len(bases) == 1:
            base = bases[0]
            path = []
3245 3246
            from ExprNodes import AttributeNode, NameNode
            while isinstance(base, AttributeNode):
3247 3248
                path.insert(0, base.attribute)
                base = base.obj
3249
            if isinstance(base, NameNode):
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260
                path.insert(0, base.name)
                base_class_name = path[-1]
                if len(path) > 1:
                    base_class_module = u'.'.join(path[:-1])
                else:
                    base_class_module = None
            else:
                error(self.classobj.bases.args.pos, "Invalid base class")
        else:
            error(self.classobj.bases.args.pos, "C class may only have one base class")
            return None
3261 3262

        return CClassDefNode(self.pos,
3263 3264 3265 3266 3267
                             visibility = 'private',
                             module_name = None,
                             class_name = self.name,
                             base_class_module = base_class_module,
                             base_class_name = base_class_name,
3268
                             decorators = self.decorators,
3269 3270 3271
                             body = self.body,
                             in_pxd = False,
                             doc = self.doc)
3272

3273 3274
    def create_scope(self, env):
        genv = env
3275 3276
        while genv.is_py_class_scope or genv.is_c_class_scope:
            genv = genv.outer_scope
3277 3278
        cenv = self.scope = PyClassScope(name = self.name, outer_scope = genv)
        return cenv
3279

William Stein's avatar
William Stein committed
3280 3281
    def analyse_declarations(self, env):
        self.target.analyse_target_declaration(env)
3282
        cenv = self.create_scope(env)
3283
        cenv.directives = env.directives
3284 3285
        cenv.class_obj_cname = self.target.entry.cname
        self.body.analyse_declarations(cenv)
3286

William Stein's avatar
William Stein committed
3287
    def analyse_expressions(self, env):
3288 3289 3290 3291
        if self.py3_style_class:
            self.bases.analyse_expressions(env)
            self.metaclass.analyse_expressions(env)
            self.mkw.analyse_expressions(env)
William Stein's avatar
William Stein committed
3292
        self.dict.analyse_expressions(env)
3293
        self.classobj.analyse_expressions(env)
William Stein's avatar
William Stein committed
3294
        genv = env.global_scope()
3295
        cenv = self.scope
William Stein's avatar
William Stein committed
3296
        self.body.analyse_expressions(cenv)
3297
        self.target.analyse_target_expression(env, self.classobj)
3298

3299
    def generate_function_definitions(self, env, code):
3300
        self.generate_lambda_definitions(self.scope, code)
3301
        self.body.generate_function_definitions(self.scope, code)
3302

William Stein's avatar
William Stein committed
3303
    def generate_execution_code(self, code):
3304 3305
        code.pyclass_stack.append(self)
        cenv = self.scope
3306 3307 3308 3309
        if self.py3_style_class:
            self.bases.generate_evaluation_code(code)
            self.mkw.generate_evaluation_code(code)
            self.metaclass.generate_evaluation_code(code)
William Stein's avatar
William Stein committed
3310
        self.dict.generate_evaluation_code(code)
Vitja Makarov's avatar
Vitja Makarov committed
3311 3312
        cenv.namespace_cname = cenv.class_obj_cname = self.dict.result()
        self.body.generate_execution_code(code)
3313
        self.classobj.generate_evaluation_code(code)
3314
        cenv.namespace_cname = cenv.class_obj_cname = self.classobj.result()
3315
        self.target.generate_assignment_code(self.classobj, code)
William Stein's avatar
William Stein committed
3316
        self.dict.generate_disposal_code(code)
3317
        self.dict.free_temps(code)
3318 3319 3320 3321 3322 3323 3324
        if self.py3_style_class:
            self.mkw.generate_disposal_code(code)
            self.mkw.free_temps(code)
            self.metaclass.generate_disposal_code(code)
            self.metaclass.free_temps(code)
            self.bases.generate_disposal_code(code)
            self.bases.free_temps(code)
3325
        code.pyclass_stack.pop()
William Stein's avatar
William Stein committed
3326

Robert Bradshaw's avatar
Robert Bradshaw committed
3327
class CClassDefNode(ClassDefNode):
William Stein's avatar
William Stein committed
3328 3329 3330 3331
    #  An extension type definition.
    #
    #  visibility         'private' or 'public' or 'extern'
    #  typedef_flag       boolean
Stefan Behnel's avatar
Stefan Behnel committed
3332
    #  api                boolean
William Stein's avatar
William Stein committed
3333 3334 3335 3336 3337 3338 3339 3340
    #  module_name        string or None    For import of extern type objects
    #  class_name         string            Unqualified name of class
    #  as_name            string or None    Name to declare as in this scope
    #  base_class_module  string or None    Module containing the base class
    #  base_class_name    string or None    Name of the base class
    #  objstruct_name     string or None    Specified C name of object struct
    #  typeobj_name       string or None    Specified C name of type object
    #  in_pxd             boolean           Is in a .pxd file
3341
    #  decorators         [DecoratorNode]   list of decorators or None
William Stein's avatar
William Stein committed
3342 3343 3344 3345
    #  doc                string or None
    #  body               StatNode or None
    #  entry              Symtab.Entry
    #  base_type          PyExtensionType or None
3346 3347
    #  buffer_defaults_node DictNode or None Declares defaults for a buffer
    #  buffer_defaults_pos
3348

3349
    child_attrs = ["body"]
3350 3351
    buffer_defaults_node = None
    buffer_defaults_pos = None
3352 3353 3354 3355
    typedef_flag = False
    api = False
    objstruct_name = None
    typeobj_name = None
3356
    decorators = None
3357
    shadow = False
3358

William Stein's avatar
William Stein committed
3359 3360 3361 3362
    def analyse_declarations(self, env):
        #print "CClassDefNode.analyse_declarations:", self.class_name
        #print "...visibility =", self.visibility
        #print "...module_name =", self.module_name
3363 3364 3365 3366 3367 3368 3369 3370 3371

        import Buffer
        if self.buffer_defaults_node:
            buffer_defaults = Buffer.analyse_buffer_options(self.buffer_defaults_pos,
                                                            env, [], self.buffer_defaults_node,
                                                            need_complete=False)
        else:
            buffer_defaults = None

William Stein's avatar
William Stein committed
3372 3373 3374 3375
        if env.in_cinclude and not self.objstruct_name:
            error(self.pos, "Object struct name specification required for "
                "C class defined in 'extern from' block")
        self.base_type = None
3376 3377
        # Now that module imports are cached, we need to
        # import the modules for extern classes.
3378 3379 3380 3381 3382 3383 3384
        if self.module_name:
            self.module = None
            for module in env.cimported_modules:
                if module.name == self.module_name:
                    self.module = module
            if self.module is None:
                self.module = ModuleScope(self.module_name, None, env.context)
3385
                self.module.has_extern_class = 1
Robert Bradshaw's avatar
Robert Bradshaw committed
3386
                env.add_imported_module(self.module)
3387

William Stein's avatar
William Stein committed
3388 3389 3390 3391 3392
        if self.base_class_name:
            if self.base_class_module:
                base_class_scope = env.find_module(self.base_class_module, self.pos)
            else:
                base_class_scope = env
3393 3394 3395 3396 3397 3398
            if self.base_class_name == 'object':
                # extension classes are special and don't need to inherit from object
                if base_class_scope is None or base_class_scope.lookup('object') is None:
                    self.base_class_name = None
                    self.base_class_module = None
                    base_class_scope = None
William Stein's avatar
William Stein committed
3399 3400 3401 3402 3403
            if base_class_scope:
                base_class_entry = base_class_scope.find(self.base_class_name, self.pos)
                if base_class_entry:
                    if not base_class_entry.is_type:
                        error(self.pos, "'%s' is not a type name" % self.base_class_name)
3404 3405 3406
                    elif not base_class_entry.type.is_extension_type and \
                             not (base_class_entry.type.is_builtin_type and \
                                  base_class_entry.type.objstruct_cname):
William Stein's avatar
William Stein committed
3407 3408
                        error(self.pos, "'%s' is not an extension type" % self.base_class_name)
                    elif not base_class_entry.type.is_complete():
3409 3410 3411
                        error(self.pos, "Base class '%s' of type '%s' is incomplete" % (
                            self.base_class_name, self.class_name))
                    elif base_class_entry.type.scope and base_class_entry.type.scope.directives and \
3412
                             base_class_entry.type.scope.directives['final']:
3413 3414
                        error(self.pos, "Base class '%s' of type '%s' is final" % (
                            self.base_class_name, self.class_name))
3415 3416 3417 3418
                    elif base_class_entry.type.is_builtin_type and \
                             base_class_entry.type.name in ('tuple', 'str', 'bytes'):
                        error(self.pos, "inheritance from PyVarObject types like '%s' is not currently supported"
                              % base_class_entry.type.name)
William Stein's avatar
William Stein committed
3419 3420 3421
                    else:
                        self.base_type = base_class_entry.type
        has_body = self.body is not None
3422
        if self.module_name and self.visibility != 'extern':
3423 3424 3425 3426 3427 3428
            module_path = self.module_name.split(".")
            home_scope = env.find_imported_module(module_path, self.pos)
            if not home_scope:
                return
        else:
            home_scope = env
3429 3430

        if self.visibility == 'extern':
3431 3432 3433
            if (self.module_name == '__builtin__' and
                self.class_name in Builtin.builtin_types and
                env.qualified_name[:8] != 'cpython.'): # allow overloaded names for cimporting from cpython
3434
                warning(self.pos, "%s already a builtin Cython type" % self.class_name, 1)
3435

3436
        self.entry = home_scope.declare_c_class(
3437
            name = self.class_name,
William Stein's avatar
William Stein committed
3438 3439 3440 3441 3442 3443 3444 3445
            pos = self.pos,
            defining = has_body and self.in_pxd,
            implementing = has_body and not self.in_pxd,
            module_name = self.module_name,
            base_type = self.base_type,
            objstruct_cname = self.objstruct_name,
            typeobj_cname = self.typeobj_name,
            visibility = self.visibility,
Stefan Behnel's avatar
Stefan Behnel committed
3446
            typedef_flag = self.typedef_flag,
3447
            api = self.api,
Robert Bradshaw's avatar
Robert Bradshaw committed
3448
            buffer_defaults = buffer_defaults,
3449 3450 3451
            shadow = self.shadow)
        if self.shadow:
            home_scope.lookup(self.class_name).as_variable = self.entry
3452
        if home_scope is not env and self.visibility == 'extern':
3453
            env.add_imported_entry(self.class_name, self.entry, self.pos)
3454
        self.scope = scope = self.entry.type.scope
3455 3456
        if scope is not None:
            scope.directives = env.directives
3457

3458
        if self.doc and Options.docstrings:
3459
            scope.doc = embed_position(self.pos, self.doc)
3460

William Stein's avatar
William Stein committed
3461 3462 3463 3464 3465 3466 3467
        if has_body:
            self.body.analyse_declarations(scope)
            if self.in_pxd:
                scope.defined = 1
            else:
                scope.implemented = 1
        env.allocate_vtable_names(self.entry)
3468

William Stein's avatar
William Stein committed
3469 3470
    def analyse_expressions(self, env):
        if self.body:
Robert Bradshaw's avatar
Robert Bradshaw committed
3471 3472
            scope = self.entry.type.scope
            self.body.analyse_expressions(scope)
3473

3474
    def generate_function_definitions(self, env, code):
William Stein's avatar
William Stein committed
3475
        if self.body:
3476 3477
            self.generate_lambda_definitions(self.scope, code)
            self.body.generate_function_definitions(self.scope, code)
3478

William Stein's avatar
William Stein committed
3479 3480 3481 3482 3483
    def generate_execution_code(self, code):
        # This is needed to generate evaluation code for
        # default values of method arguments.
        if self.body:
            self.body.generate_execution_code(code)
3484

3485 3486 3487
    def annotate(self, code):
        if self.body:
            self.body.annotate(code)
William Stein's avatar
William Stein committed
3488 3489 3490 3491 3492 3493


class PropertyNode(StatNode):
    #  Definition of a property in an extension type.
    #
    #  name   string
3494
    #  doc    EncodedString or None    Doc string
William Stein's avatar
William Stein committed
3495
    #  body   StatListNode
3496

3497 3498
    child_attrs = ["body"]

William Stein's avatar
William Stein committed
3499 3500 3501
    def analyse_declarations(self, env):
        entry = env.declare_property(self.name, self.doc, self.pos)
        if entry:
3502
            entry.scope.directives = env.directives
William Stein's avatar
William Stein committed
3503
            self.body.analyse_declarations(entry.scope)
3504

William Stein's avatar
William Stein committed
3505 3506
    def analyse_expressions(self, env):
        self.body.analyse_expressions(env)
3507

3508 3509
    def generate_function_definitions(self, env, code):
        self.body.generate_function_definitions(env, code)
William Stein's avatar
William Stein committed
3510 3511 3512 3513

    def generate_execution_code(self, code):
        pass

3514 3515 3516
    def annotate(self, code):
        self.body.annotate(code)

William Stein's avatar
William Stein committed
3517 3518 3519 3520 3521

class GlobalNode(StatNode):
    # Global variable declaration.
    #
    # names    [string]
3522

3523 3524
    child_attrs = []

William Stein's avatar
William Stein committed
3525 3526 3527 3528 3529 3530
    def analyse_declarations(self, env):
        for name in self.names:
            env.declare_global(name, self.pos)

    def analyse_expressions(self, env):
        pass
3531

William Stein's avatar
William Stein committed
3532 3533 3534 3535
    def generate_execution_code(self, code):
        pass


3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553
class NonlocalNode(StatNode):
    # Nonlocal variable declaration via the 'nonlocal' keyword.
    #
    # names    [string]

    child_attrs = []

    def analyse_declarations(self, env):
        for name in self.names:
            env.declare_nonlocal(name, self.pos)

    def analyse_expressions(self, env):
        pass

    def generate_execution_code(self, code):
        pass


William Stein's avatar
William Stein committed
3554 3555 3556 3557
class ExprStatNode(StatNode):
    #  Expression used as a statement.
    #
    #  expr   ExprNode
3558 3559

    child_attrs = ["expr"]
3560

Robert Bradshaw's avatar
Robert Bradshaw committed
3561 3562 3563
    def analyse_declarations(self, env):
        import ExprNodes
        if isinstance(self.expr, ExprNodes.GeneralCallNode):
3564
            func = self.expr.function.as_cython_attribute()
Robert Bradshaw's avatar
Robert Bradshaw committed
3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575
            if func == u'declare':
                args, kwds = self.expr.explicit_args_kwds()
                if len(args):
                    error(self.expr.pos, "Variable names must be specified.")
                for var, type_node in kwds.key_value_pairs:
                    type = type_node.analyse_as_type(env)
                    if type is None:
                        error(type_node.pos, "Unknown type")
                    else:
                        env.declare_var(var.value, type, var.pos, is_cdef = True)
                self.__class__ = PassStatNode
3576

William Stein's avatar
William Stein committed
3577
    def analyse_expressions(self, env):
3578
        self.expr.result_is_used = False # hint that .result() may safely be left empty
William Stein's avatar
William Stein committed
3579
        self.expr.analyse_expressions(env)
3580

3581
    def nogil_check(self, env):
3582
        if self.expr.type.is_pyobject and self.expr.is_temp:
3583 3584 3585 3586
            self.gil_error()

    gil_message = "Discarding owned Python object"

William Stein's avatar
William Stein committed
3587 3588
    def generate_execution_code(self, code):
        self.expr.generate_evaluation_code(code)
3589 3590
        if not self.expr.is_temp and self.expr.result():
            code.putln("%s;" % self.expr.result())
William Stein's avatar
William Stein committed
3591
        self.expr.generate_disposal_code(code)
3592
        self.expr.free_temps(code)
William Stein's avatar
William Stein committed
3593

3594 3595 3596
    def generate_function_definitions(self, env, code):
        self.expr.generate_function_definitions(env, code)

3597 3598 3599
    def annotate(self, code):
        self.expr.annotate(code)

William Stein's avatar
William Stein committed
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610

class AssignmentNode(StatNode):
    #  Abstract base class for assignment nodes.
    #
    #  The analyse_expressions and generate_execution_code
    #  phases of assignments are split into two sub-phases
    #  each, to enable all the right hand sides of a
    #  parallel assignment to be evaluated before assigning
    #  to any of the left hand sides.

    def analyse_expressions(self, env):
3611 3612
        self.analyse_types(env)

3613 3614 3615
#       def analyse_expressions(self, env):
#           self.analyse_expressions_1(env)
#           self.analyse_expressions_2(env)
William Stein's avatar
William Stein committed
3616 3617 3618 3619

    def generate_execution_code(self, code):
        self.generate_rhs_evaluation_code(code)
        self.generate_assignment_code(code)
3620

William Stein's avatar
William Stein committed
3621 3622 3623 3624 3625 3626 3627 3628

class SingleAssignmentNode(AssignmentNode):
    #  The simplest case:
    #
    #    a = b
    #
    #  lhs      ExprNode      Left hand side
    #  rhs      ExprNode      Right hand side
3629
    #  first    bool          Is this guaranteed the first assignment to lhs?
3630

3631
    child_attrs = ["lhs", "rhs"]
3632
    first = False
3633
    declaration_only = False
William Stein's avatar
William Stein committed
3634 3635

    def analyse_declarations(self, env):
3636
        import ExprNodes
3637

3638 3639
        # handle declarations of the form x = cython.foo()
        if isinstance(self.rhs, ExprNodes.CallNode):
3640
            func_name = self.rhs.function.as_cython_attribute()
3641 3642
            if func_name:
                args, kwds = self.rhs.explicit_args_kwds()
3643

3644
                if func_name in ['declare', 'typedef']:
Robert Bradshaw's avatar
Robert Bradshaw committed
3645
                    if len(args) > 2 or kwds is not None:
3646
                        error(self.rhs.pos, "Can only declare one type at a time.")
3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
                        return
                    type = args[0].analyse_as_type(env)
                    if type is None:
                        error(args[0].pos, "Unknown type")
                        return
                    lhs = self.lhs
                    if func_name == 'declare':
                        if isinstance(lhs, ExprNodes.NameNode):
                            vars = [(lhs.name, lhs.pos)]
                        elif isinstance(lhs, ExprNodes.TupleNode):
                            vars = [(var.name, var.pos) for var in lhs.args]
                        else:
                            error(lhs.pos, "Invalid declaration")
                            return
                        for var, pos in vars:
                            env.declare_var(var, type, pos, is_cdef = True)
Robert Bradshaw's avatar
Robert Bradshaw committed
3663 3664 3665 3666 3667
                        if len(args) == 2:
                            # we have a value
                            self.rhs = args[1]
                        else:
                            self.declaration_only = True
3668
                    else:
Robert Bradshaw's avatar
Robert Bradshaw committed
3669
                        self.declaration_only = True
3670 3671
                        if not isinstance(lhs, ExprNodes.NameNode):
                            error(lhs.pos, "Invalid declaration.")
3672
                        env.declare_typedef(lhs.name, type, self.pos, visibility='private')
3673

3674 3675 3676
                elif func_name in ['struct', 'union']:
                    self.declaration_only = True
                    if len(args) > 0 or kwds is None:
3677
                        error(self.rhs.pos, "Struct or union members must be given by name.")
3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694
                        return
                    members = []
                    for member, type_node in kwds.key_value_pairs:
                        type = type_node.analyse_as_type(env)
                        if type is None:
                            error(type_node.pos, "Unknown type")
                        else:
                            members.append((member.value, type, member.pos))
                    if len(members) < len(kwds.key_value_pairs):
                        return
                    if not isinstance(self.lhs, ExprNodes.NameNode):
                        error(self.lhs.pos, "Invalid declaration.")
                    name = self.lhs.name
                    scope = StructOrUnionScope(name)
                    env.declare_struct_or_union(name, func_name, scope, False, self.rhs.pos)
                    for member, type, pos in members:
                        scope.declare_var(member, type, pos)
3695

3696 3697 3698 3699
        if self.declaration_only:
            return
        else:
            self.lhs.analyse_target_declaration(env)
3700

3701
    def analyse_types(self, env, use_temp = 0):
William Stein's avatar
William Stein committed
3702 3703
        self.rhs.analyse_types(env)
        self.lhs.analyse_target_types(env)
3704
        self.lhs.gil_assignment_check(env)
William Stein's avatar
William Stein committed
3705 3706 3707
        self.rhs = self.rhs.coerce_to(self.lhs.type, env)
        if use_temp:
            self.rhs = self.rhs.coerce_to_temp(env)
3708

William Stein's avatar
William Stein committed
3709 3710
    def generate_rhs_evaluation_code(self, code):
        self.rhs.generate_evaluation_code(code)
3711

William Stein's avatar
William Stein committed
3712 3713 3714
    def generate_assignment_code(self, code):
        self.lhs.generate_assignment_code(self.rhs, code)

3715 3716 3717
    def generate_function_definitions(self, env, code):
        self.rhs.generate_function_definitions(env, code)

3718 3719 3720 3721
    def annotate(self, code):
        self.lhs.annotate(code)
        self.rhs.annotate(code)

William Stein's avatar
William Stein committed
3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733

class CascadedAssignmentNode(AssignmentNode):
    #  An assignment with multiple left hand sides:
    #
    #    a = b = c
    #
    #  lhs_list   [ExprNode]   Left hand sides
    #  rhs        ExprNode     Right hand sides
    #
    #  Used internally:
    #
    #  coerced_rhs_list   [ExprNode]   RHS coerced to type of each LHS
3734

3735
    child_attrs = ["lhs_list", "rhs", "coerced_rhs_list"]
3736
    coerced_rhs_list = None
3737

William Stein's avatar
William Stein committed
3738 3739 3740
    def analyse_declarations(self, env):
        for lhs in self.lhs_list:
            lhs.analyse_target_declaration(env)
3741

3742
    def analyse_types(self, env, use_temp = 0):
William Stein's avatar
William Stein committed
3743
        self.rhs.analyse_types(env)
Stefan Behnel's avatar
Stefan Behnel committed
3744 3745 3746 3747 3748
        if not self.rhs.is_simple():
            if use_temp:
                self.rhs = self.rhs.coerce_to_temp(env)
            else:
                self.rhs = self.rhs.coerce_to_simple(env)
William Stein's avatar
William Stein committed
3749 3750 3751 3752
        from ExprNodes import CloneNode
        self.coerced_rhs_list = []
        for lhs in self.lhs_list:
            lhs.analyse_target_types(env)
3753
            lhs.gil_assignment_check(env)
William Stein's avatar
William Stein committed
3754 3755 3756
            rhs = CloneNode(self.rhs)
            rhs = rhs.coerce_to(lhs.type, env)
            self.coerced_rhs_list.append(rhs)
3757

William Stein's avatar
William Stein committed
3758 3759
    def generate_rhs_evaluation_code(self, code):
        self.rhs.generate_evaluation_code(code)
3760

William Stein's avatar
William Stein committed
3761 3762 3763 3764 3765 3766 3767 3768
    def generate_assignment_code(self, code):
        for i in range(len(self.lhs_list)):
            lhs = self.lhs_list[i]
            rhs = self.coerced_rhs_list[i]
            rhs.generate_evaluation_code(code)
            lhs.generate_assignment_code(rhs, code)
            # Assignment has disposed of the cloned RHS
        self.rhs.generate_disposal_code(code)
3769
        self.rhs.free_temps(code)
William Stein's avatar
William Stein committed
3770

3771 3772 3773
    def generate_function_definitions(self, env, code):
        self.rhs.generate_function_definitions(env, code)

3774 3775 3776 3777 3778
    def annotate(self, code):
        for i in range(len(self.lhs_list)):
            lhs = self.lhs_list[i].annotate(code)
            rhs = self.coerced_rhs_list[i].annotate(code)
        self.rhs.annotate(code)
3779

3780

William Stein's avatar
William Stein committed
3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793
class ParallelAssignmentNode(AssignmentNode):
    #  A combined packing/unpacking assignment:
    #
    #    a, b, c =  d, e, f
    #
    #  This has been rearranged by the parser into
    #
    #    a = d ; b = e ; c = f
    #
    #  but we must evaluate all the right hand sides
    #  before assigning to any of the left hand sides.
    #
    #  stats     [AssignmentNode]   The constituent assignments
3794

3795 3796
    child_attrs = ["stats"]

William Stein's avatar
William Stein committed
3797 3798 3799
    def analyse_declarations(self, env):
        for stat in self.stats:
            stat.analyse_declarations(env)
3800

William Stein's avatar
William Stein committed
3801 3802
    def analyse_expressions(self, env):
        for stat in self.stats:
3803 3804
            stat.analyse_types(env, use_temp = 1)

Robert Bradshaw's avatar
Robert Bradshaw committed
3805 3806 3807 3808 3809
#    def analyse_expressions(self, env):
#        for stat in self.stats:
#            stat.analyse_expressions_1(env, use_temp = 1)
#        for stat in self.stats:
#            stat.analyse_expressions_2(env)
3810

William Stein's avatar
William Stein committed
3811 3812 3813 3814 3815 3816
    def generate_execution_code(self, code):
        for stat in self.stats:
            stat.generate_rhs_evaluation_code(code)
        for stat in self.stats:
            stat.generate_assignment_code(code)

3817 3818 3819 3820
    def generate_function_definitions(self, env, code):
        for stat in self.stats:
            stat.generate_function_definitions(env, code)

3821 3822 3823 3824 3825
    def annotate(self, code):
        for stat in self.stats:
            stat.annotate(code)


3826
class InPlaceAssignmentNode(AssignmentNode):
Craig Citro's avatar
Craig Citro committed
3827
    #  An in place arithmetic operand:
3828 3829 3830 3831 3832 3833 3834 3835 3836 3837
    #
    #    a += b
    #    a -= b
    #    ...
    #
    #  lhs      ExprNode      Left hand side
    #  rhs      ExprNode      Right hand side
    #  op       char          one of "+-*/%^&|"
    #  dup     (ExprNode)     copy of lhs used for operation (auto-generated)
    #
3838 3839 3840 3841 3842 3843 3844
    #  This code is a bit tricky because in order to obey Python
    #  semantics the sub-expressions (e.g. indices) of the lhs must
    #  not be evaluated twice. So we must re-use the values calculated
    #  in evaluation phase for the assignment phase as well.
    #  Fortunately, the type of the lhs node is fairly constrained
    #  (it must be a NameNode, AttributeNode, or IndexNode).

3845
    child_attrs = ["lhs", "rhs"]
3846

3847 3848
    def analyse_declarations(self, env):
        self.lhs.analyse_target_declaration(env)
3849

3850
    def analyse_types(self, env):
3851 3852
        self.rhs.analyse_types(env)
        self.lhs.analyse_target_types(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
3853

3854
    def generate_execution_code(self, code):
3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
        import ExprNodes
        self.rhs.generate_evaluation_code(code)
        self.lhs.generate_subexpr_evaluation_code(code)
        c_op = self.operator
        if c_op == "//":
            c_op = "/"
        elif c_op == "**":
            error(self.pos, "No C inplace power operator")
        if isinstance(self.lhs, ExprNodes.IndexNode) and self.lhs.is_buffer_access:
            if self.lhs.type.is_pyobject:
                error(self.pos, "In-place operators not allowed on object buffers in this release.")
Robert Bradshaw's avatar
Robert Bradshaw committed
3866 3867
            if c_op in ('/', '%') and self.lhs.type.is_int and not code.directives['cdivision']:
                error(self.pos, "In-place non-c divide operators not allowed on int buffers.")
3868 3869 3870 3871 3872 3873 3874 3875 3876 3877
            self.lhs.generate_buffer_setitem_code(self.rhs, code, c_op)
        else:
            # C++
            # TODO: make sure overload is declared
            code.putln("%s %s= %s;" % (self.lhs.result(), c_op, self.rhs.result()))
        self.lhs.generate_subexpr_disposal_code(code)
        self.lhs.free_subexpr_temps(code)
        self.rhs.generate_disposal_code(code)
        self.rhs.free_temps(code)

3878 3879 3880
    def annotate(self, code):
        self.lhs.annotate(code)
        self.rhs.annotate(code)
3881

3882 3883
    def create_binop_node(self):
        import ExprNodes
3884
        return ExprNodes.binop_node(self.pos, self.operator, self.lhs, self.rhs)
3885

William Stein's avatar
William Stein committed
3886 3887 3888 3889

class PrintStatNode(StatNode):
    #  print statement
    #
3890
    #  arg_tuple         TupleNode
3891
    #  stream            ExprNode or None (stdout)
3892
    #  append_newline    boolean
3893

3894
    child_attrs = ["arg_tuple", "stream"]
3895

William Stein's avatar
William Stein committed
3896
    def analyse_expressions(self, env):
3897 3898 3899
        if self.stream:
            self.stream.analyse_expressions(env)
            self.stream = self.stream.coerce_to_pyobject(env)
3900
        self.arg_tuple.analyse_expressions(env)
3901
        self.arg_tuple = self.arg_tuple.coerce_to_pyobject(env)
3902
        env.use_utility_code(printing_utility_code)
3903 3904
        if len(self.arg_tuple.args) == 1 and self.append_newline:
            env.use_utility_code(printing_one_utility_code)
3905

3906
    nogil_check = Node.gil_error
3907
    gil_message = "Python print statement"
3908

William Stein's avatar
William Stein committed
3909
    def generate_execution_code(self, code):
3910 3911 3912 3913 3914
        if self.stream:
            self.stream.generate_evaluation_code(code)
            stream_result = self.stream.py_result()
        else:
            stream_result = '0'
3915 3916 3917
        if len(self.arg_tuple.args) == 1 and self.append_newline:
            arg = self.arg_tuple.args[0]
            arg.generate_evaluation_code(code)
3918

3919
            code.putln(
3920 3921
                "if (__Pyx_PrintOne(%s, %s) < 0) %s" % (
                    stream_result,
3922 3923 3924 3925 3926 3927 3928
                    arg.py_result(),
                    code.error_goto(self.pos)))
            arg.generate_disposal_code(code)
            arg.free_temps(code)
        else:
            self.arg_tuple.generate_evaluation_code(code)
            code.putln(
3929 3930
                "if (__Pyx_Print(%s, %s, %d) < 0) %s" % (
                    stream_result,
3931 3932 3933 3934 3935
                    self.arg_tuple.py_result(),
                    self.append_newline,
                    code.error_goto(self.pos)))
            self.arg_tuple.generate_disposal_code(code)
            self.arg_tuple.free_temps(code)
3936

3937 3938 3939 3940
        if self.stream:
            self.stream.generate_disposal_code(code)
            self.stream.free_temps(code)

3941
    def generate_function_definitions(self, env, code):
3942 3943
        if self.stream:
            self.stream.generate_function_definitions(env, code)
3944
        self.arg_tuple.generate_function_definitions(env, code)
3945

3946
    def annotate(self, code):
3947 3948
        if self.stream:
            self.stream.annotate(code)
3949
        self.arg_tuple.annotate(code)
William Stein's avatar
William Stein committed
3950 3951


3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
class ExecStatNode(StatNode):
    #  exec statement
    #
    #  args     [ExprNode]

    child_attrs = ["args"]

    def analyse_expressions(self, env):
        for i, arg in enumerate(self.args):
            arg.analyse_expressions(env)
            arg = arg.coerce_to_pyobject(env)
            self.args[i] = arg
        env.use_utility_code(Builtin.pyexec_utility_code)

3966
    nogil_check = Node.gil_error
3967 3968 3969 3970 3971 3972 3973 3974
    gil_message = "Python exec statement"

    def generate_execution_code(self, code):
        args = []
        for arg in self.args:
            arg.generate_evaluation_code(code)
            args.append( arg.py_result() )
        args = tuple(args + ['0', '0'][:3-len(args)])
3975
        temp_result = code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=True)
3976
        code.putln("%s = __Pyx_PyRun(%s, %s, %s);" % (
3977
                (temp_result,) + args))
3978 3979
        for arg in self.args:
            arg.generate_disposal_code(code)
3980
            arg.free_temps(code)
3981
        code.putln(
3982 3983 3984 3985
            code.error_goto_if_null(temp_result, self.pos))
        code.put_gotref(temp_result)
        code.put_decref_clear(temp_result, py_object_type)
        code.funcstate.release_temp(temp_result)
3986 3987 3988 3989 3990 3991

    def annotate(self, code):
        for arg in self.args:
            arg.annotate(code)


William Stein's avatar
William Stein committed
3992 3993 3994 3995
class DelStatNode(StatNode):
    #  del statement
    #
    #  args     [ExprNode]
3996

3997 3998
    child_attrs = ["args"]

William Stein's avatar
William Stein committed
3999 4000 4001
    def analyse_declarations(self, env):
        for arg in self.args:
            arg.analyse_target_declaration(env)
4002

William Stein's avatar
William Stein committed
4003 4004
    def analyse_expressions(self, env):
        for arg in self.args:
4005
            arg.analyse_target_expression(env, None)
Robert Bradshaw's avatar
Robert Bradshaw committed
4006
            if arg.type.is_pyobject:
Robert Bradshaw's avatar
Robert Bradshaw committed
4007
                pass
Robert Bradshaw's avatar
Robert Bradshaw committed
4008
            elif arg.type.is_ptr and arg.type.base_type.is_cpp_class:
Robert Bradshaw's avatar
Robert Bradshaw committed
4009
                self.cpp_check(env)
4010
            elif arg.type.is_cpp_class:
Robert Bradshaw's avatar
merge  
Robert Bradshaw committed
4011
                error(arg.pos, "Deletion of non-heap C++ object")
4012
            else:
Robert Bradshaw's avatar
Robert Bradshaw committed
4013
                error(arg.pos, "Deletion of non-Python, non-C++ object")
4014
            #arg.release_target_temp(env)
4015

4016
    def nogil_check(self, env):
4017 4018
        for arg in self.args:
            if arg.type.is_pyobject:
4019
                self.gil_error()
4020

4021 4022
    gil_message = "Deleting Python object"

William Stein's avatar
William Stein committed
4023 4024 4025 4026
    def generate_execution_code(self, code):
        for arg in self.args:
            if arg.type.is_pyobject:
                arg.generate_deletion_code(code)
4027
            elif arg.type.is_ptr and arg.type.base_type.is_cpp_class:
Robert Bradshaw's avatar
Robert Bradshaw committed
4028
                arg.generate_result_code(code)
Robert Bradshaw's avatar
merge  
Robert Bradshaw committed
4029
                code.putln("delete %s;" % arg.result())
William Stein's avatar
William Stein committed
4030 4031
            # else error reported earlier

4032 4033 4034 4035
    def annotate(self, code):
        for arg in self.args:
            arg.annotate(code)

William Stein's avatar
William Stein committed
4036 4037 4038

class PassStatNode(StatNode):
    #  pass statement
4039 4040

    child_attrs = []
4041

William Stein's avatar
William Stein committed
4042 4043
    def analyse_expressions(self, env):
        pass
4044

William Stein's avatar
William Stein committed
4045 4046 4047 4048 4049 4050
    def generate_execution_code(self, code):
        pass


class BreakStatNode(StatNode):

4051 4052
    child_attrs = []

William Stein's avatar
William Stein committed
4053 4054
    def analyse_expressions(self, env):
        pass
4055

William Stein's avatar
William Stein committed
4056 4057 4058 4059
    def generate_execution_code(self, code):
        if not code.break_label:
            error(self.pos, "break statement not inside loop")
        else:
4060
            code.put_goto(code.break_label)
William Stein's avatar
William Stein committed
4061 4062 4063 4064


class ContinueStatNode(StatNode):

4065 4066
    child_attrs = []

William Stein's avatar
William Stein committed
4067 4068
    def analyse_expressions(self, env):
        pass
4069

William Stein's avatar
William Stein committed
4070
    def generate_execution_code(self, code):
4071
        if code.funcstate.in_try_finally:
William Stein's avatar
William Stein committed
4072 4073 4074 4075
            error(self.pos, "continue statement inside try of try...finally")
        elif not code.continue_label:
            error(self.pos, "continue statement not inside loop")
        else:
4076
            code.put_goto(code.continue_label)
William Stein's avatar
William Stein committed
4077 4078 4079 4080 4081 4082 4083


class ReturnStatNode(StatNode):
    #  return statement
    #
    #  value         ExprNode or None
    #  return_type   PyrexType
4084

4085 4086
    child_attrs = ["value"]

William Stein's avatar
William Stein committed
4087 4088 4089 4090 4091 4092 4093 4094 4095
    def analyse_expressions(self, env):
        return_type = env.return_type
        self.return_type = return_type
        if not return_type:
            error(self.pos, "Return not inside a function body")
            return
        if self.value:
            self.value.analyse_types(env)
            if return_type.is_void or return_type.is_returncode:
4096
                error(self.value.pos,
William Stein's avatar
William Stein committed
4097 4098 4099 4100 4101 4102 4103 4104
                    "Return with value in void function")
            else:
                self.value = self.value.coerce_to(env.return_type, env)
        else:
            if (not return_type.is_void
                and not return_type.is_pyobject
                and not return_type.is_returncode):
                    error(self.pos, "Return value required")
4105

4106
    def nogil_check(self, env):
4107
        if self.return_type.is_pyobject:
4108
            self.gil_error()
4109 4110 4111

    gil_message = "Returning Python object"

William Stein's avatar
William Stein committed
4112
    def generate_execution_code(self, code):
4113
        code.mark_pos(self.pos)
William Stein's avatar
William Stein committed
4114 4115 4116
        if not self.return_type:
            # error reported earlier
            return
4117 4118 4119
        if self.return_type.is_pyobject:
            code.put_xdecref(Naming.retval_cname,
                             self.return_type)
William Stein's avatar
William Stein committed
4120 4121 4122 4123 4124 4125 4126 4127
        if self.value:
            self.value.generate_evaluation_code(code)
            self.value.make_owned_reference(code)
            code.putln(
                "%s = %s;" % (
                    Naming.retval_cname,
                    self.value.result_as(self.return_type)))
            self.value.generate_post_assignment_code(code)
4128
            self.value.free_temps(code)
William Stein's avatar
William Stein committed
4129 4130 4131 4132 4133 4134 4135 4136
        else:
            if self.return_type.is_pyobject:
                code.put_init_to_py_none(Naming.retval_cname, self.return_type)
            elif self.return_type.is_returncode:
                code.putln(
                    "%s = %s;" % (
                        Naming.retval_cname,
                        self.return_type.default_value))
4137
        for cname, type in code.funcstate.temps_holding_reference():
4138
            code.put_decref_clear(cname, type)
4139
        code.put_goto(code.return_label)
4140 4141 4142 4143

    def generate_function_definitions(self, env, code):
        if self.value is not None:
            self.value.generate_function_definitions(env, code)
4144

4145 4146 4147
    def annotate(self, code):
        if self.value:
            self.value.annotate(code)
William Stein's avatar
William Stein committed
4148 4149 4150 4151 4152 4153 4154 4155


class RaiseStatNode(StatNode):
    #  raise statement
    #
    #  exc_type    ExprNode or None
    #  exc_value   ExprNode or None
    #  exc_tb      ExprNode or None
Haoyu Bai's avatar
Haoyu Bai committed
4156
    #  cause       ExprNode or None
4157

Haoyu Bai's avatar
Haoyu Bai committed
4158
    child_attrs = ["exc_type", "exc_value", "exc_tb", "cause"]
4159

William Stein's avatar
William Stein committed
4160 4161 4162 4163 4164 4165 4166 4167 4168 4169
    def analyse_expressions(self, env):
        if self.exc_type:
            self.exc_type.analyse_types(env)
            self.exc_type = self.exc_type.coerce_to_pyobject(env)
        if self.exc_value:
            self.exc_value.analyse_types(env)
            self.exc_value = self.exc_value.coerce_to_pyobject(env)
        if self.exc_tb:
            self.exc_tb.analyse_types(env)
            self.exc_tb = self.exc_tb.coerce_to_pyobject(env)
Haoyu Bai's avatar
Haoyu Bai committed
4170 4171 4172
        if self.cause:
            self.cause.analyse_types(env)
            self.cause = self.cause.coerce_to_pyobject(env)
4173 4174 4175 4176 4177
        # special cases for builtin exceptions
        self.builtin_exc_name = None
        if self.exc_type and not self.exc_value and not self.exc_tb:
            exc = self.exc_type
            import ExprNodes
Robert Bradshaw's avatar
Robert Bradshaw committed
4178 4179
            if (isinstance(exc, ExprNodes.SimpleCallNode) and
                not (exc.args or (exc.arg_tuple is not None and
4180
                                  exc.arg_tuple.args))):
4181 4182 4183 4184 4185
                exc = exc.function # extract the exception type
            if exc.is_name and exc.entry.is_builtin:
                self.builtin_exc_name = exc.name
                if self.builtin_exc_name == 'MemoryError':
                    self.exc_type = None # has a separate implementation
4186

4187
    nogil_check = Node.gil_error
4188 4189
    gil_message = "Raising exception"

William Stein's avatar
William Stein committed
4190
    def generate_execution_code(self, code):
4191 4192 4193 4194
        if self.builtin_exc_name == 'MemoryError':
            code.putln('PyErr_NoMemory(); %s' % code.error_goto(self.pos))
            return

William Stein's avatar
William Stein committed
4195 4196 4197 4198
        if self.exc_type:
            self.exc_type.generate_evaluation_code(code)
            type_code = self.exc_type.py_result()
        else:
Stefan Behnel's avatar
Stefan Behnel committed
4199
            type_code = "0"
William Stein's avatar
William Stein committed
4200 4201 4202 4203 4204 4205 4206 4207 4208 4209
        if self.exc_value:
            self.exc_value.generate_evaluation_code(code)
            value_code = self.exc_value.py_result()
        else:
            value_code = "0"
        if self.exc_tb:
            self.exc_tb.generate_evaluation_code(code)
            tb_code = self.exc_tb.py_result()
        else:
            tb_code = "0"
Haoyu Bai's avatar
Haoyu Bai committed
4210 4211 4212 4213 4214
        if self.cause:
            self.cause.generate_evaluation_code(code)
            cause_code = self.cause.py_result()
        else:
            cause_code = "0"
4215
        code.globalstate.use_utility_code(raise_utility_code)
4216
        code.putln(
Haoyu Bai's avatar
Haoyu Bai committed
4217
            "__Pyx_Raise(%s, %s, %s, %s);" % (
4218 4219
                type_code,
                value_code,
Haoyu Bai's avatar
Haoyu Bai committed
4220 4221 4222
                tb_code,
                cause_code))
        for obj in (self.exc_type, self.exc_value, self.exc_tb, self.cause):
4223 4224 4225
            if obj:
                obj.generate_disposal_code(code)
                obj.free_temps(code)
William Stein's avatar
William Stein committed
4226 4227 4228
        code.putln(
            code.error_goto(self.pos))

4229 4230 4231 4232 4233 4234 4235
    def generate_function_definitions(self, env, code):
        if self.exc_type is not None:
            self.exc_type.generate_function_definitions(env, code)
        if self.exc_value is not None:
            self.exc_value.generate_function_definitions(env, code)
        if self.exc_tb is not None:
            self.exc_tb.generate_function_definitions(env, code)
Haoyu Bai's avatar
Haoyu Bai committed
4236 4237
        if self.cause is not None:
            self.cause.generate_function_definitions(env, code)
4238

4239 4240 4241 4242 4243 4244 4245
    def annotate(self, code):
        if self.exc_type:
            self.exc_type.annotate(code)
        if self.exc_value:
            self.exc_value.annotate(code)
        if self.exc_tb:
            self.exc_tb.annotate(code)
Haoyu Bai's avatar
Haoyu Bai committed
4246 4247
        if self.cause:
            self.cause.annotate(code)
4248

William Stein's avatar
William Stein committed
4249

4250 4251
class ReraiseStatNode(StatNode):

4252 4253
    child_attrs = []

4254
    def analyse_expressions(self, env):
4255
        env.use_utility_code(restore_exception_utility_code)
4256

4257
    nogil_check = Node.gil_error
4258 4259
    gil_message = "Raising exception"

4260
    def generate_execution_code(self, code):
4261
        vars = code.funcstate.exc_vars
4262
        if vars:
4263 4264 4265 4266 4267 4268
            for varname in vars:
                code.put_giveref(varname)
            code.putln("__Pyx_ErrRestore(%s, %s, %s);" % tuple(vars))
            for varname in vars:
                code.put("%s = 0; " % varname)
            code.putln()
4269 4270 4271
            code.putln(code.error_goto(self.pos))
        else:
            error(self.pos, "Reraise not inside except clause")
4272

4273

William Stein's avatar
William Stein committed
4274 4275 4276 4277 4278
class AssertStatNode(StatNode):
    #  assert statement
    #
    #  cond    ExprNode
    #  value   ExprNode or None
4279

4280 4281
    child_attrs = ["cond", "value"]

William Stein's avatar
William Stein committed
4282 4283 4284 4285 4286
    def analyse_expressions(self, env):
        self.cond = self.cond.analyse_boolean_expression(env)
        if self.value:
            self.value.analyse_types(env)
            self.value = self.value.coerce_to_pyobject(env)
4287

4288
    nogil_check = Node.gil_error
4289
    gil_message = "Raising exception"
4290

William Stein's avatar
William Stein committed
4291
    def generate_execution_code(self, code):
4292
        code.putln("#ifndef CYTHON_WITHOUT_ASSERTIONS")
William Stein's avatar
William Stein committed
4293 4294
        self.cond.generate_evaluation_code(code)
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
4295
            "if (unlikely(!%s)) {" %
4296
                self.cond.result())
William Stein's avatar
William Stein committed
4297
        if self.value:
4298
            self.value.generate_evaluation_code(code)
William Stein's avatar
William Stein committed
4299 4300 4301
            code.putln(
                "PyErr_SetObject(PyExc_AssertionError, %s);" %
                    self.value.py_result())
4302
            self.value.generate_disposal_code(code)
4303
            self.value.free_temps(code)
William Stein's avatar
William Stein committed
4304 4305 4306 4307 4308 4309 4310 4311
        else:
            code.putln(
                "PyErr_SetNone(PyExc_AssertionError);")
        code.putln(
                code.error_goto(self.pos))
        code.putln(
            "}")
        self.cond.generate_disposal_code(code)
4312
        self.cond.free_temps(code)
4313
        code.putln("#endif")
William Stein's avatar
William Stein committed
4314

4315 4316 4317 4318 4319
    def generate_function_definitions(self, env, code):
        self.cond.generate_function_definitions(env, code)
        if self.value is not None:
            self.value.generate_function_definitions(env, code)

4320 4321 4322 4323 4324 4325
    def annotate(self, code):
        self.cond.annotate(code)
        if self.value:
            self.value.annotate(code)


William Stein's avatar
William Stein committed
4326 4327 4328 4329 4330
class IfStatNode(StatNode):
    #  if statement
    #
    #  if_clauses   [IfClauseNode]
    #  else_clause  StatNode or None
4331 4332

    child_attrs = ["if_clauses", "else_clause"]
4333

4334 4335 4336 4337 4338 4339 4340 4341 4342
    def analyse_control_flow(self, env):
        env.start_branching(self.pos)
        for if_clause in self.if_clauses:
            if_clause.analyse_control_flow(env)
            env.next_branch(if_clause.end_pos())
        if self.else_clause:
            self.else_clause.analyse_control_flow(env)
        env.finish_branching(self.end_pos())

William Stein's avatar
William Stein committed
4343 4344 4345 4346 4347
    def analyse_declarations(self, env):
        for if_clause in self.if_clauses:
            if_clause.analyse_declarations(env)
        if self.else_clause:
            self.else_clause.analyse_declarations(env)
4348

William Stein's avatar
William Stein committed
4349 4350 4351 4352 4353
    def analyse_expressions(self, env):
        for if_clause in self.if_clauses:
            if_clause.analyse_expressions(env)
        if self.else_clause:
            self.else_clause.analyse_expressions(env)
4354

William Stein's avatar
William Stein committed
4355
    def generate_execution_code(self, code):
4356
        code.mark_pos(self.pos)
4357 4358 4359 4360 4361
        end_label = code.new_label()
        for if_clause in self.if_clauses:
            if_clause.generate_execution_code(code, end_label)
        if self.else_clause:
            code.putln("/*else*/ {")
William Stein's avatar
William Stein committed
4362
            self.else_clause.generate_execution_code(code)
4363 4364
            code.putln("}")
        code.put_label(end_label)
4365

4366 4367 4368 4369 4370
    def generate_function_definitions(self, env, code):
        for clause in self.if_clauses:
            clause.generate_function_definitions(env, code)
        if self.else_clause is not None:
            self.else_clause.generate_function_definitions(env, code)
4371

4372 4373 4374 4375 4376
    def annotate(self, code):
        for if_clause in self.if_clauses:
            if_clause.annotate(code)
        if self.else_clause:
            self.else_clause.annotate(code)
William Stein's avatar
William Stein committed
4377 4378 4379 4380 4381 4382 4383


class IfClauseNode(Node):
    #  if or elif clause in an if statement
    #
    #  condition   ExprNode
    #  body        StatNode
4384

4385 4386
    child_attrs = ["condition", "body"]

4387 4388
    def analyse_control_flow(self, env):
        self.body.analyse_control_flow(env)
4389

William Stein's avatar
William Stein committed
4390 4391
    def analyse_declarations(self, env):
        self.body.analyse_declarations(env)
4392

William Stein's avatar
William Stein committed
4393 4394 4395 4396
    def analyse_expressions(self, env):
        self.condition = \
            self.condition.analyse_temp_boolean_expression(env)
        self.body.analyse_expressions(env)
4397 4398 4399

    def get_constant_condition_result(self):
        if self.condition.has_constant_result():
4400
            return bool(self.condition.constant_result)
4401 4402 4403
        else:
            return None

William Stein's avatar
William Stein committed
4404 4405 4406 4407
    def generate_execution_code(self, code, end_label):
        self.condition.generate_evaluation_code(code)
        code.putln(
            "if (%s) {" %
4408
                self.condition.result())
4409 4410
        self.condition.generate_disposal_code(code)
        self.condition.free_temps(code)
William Stein's avatar
William Stein committed
4411
        self.body.generate_execution_code(code)
4412
        code.put_goto(end_label)
William Stein's avatar
William Stein committed
4413
        code.putln("}")
4414

4415 4416 4417 4418
    def generate_function_definitions(self, env, code):
        self.condition.generate_function_definitions(env, code)
        self.body.generate_function_definitions(env, code)

4419 4420 4421
    def annotate(self, code):
        self.condition.annotate(code)
        self.body.annotate(code)
4422

4423 4424 4425 4426 4427 4428

class SwitchCaseNode(StatNode):
    # Generated in the optimization of an if-elif-else node
    #
    # conditions    [ExprNode]
    # body          StatNode
4429

4430
    child_attrs = ['conditions', 'body']
4431

4432 4433
    def generate_execution_code(self, code):
        for cond in self.conditions:
4434
            code.mark_pos(cond.pos)
4435 4436
            cond.generate_evaluation_code(code)
            code.putln("case %s:" % cond.result())
4437 4438
        self.body.generate_execution_code(code)
        code.putln("break;")
4439 4440 4441 4442 4443

    def generate_function_definitions(self, env, code):
        for cond in self.conditions:
            cond.generate_function_definitions(env, code)
        self.body.generate_function_definitions(env, code)
4444

4445 4446 4447
    def annotate(self, code):
        for cond in self.conditions:
            cond.annotate(code)
4448
        self.body.annotate(code)
4449 4450 4451 4452 4453 4454 4455

class SwitchStatNode(StatNode):
    # Generated in the optimization of an if-elif-else node
    #
    # test          ExprNode
    # cases         [SwitchCaseNode]
    # else_clause   StatNode or None
4456

4457
    child_attrs = ['test', 'cases', 'else_clause']
4458

4459
    def generate_execution_code(self, code):
4460
        self.test.generate_evaluation_code(code)
4461
        code.putln("switch (%s) {" % self.test.result())
4462 4463 4464 4465 4466
        for case in self.cases:
            case.generate_execution_code(code)
        if self.else_clause is not None:
            code.putln("default:")
            self.else_clause.generate_execution_code(code)
4467
            code.putln("break;")
4468 4469
        code.putln("}")

4470 4471 4472 4473 4474 4475 4476
    def generate_function_definitions(self, env, code):
        self.test.generate_function_definitions(env, code)
        for case in self.cases:
            case.generate_function_definitions(env, code)
        if self.else_clause is not None:
            self.else_clause.generate_function_definitions(env, code)

4477 4478 4479 4480
    def annotate(self, code):
        self.test.annotate(code)
        for case in self.cases:
            case.annotate(code)
4481 4482
        if self.else_clause is not None:
            self.else_clause.annotate(code)
4483

4484
class LoopNode(object):
4485

4486 4487 4488 4489 4490 4491 4492 4493
    def analyse_control_flow(self, env):
        env.start_branching(self.pos)
        self.body.analyse_control_flow(env)
        env.next_branch(self.body.end_pos())
        if self.else_clause:
            self.else_clause.analyse_control_flow(env)
        env.finish_branching(self.end_pos())

4494

4495
class WhileStatNode(LoopNode, StatNode):
William Stein's avatar
William Stein committed
4496 4497 4498 4499 4500
    #  while statement
    #
    #  condition    ExprNode
    #  body         StatNode
    #  else_clause  StatNode
4501 4502

    child_attrs = ["condition", "body", "else_clause"]
4503

William Stein's avatar
William Stein committed
4504 4505 4506 4507
    def analyse_declarations(self, env):
        self.body.analyse_declarations(env)
        if self.else_clause:
            self.else_clause.analyse_declarations(env)
4508

William Stein's avatar
William Stein committed
4509 4510 4511 4512 4513 4514
    def analyse_expressions(self, env):
        self.condition = \
            self.condition.analyse_temp_boolean_expression(env)
        self.body.analyse_expressions(env)
        if self.else_clause:
            self.else_clause.analyse_expressions(env)
4515

William Stein's avatar
William Stein committed
4516 4517 4518 4519 4520
    def generate_execution_code(self, code):
        old_loop_labels = code.new_loop_labels()
        code.putln(
            "while (1) {")
        self.condition.generate_evaluation_code(code)
4521
        self.condition.generate_disposal_code(code)
William Stein's avatar
William Stein committed
4522 4523
        code.putln(
            "if (!%s) break;" %
4524
                self.condition.result())
4525
        self.condition.free_temps(code)
William Stein's avatar
William Stein committed
4526
        self.body.generate_execution_code(code)
4527
        code.put_label(code.continue_label)
William Stein's avatar
William Stein committed
4528 4529 4530 4531 4532 4533 4534 4535 4536
        code.putln("}")
        break_label = code.break_label
        code.set_loop_labels(old_loop_labels)
        if self.else_clause:
            code.putln("/*else*/ {")
            self.else_clause.generate_execution_code(code)
            code.putln("}")
        code.put_label(break_label)

4537 4538 4539 4540 4541 4542
    def generate_function_definitions(self, env, code):
        self.condition.generate_function_definitions(env, code)
        self.body.generate_function_definitions(env, code)
        if self.else_clause is not None:
            self.else_clause.generate_function_definitions(env, code)

4543 4544 4545 4546 4547 4548
    def annotate(self, code):
        self.condition.annotate(code)
        self.body.annotate(code)
        if self.else_clause:
            self.else_clause.annotate(code)

William Stein's avatar
William Stein committed
4549

Robert Bradshaw's avatar
Robert Bradshaw committed
4550
def ForStatNode(pos, **kw):
4551
    if 'iterator' in kw:
Robert Bradshaw's avatar
Robert Bradshaw committed
4552 4553 4554 4555
        return ForInStatNode(pos, **kw)
    else:
        return ForFromStatNode(pos, **kw)

4556
class ForInStatNode(LoopNode, StatNode):
William Stein's avatar
William Stein committed
4557 4558 4559 4560 4561 4562 4563
    #  for statement
    #
    #  target        ExprNode
    #  iterator      IteratorNode
    #  body          StatNode
    #  else_clause   StatNode
    #  item          NextNode       used internally
4564

4565
    child_attrs = ["target", "iterator", "body", "else_clause"]
4566
    item = None
4567

William Stein's avatar
William Stein committed
4568 4569 4570 4571 4572
    def analyse_declarations(self, env):
        self.target.analyse_target_declaration(env)
        self.body.analyse_declarations(env)
        if self.else_clause:
            self.else_clause.analyse_declarations(env)
4573

William Stein's avatar
William Stein committed
4574 4575 4576
    def analyse_expressions(self, env):
        import ExprNodes
        self.target.analyse_target_types(env)
4577
        self.iterator.analyse_expressions(env)
William Stein's avatar
William Stein committed
4578
        self.item = ExprNodes.NextNode(self.iterator, env)
4579 4580 4581 4582 4583 4584
        if (self.iterator.type.is_ptr or self.iterator.type.is_array) and \
            self.target.type.assignable_from(self.iterator.type):
            # C array slice optimization.
            pass
        else:
            self.item = self.item.coerce_to(self.target.type, env)
William Stein's avatar
William Stein committed
4585 4586 4587 4588 4589 4590
        self.body.analyse_expressions(env)
        if self.else_clause:
            self.else_clause.analyse_expressions(env)

    def generate_execution_code(self, code):
        old_loop_labels = code.new_loop_labels()
4591
        self.iterator.allocate_counter_temp(code)
William Stein's avatar
William Stein committed
4592
        self.iterator.generate_evaluation_code(code)
Mark Florisson's avatar
Mark Florisson committed
4593
        code.putln("for (;;) {")
William Stein's avatar
William Stein committed
4594 4595 4596
        self.item.generate_evaluation_code(code)
        self.target.generate_assignment_code(self.item, code)
        self.body.generate_execution_code(code)
4597
        code.put_label(code.continue_label)
Mark Florisson's avatar
Mark Florisson committed
4598
        code.putln("}")
William Stein's avatar
William Stein committed
4599 4600
        break_label = code.break_label
        code.set_loop_labels(old_loop_labels)
4601

William Stein's avatar
William Stein committed
4602
        if self.else_clause:
4603 4604 4605 4606 4607 4608 4609
            # in nested loops, the 'else' block can contain a
            # 'continue' statement for the outer loop, but we may need
            # to generate cleanup code before taking that path, so we
            # intercept it here
            orig_continue_label = code.continue_label
            code.continue_label = code.new_label('outer_continue')

William Stein's avatar
William Stein committed
4610 4611 4612
            code.putln("/*else*/ {")
            self.else_clause.generate_execution_code(code)
            code.putln("}")
4613 4614 4615 4616 4617 4618 4619 4620 4621 4622

            if code.label_used(code.continue_label):
                code.put_goto(break_label)
                code.put_label(code.continue_label)
                self.iterator.generate_disposal_code(code)
                code.put_goto(orig_continue_label)
            code.set_loop_labels(old_loop_labels)

        if code.label_used(break_label):
            code.put_label(break_label)
4623
        self.iterator.release_counter_temp(code)
William Stein's avatar
William Stein committed
4624
        self.iterator.generate_disposal_code(code)
4625
        self.iterator.free_temps(code)
William Stein's avatar
William Stein committed
4626

4627 4628 4629 4630 4631 4632 4633
    def generate_function_definitions(self, env, code):
        self.target.generate_function_definitions(env, code)
        self.iterator.generate_function_definitions(env, code)
        self.body.generate_function_definitions(env, code)
        if self.else_clause is not None:
            self.else_clause.generate_function_definitions(env, code)

4634 4635 4636 4637 4638 4639 4640 4641
    def annotate(self, code):
        self.target.annotate(code)
        self.iterator.annotate(code)
        self.body.annotate(code)
        if self.else_clause:
            self.else_clause.annotate(code)
        self.item.annotate(code)

William Stein's avatar
William Stein committed
4642

4643
class ForFromStatNode(LoopNode, StatNode):
William Stein's avatar
William Stein committed
4644 4645 4646 4647 4648 4649 4650
    #  for name from expr rel name rel expr
    #
    #  target        NameNode
    #  bound1        ExprNode
    #  relation1     string
    #  relation2     string
    #  bound2        ExprNode
4651
    #  step          ExprNode or None
William Stein's avatar
William Stein committed
4652 4653 4654 4655 4656
    #  body          StatNode
    #  else_clause   StatNode or None
    #
    #  Used internally:
    #
Robert Bradshaw's avatar
Robert Bradshaw committed
4657
    #  from_range         bool
4658
    #  is_py_target       bool
4659
    #  loopvar_node       ExprNode (usually a NameNode or temp node)
William Stein's avatar
William Stein committed
4660
    #  py_loopvar_node    PyTempNode or None
4661
    child_attrs = ["target", "bound1", "bound2", "step", "body", "else_clause"]
4662 4663

    is_py_target = False
4664
    loopvar_node = None
4665
    py_loopvar_node = None
Robert Bradshaw's avatar
Robert Bradshaw committed
4666
    from_range = False
4667

4668 4669 4670 4671 4672 4673 4674
    gil_message = "For-loop using object bounds or target"

    def nogil_check(self, env):
        for x in (self.target, self.bound1, self.bound2):
            if x.type.is_pyobject:
                self.gil_error()

Robert Bradshaw's avatar
Robert Bradshaw committed
4675 4676 4677 4678 4679
    def analyse_declarations(self, env):
        self.target.analyse_target_declaration(env)
        self.body.analyse_declarations(env)
        if self.else_clause:
            self.else_clause.analyse_declarations(env)
4680

William Stein's avatar
William Stein committed
4681 4682 4683 4684 4685
    def analyse_expressions(self, env):
        import ExprNodes
        self.target.analyse_target_types(env)
        self.bound1.analyse_types(env)
        self.bound2.analyse_types(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
4686 4687 4688 4689
        if self.step is not None:
            if isinstance(self.step, ExprNodes.UnaryMinusNode):
                warning(self.step.pos, "Probable infinite loop in for-from-by statment. Consider switching the directions of the relations.", 2)
            self.step.analyse_types(env)
4690

Robert Bradshaw's avatar
Robert Bradshaw committed
4691
        target_type = self.target.type
4692
        if self.target.type.is_numeric:
Robert Bradshaw's avatar
Robert Bradshaw committed
4693
            loop_type = self.target.type
4694
        else:
Robert Bradshaw's avatar
Robert Bradshaw committed
4695 4696 4697 4698 4699 4700 4701 4702 4703
            loop_type = PyrexTypes.c_int_type
            if not self.bound1.type.is_pyobject:
                loop_type = PyrexTypes.widest_numeric_type(loop_type, self.bound1.type)
            if not self.bound2.type.is_pyobject:
                loop_type = PyrexTypes.widest_numeric_type(loop_type, self.bound2.type)
            if self.step is not None and not self.step.type.is_pyobject:
                loop_type = PyrexTypes.widest_numeric_type(loop_type, self.step.type)
        self.bound1 = self.bound1.coerce_to(loop_type, env)
        self.bound2 = self.bound2.coerce_to(loop_type, env)
Robert Bradshaw's avatar
Robert Bradshaw committed
4704 4705
        if not self.bound2.is_literal:
            self.bound2 = self.bound2.coerce_to_temp(env)
4706
        if self.step is not None:
4707
            self.step = self.step.coerce_to(loop_type, env)
Robert Bradshaw's avatar
Robert Bradshaw committed
4708 4709
            if not self.step.is_literal:
                self.step = self.step.coerce_to_temp(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
4710

William Stein's avatar
William Stein committed
4711
        target_type = self.target.type
4712
        if not (target_type.is_pyobject or target_type.is_numeric):
4713
            error(self.target.pos,
Robert Bradshaw's avatar
Robert Bradshaw committed
4714
                "for-from loop variable must be c numeric type or Python object")
4715
        if target_type.is_numeric:
Robert Bradshaw's avatar
Robert Bradshaw committed
4716
            self.is_py_target = False
4717 4718
            if isinstance(self.target, ExprNodes.IndexNode) and self.target.is_buffer_access:
                raise error(self.pos, "Buffer indexing not allowed as for loop target.")
4719
            self.loopvar_node = self.target
William Stein's avatar
William Stein committed
4720 4721
            self.py_loopvar_node = None
        else:
Robert Bradshaw's avatar
Robert Bradshaw committed
4722 4723
            self.is_py_target = True
            c_loopvar_node = ExprNodes.TempNode(self.pos, loop_type, env)
4724
            self.loopvar_node = c_loopvar_node
William Stein's avatar
William Stein committed
4725 4726 4727 4728 4729
            self.py_loopvar_node = \
                ExprNodes.CloneNode(c_loopvar_node).coerce_to_pyobject(env)
        self.body.analyse_expressions(env)
        if self.else_clause:
            self.else_clause.analyse_expressions(env)
4730

William Stein's avatar
William Stein committed
4731 4732
    def generate_execution_code(self, code):
        old_loop_labels = code.new_loop_labels()
Robert Bradshaw's avatar
Robert Bradshaw committed
4733
        from_range = self.from_range
William Stein's avatar
William Stein committed
4734 4735 4736
        self.bound1.generate_evaluation_code(code)
        self.bound2.generate_evaluation_code(code)
        offset, incop = self.relation_table[self.relation1]
4737 4738
        if self.step is not None:
            self.step.generate_evaluation_code(code)
Magnus Lie Hetland's avatar
Magnus Lie Hetland committed
4739 4740
            step = self.step.result()
            incop = "%s=%s" % (incop[0], step)
4741 4742 4743 4744 4745
        import ExprNodes
        if isinstance(self.loopvar_node, ExprNodes.TempNode):
            self.loopvar_node.allocate(code)
        if isinstance(self.py_loopvar_node, ExprNodes.TempNode):
            self.py_loopvar_node.allocate(code)
4746
        if from_range:
Robert Bradshaw's avatar
Robert Bradshaw committed
4747
            loopvar_name = code.funcstate.allocate_temp(self.target.type, False)
4748
        else:
Robert Bradshaw's avatar
Robert Bradshaw committed
4749
            loopvar_name = self.loopvar_node.result()
William Stein's avatar
William Stein committed
4750 4751
        code.putln(
            "for (%s = %s%s; %s %s %s; %s%s) {" % (
4752
                loopvar_name,
4753
                self.bound1.result(), offset,
Robert Bradshaw's avatar
Robert Bradshaw committed
4754
                loopvar_name, self.relation2, self.bound2.result(),
4755
                loopvar_name, incop))
William Stein's avatar
William Stein committed
4756 4757 4758
        if self.py_loopvar_node:
            self.py_loopvar_node.generate_evaluation_code(code)
            self.target.generate_assignment_code(self.py_loopvar_node, code)
Robert Bradshaw's avatar
Robert Bradshaw committed
4759 4760 4761
        elif from_range:
            code.putln("%s = %s;" % (
                            self.target.result(), loopvar_name))
William Stein's avatar
William Stein committed
4762 4763
        self.body.generate_execution_code(code)
        code.put_label(code.continue_label)
Robert Bradshaw's avatar
Robert Bradshaw committed
4764
        if self.py_loopvar_node:
4765 4766 4767
            # This mess is to make for..from loops with python targets behave
            # exactly like those with C targets with regards to re-assignment
            # of the loop variable.
4768
            import ExprNodes
4769
            if self.target.entry.is_pyglobal:
4770
                # We know target is a NameNode, this is the only ugly case.
4771
                target_node = ExprNodes.PyTempNode(self.target.pos, None)
4772 4773
                target_node.allocate(code)
                interned_cname = code.intern_identifier(self.target.entry.name)
4774
                code.globalstate.use_utility_code(ExprNodes.get_name_interned_utility_code)
4775
                code.putln("%s = __Pyx_GetName(%s, %s); %s" % (
4776
                                target_node.result(),
4777
                                Naming.module_cname,
4778 4779 4780
                                interned_cname,
                                code.error_goto_if_null(target_node.result(), self.target.pos)))
                code.put_gotref(target_node.result())
4781 4782 4783
            else:
                target_node = self.target
            from_py_node = ExprNodes.CoerceFromPyTypeNode(self.loopvar_node.type, target_node, None)
4784 4785
            from_py_node.temp_code = loopvar_name
            from_py_node.generate_result_code(code)
4786
            if self.target.entry.is_pyglobal:
4787 4788
                code.put_decref(target_node.result(), target_node.type)
                target_node.release(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
4789
        code.putln("}")
4790
        if self.py_loopvar_node:
4791 4792
            # This is potentially wasteful, but we don't want the semantics to
            # depend on whether or not the loop is a python type.
4793 4794
            self.py_loopvar_node.generate_evaluation_code(code)
            self.target.generate_assignment_code(self.py_loopvar_node, code)
4795 4796
        if from_range:
            code.funcstate.release_temp(loopvar_name)
William Stein's avatar
William Stein committed
4797 4798 4799 4800 4801 4802 4803 4804
        break_label = code.break_label
        code.set_loop_labels(old_loop_labels)
        if self.else_clause:
            code.putln("/*else*/ {")
            self.else_clause.generate_execution_code(code)
            code.putln("}")
        code.put_label(break_label)
        self.bound1.generate_disposal_code(code)
4805
        self.bound1.free_temps(code)
William Stein's avatar
William Stein committed
4806
        self.bound2.generate_disposal_code(code)
4807
        self.bound2.free_temps(code)
4808 4809 4810 4811
        if isinstance(self.loopvar_node, ExprNodes.TempNode):
            self.loopvar_node.release(code)
        if isinstance(self.py_loopvar_node, ExprNodes.TempNode):
            self.py_loopvar_node.release(code)
4812 4813
        if self.step is not None:
            self.step.generate_disposal_code(code)
4814
            self.step.free_temps(code)
4815

William Stein's avatar
William Stein committed
4816 4817 4818 4819 4820 4821 4822
    relation_table = {
        # {relop : (initial offset, increment op)}
        '<=': ("",   "++"),
        '<' : ("+1", "++"),
        '>=': ("",   "--"),
        '>' : ("-1", "--")
    }
4823 4824 4825 4826 4827 4828 4829 4830 4831 4832

    def generate_function_definitions(self, env, code):
        self.target.generate_function_definitions(env, code)
        self.bound1.generate_function_definitions(env, code)
        self.bound2.generate_function_definitions(env, code)
        if self.step is not None:
            self.step.generate_function_definitions(env, code)
        self.body.generate_function_definitions(env, code)
        if self.else_clause is not None:
            self.else_clause.generate_function_definitions(env, code)
4833

4834 4835 4836 4837 4838
    def annotate(self, code):
        self.target.annotate(code)
        self.bound1.annotate(code)
        self.bound2.annotate(code)
        if self.step:
4839
            self.step.annotate(code)
4840 4841 4842
        self.body.annotate(code)
        if self.else_clause:
            self.else_clause.annotate(code)
William Stein's avatar
William Stein committed
4843 4844


4845 4846 4847
class WithStatNode(StatNode):
    """
    Represents a Python with statement.
4848

4849
    Implemented by the WithTransform as follows:
4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866

        MGR = EXPR
        EXIT = MGR.__exit__
        VALUE = MGR.__enter__()
        EXC = True
        try:
            try:
                TARGET = VALUE  # optional
                BODY
            except:
                EXC = False
                if not EXIT(*EXCINFO):
                    raise
        finally:
            if EXC:
                EXIT(None, None, None)
            MGR = EXIT = VALUE = None
4867 4868
    """
    #  manager          The with statement manager object
4869
    #  target           ExprNode  the target lhs of the __enter__() call
4870
    #  body             StatNode
4871

4872
    child_attrs = ["manager", "target", "body"]
4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883

    has_target = False

    def analyse_declarations(self, env):
        self.manager.analyse_declarations(env)
        self.body.analyse_declarations(env)

    def analyse_expressions(self, env):
        self.manager.analyse_types(env)
        self.body.analyse_expressions(env)

4884 4885 4886 4887
    def generate_function_definitions(self, env, code):
        self.manager.generate_function_definitions(env, code)
        self.body.generate_function_definitions(env, code)

4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975
    def generate_execution_code(self, code):
        code.putln("/*with:*/ {")
        self.manager.generate_evaluation_code(code)
        self.exit_var = code.funcstate.allocate_temp(py_object_type, manage_ref=False)
        code.putln("%s = PyObject_GetAttr(%s, %s); %s" % (
            self.exit_var,
            self.manager.py_result(),
            code.get_py_string_const(EncodedString('__exit__'), identifier=True),
            code.error_goto_if_null(self.exit_var, self.pos),
            ))
        code.put_gotref(self.exit_var)

        # need to free exit_var in the face of exceptions during setup
        old_error_label = code.new_error_label()
        intermediate_error_label = code.error_label

        enter_func = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
        code.putln("%s = PyObject_GetAttr(%s, %s); %s" % (
            enter_func,
            self.manager.py_result(),
            code.get_py_string_const(EncodedString('__enter__'), identifier=True),
            code.error_goto_if_null(enter_func, self.pos),
            ))
        code.put_gotref(enter_func)
        self.manager.generate_disposal_code(code)
        self.manager.free_temps(code)
        self.target_temp.allocate(code)
        code.putln('%s = PyObject_Call(%s, ((PyObject *)%s), NULL); %s' % (
            self.target_temp.result(),
            enter_func,
            Naming.empty_tuple,
            code.error_goto_if_null(self.target_temp.result(), self.pos),
            ))
        code.put_gotref(self.target_temp.result())
        code.put_decref_clear(enter_func, py_object_type)
        code.funcstate.release_temp(enter_func)
        if not self.has_target:
            code.put_decref_clear(self.target_temp.result(), type=py_object_type)
            self.target_temp.release(code)
            # otherwise, WithTargetAssignmentStatNode will do it for us

        code.error_label = old_error_label
        self.body.generate_execution_code(code)

        step_over_label = code.new_label()
        code.put_goto(step_over_label)
        code.put_label(intermediate_error_label)
        code.put_decref_clear(self.exit_var, py_object_type)
        code.put_goto(old_error_label)
        code.put_label(step_over_label)

        code.funcstate.release_temp(self.exit_var)
        code.putln('}')

class WithTargetAssignmentStatNode(AssignmentNode):
    # The target assignment of the 'with' statement value (return
    # value of the __enter__() call).
    #
    # This is a special cased assignment that steals the RHS reference
    # and frees its temp.
    #
    # lhs  ExprNode  the assignment target
    # rhs  TempNode  the return value of the __enter__() call

    child_attrs = ["lhs", "rhs"]

    def analyse_declarations(self, env):
        self.lhs.analyse_target_declaration(env)

    def analyse_types(self, env):
        self.rhs.analyse_types(env)
        self.lhs.analyse_target_types(env)
        self.lhs.gil_assignment_check(env)
        self.orig_rhs = self.rhs
        self.rhs = self.rhs.coerce_to(self.lhs.type, env)

    def generate_execution_code(self, code):
        self.rhs.generate_evaluation_code(code)
        self.lhs.generate_assignment_code(self.rhs, code)
        self.orig_rhs.release(code)

    def generate_function_definitions(self, env, code):
        self.rhs.generate_function_definitions(env, code)

    def annotate(self, code):
        self.lhs.annotate(code)
        self.rhs.annotate(code)

4976

William Stein's avatar
William Stein committed
4977 4978 4979 4980 4981 4982
class TryExceptStatNode(StatNode):
    #  try .. except statement
    #
    #  body             StatNode
    #  except_clauses   [ExceptClauseNode]
    #  else_clause      StatNode or None
4983

4984
    child_attrs = ["body", "except_clauses", "else_clause"]
4985

4986 4987 4988
    def analyse_control_flow(self, env):
        env.start_branching(self.pos)
        self.body.analyse_control_flow(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
4989 4990 4991
        successful_try = env.control_flow # grab this for later
        env.next_branch(self.body.end_pos())
        env.finish_branching(self.body.end_pos())
4992

Robert Bradshaw's avatar
Robert Bradshaw committed
4993
        env.start_branching(self.except_clauses[0].pos)
4994 4995
        for except_clause in self.except_clauses:
            except_clause.analyse_control_flow(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
4996
            env.next_branch(except_clause.end_pos())
4997

Robert Bradshaw's avatar
Robert Bradshaw committed
4998 4999
        # the else cause it executed only when the try clause finishes
        env.control_flow.incoming = successful_try
5000 5001 5002 5003
        if self.else_clause:
            self.else_clause.analyse_control_flow(env)
        env.finish_branching(self.end_pos())

William Stein's avatar
William Stein committed
5004 5005 5006 5007 5008 5009
    def analyse_declarations(self, env):
        self.body.analyse_declarations(env)
        for except_clause in self.except_clauses:
            except_clause.analyse_declarations(env)
        if self.else_clause:
            self.else_clause.analyse_declarations(env)
5010
        env.use_utility_code(reset_exception_utility_code)
5011

William Stein's avatar
William Stein committed
5012 5013
    def analyse_expressions(self, env):
        self.body.analyse_expressions(env)
5014
        default_clause_seen = 0
William Stein's avatar
William Stein committed
5015 5016
        for except_clause in self.except_clauses:
            except_clause.analyse_expressions(env)
5017 5018 5019 5020 5021
            if default_clause_seen:
                error(except_clause.pos, "default 'except:' must be last")
            if not except_clause.pattern:
                default_clause_seen = 1
        self.has_default_clause = default_clause_seen
William Stein's avatar
William Stein committed
5022 5023
        if self.else_clause:
            self.else_clause.analyse_expressions(env)
5024

5025
    nogil_check = Node.gil_error
5026 5027
    gil_message = "Try-except statement"

William Stein's avatar
William Stein committed
5028
    def generate_execution_code(self, code):
5029
        old_return_label = code.return_label
5030
        old_break_label = code.break_label
5031
        old_continue_label = code.continue_label
William Stein's avatar
William Stein committed
5032 5033
        old_error_label = code.new_error_label()
        our_error_label = code.error_label
5034 5035 5036
        except_end_label = code.new_label('exception_handled')
        except_error_label = code.new_label('except_error')
        except_return_label = code.new_label('except_return')
5037
        try_return_label = code.new_label('try_return')
5038
        try_break_label = code.new_label('try_break')
5039
        try_continue_label = code.new_label('try_continue')
5040
        try_end_label = code.new_label('try_end')
5041

5042 5043
        exc_save_vars = [code.funcstate.allocate_temp(py_object_type, False)
                         for i in xrange(3)]
5044 5045
        code.putln("{")
        code.putln("__Pyx_ExceptionSave(%s);" %
5046 5047
                   ', '.join(['&%s' % var for var in exc_save_vars]))
        for var in exc_save_vars:
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
5048
            code.put_xgotref(var)
William Stein's avatar
William Stein committed
5049 5050
        code.putln(
            "/*try:*/ {")
5051
        code.return_label = try_return_label
5052
        code.break_label = try_break_label
5053
        code.continue_label = try_continue_label
William Stein's avatar
William Stein committed
5054 5055 5056
        self.body.generate_execution_code(code)
        code.putln(
            "}")
5057
        temps_to_clean_up = code.funcstate.all_free_managed_temps()
5058 5059
        code.error_label = except_error_label
        code.return_label = except_return_label
William Stein's avatar
William Stein committed
5060 5061 5062 5063 5064 5065
        if self.else_clause:
            code.putln(
                "/*else:*/ {")
            self.else_clause.generate_execution_code(code)
            code.putln(
                "}")
5066
        for var in exc_save_vars:
5067
            code.put_xdecref_clear(var, py_object_type)
5068
        code.put_goto(try_end_label)
5069 5070
        if code.label_used(try_return_label):
            code.put_label(try_return_label)
Stefan Behnel's avatar
Stefan Behnel committed
5071 5072
            for var in exc_save_vars:
                code.put_xgiveref(var)
5073
            code.putln("__Pyx_ExceptionReset(%s);" %
5074
                       ', '.join(exc_save_vars))
5075
            code.put_goto(old_return_label)
William Stein's avatar
William Stein committed
5076
        code.put_label(our_error_label)
5077 5078
        for temp_name, type in temps_to_clean_up:
            code.put_xdecref_clear(temp_name, type)
William Stein's avatar
William Stein committed
5079
        for except_clause in self.except_clauses:
5080 5081
            except_clause.generate_handling_code(code, except_end_label)

5082 5083 5084 5085
        error_label_used = code.label_used(except_error_label)
        if error_label_used or not self.has_default_clause:
            if error_label_used:
                code.put_label(except_error_label)
Stefan Behnel's avatar
Stefan Behnel committed
5086 5087
            for var in exc_save_vars:
                code.put_xgiveref(var)
Stefan Behnel's avatar
Stefan Behnel committed
5088
            code.putln("__Pyx_ExceptionReset(%s);" %
5089
                       ', '.join(exc_save_vars))
5090 5091
            code.put_goto(old_error_label)

5092 5093 5094 5095 5096 5097
        for exit_label, old_label in zip(
            [try_break_label, try_continue_label, except_return_label],
            [old_break_label, old_continue_label, old_return_label]):

            if code.label_used(exit_label):
                code.put_label(exit_label)
Stefan Behnel's avatar
Stefan Behnel committed
5098 5099
                for var in exc_save_vars:
                    code.put_xgiveref(var)
5100
                code.putln("__Pyx_ExceptionReset(%s);" %
5101
                           ', '.join(exc_save_vars))
5102
                code.put_goto(old_label)
5103 5104 5105

        if code.label_used(except_end_label):
            code.put_label(except_end_label)
Stefan Behnel's avatar
Stefan Behnel committed
5106 5107
            for var in exc_save_vars:
                code.put_xgiveref(var)
5108
            code.putln("__Pyx_ExceptionReset(%s);" %
5109
                       ', '.join(exc_save_vars))
5110 5111 5112
        code.put_label(try_end_label)
        code.putln("}")

5113 5114 5115
        for cname in exc_save_vars:
            code.funcstate.release_temp(cname)

5116
        code.return_label = old_return_label
5117
        code.break_label = old_break_label
5118
        code.continue_label = old_continue_label
5119
        code.error_label = old_error_label
William Stein's avatar
William Stein committed
5120

5121 5122 5123 5124 5125 5126 5127
    def generate_function_definitions(self, env, code):
        self.body.generate_function_definitions(env, code)
        for except_clause in self.except_clauses:
            except_clause.generate_function_definitions(env, code)
        if self.else_clause is not None:
            self.else_clause.generate_function_definitions(env, code)

5128 5129 5130 5131 5132 5133 5134
    def annotate(self, code):
        self.body.annotate(code)
        for except_node in self.except_clauses:
            except_node.annotate(code)
        if self.else_clause:
            self.else_clause.annotate(code)

William Stein's avatar
William Stein committed
5135 5136 5137 5138

class ExceptClauseNode(Node):
    #  Part of try ... except statement.
    #
5139
    #  pattern        [ExprNode]
William Stein's avatar
William Stein committed
5140 5141
    #  target         ExprNode or None
    #  body           StatNode
5142
    #  excinfo_target ResultRefNode or None   optional target for exception info
William Stein's avatar
William Stein committed
5143 5144 5145
    #  match_flag     string             result of exception match
    #  exc_value      ExcValueNode       used internally
    #  function_name  string             qualified name of enclosing function
5146
    #  exc_vars       (string * 3)       local exception variables
5147 5148 5149 5150

    # excinfo_target is never set by the parser, but can be set by a transform
    # in order to extract more extensive information about the exception as a
    # sys.exc_info()-style tuple into a target variable
5151

5152
    child_attrs = ["pattern", "target", "body", "exc_value", "excinfo_target"]
5153

5154
    exc_value = None
5155
    excinfo_target = None
5156

William Stein's avatar
William Stein committed
5157 5158 5159 5160
    def analyse_declarations(self, env):
        if self.target:
            self.target.analyse_target_declaration(env)
        self.body.analyse_declarations(env)
5161

William Stein's avatar
William Stein committed
5162 5163 5164 5165 5166
    def analyse_expressions(self, env):
        import ExprNodes
        genv = env.global_scope()
        self.function_name = env.qualified_name
        if self.pattern:
5167 5168 5169 5170
            # normalise/unpack self.pattern into a list
            for i, pattern in enumerate(self.pattern):
                pattern.analyse_expressions(env)
                self.pattern[i] = pattern.coerce_to_pyobject(env)
5171

William Stein's avatar
William Stein committed
5172
        if self.target:
5173
            self.exc_value = ExprNodes.ExcValueNode(self.pos, env)
5174
            self.target.analyse_target_expression(env, self.exc_value)
5175 5176 5177
        if self.excinfo_target is not None:
            import ExprNodes
            self.excinfo_tuple = ExprNodes.TupleNode(pos=self.pos, args=[
5178
                ExprNodes.ExcValueNode(pos=self.pos, env=env) for x in range(3)])
5179 5180
            self.excinfo_tuple.analyse_expressions(env)

William Stein's avatar
William Stein committed
5181
        self.body.analyse_expressions(env)
5182

William Stein's avatar
William Stein committed
5183 5184 5185
    def generate_handling_code(self, code, end_label):
        code.mark_pos(self.pos)
        if self.pattern:
5186 5187 5188 5189 5190
            exc_tests = []
            for pattern in self.pattern:
                pattern.generate_evaluation_code(code)
                exc_tests.append("PyErr_ExceptionMatches(%s)" % pattern.py_result())

5191
            match_flag = code.funcstate.allocate_temp(PyrexTypes.c_int_type, False)
William Stein's avatar
William Stein committed
5192
            code.putln(
5193 5194 5195 5196
                "%s = %s;" % (match_flag, ' || '.join(exc_tests)))
            for pattern in self.pattern:
                pattern.generate_disposal_code(code)
                pattern.free_temps(code)
William Stein's avatar
William Stein committed
5197 5198
            code.putln(
                "if (%s) {" %
5199 5200
                    match_flag)
            code.funcstate.release_temp(match_flag)
William Stein's avatar
William Stein committed
5201
        else:
5202
            code.putln("/*except:*/ {")
5203

Stefan Behnel's avatar
fix  
Stefan Behnel committed
5204
        if not getattr(self.body, 'stats', True) and \
Stefan Behnel's avatar
Stefan Behnel committed
5205
                self.excinfo_target is None and self.target is None:
Stefan Behnel's avatar
Stefan Behnel committed
5206 5207
            # most simple case: no exception variable, empty body (pass)
            # => reset the exception state, done
5208 5209 5210 5211
            code.putln("PyErr_Restore(0,0,0);")
            code.put_goto(end_label)
            code.putln("}")
            return
5212

5213 5214 5215
        exc_vars = [code.funcstate.allocate_temp(py_object_type,
                                                 manage_ref=True)
                    for i in xrange(3)]
5216
        code.putln('__Pyx_AddTraceback("%s");' % self.function_name)
William Stein's avatar
William Stein committed
5217
        # We always have to fetch the exception value even if
5218
        # there is no target, because this also normalises the
William Stein's avatar
William Stein committed
5219
        # exception and stores it in the thread state.
5220 5221
        code.globalstate.use_utility_code(get_exception_utility_code)
        exc_args = "&%s, &%s, &%s" % tuple(exc_vars)
5222 5223
        code.putln("if (__Pyx_GetException(%s) < 0) %s" % (exc_args,
            code.error_goto(self.pos)))
5224
        for x in exc_vars:
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
5225
            code.put_gotref(x)
William Stein's avatar
William Stein committed
5226
        if self.target:
5227
            self.exc_value.set_var(exc_vars[1])
5228
            self.exc_value.generate_evaluation_code(code)
William Stein's avatar
William Stein committed
5229
            self.target.generate_assignment_code(self.exc_value, code)
5230
        if self.excinfo_target is not None:
5231 5232
            for tempvar, node in zip(exc_vars, self.excinfo_tuple.args):
                node.set_var(tempvar)
5233
            self.excinfo_tuple.generate_evaluation_code(code)
5234
            self.excinfo_target.result_code = self.excinfo_tuple.result()
5235

5236 5237 5238 5239
        old_break_label, old_continue_label = code.break_label, code.continue_label
        code.break_label = code.new_label('except_break')
        code.continue_label = code.new_label('except_continue')

5240
        old_exc_vars = code.funcstate.exc_vars
5241
        code.funcstate.exc_vars = exc_vars
William Stein's avatar
William Stein committed
5242
        self.body.generate_execution_code(code)
5243
        code.funcstate.exc_vars = old_exc_vars
5244 5245
        if self.excinfo_target is not None:
            self.excinfo_tuple.generate_disposal_code(code)
5246
        for var in exc_vars:
5247
            code.put_decref_clear(var, py_object_type)
5248
        code.put_goto(end_label)
5249

Robert Bradshaw's avatar
Robert Bradshaw committed
5250 5251
        if code.label_used(code.break_label):
            code.put_label(code.break_label)
5252 5253
            if self.excinfo_target is not None:
                self.excinfo_tuple.generate_disposal_code(code)
5254
            for var in exc_vars:
5255
                code.put_decref_clear(var, py_object_type)
Robert Bradshaw's avatar
Robert Bradshaw committed
5256 5257
            code.put_goto(old_break_label)
        code.break_label = old_break_label
5258 5259 5260

        if code.label_used(code.continue_label):
            code.put_label(code.continue_label)
5261 5262
            if self.excinfo_target is not None:
                self.excinfo_tuple.generate_disposal_code(code)
5263
            for var in exc_vars:
5264
                code.put_decref_clear(var, py_object_type)
5265 5266
            code.put_goto(old_continue_label)
        code.continue_label = old_continue_label
5267

5268 5269
        if self.excinfo_target is not None:
            self.excinfo_tuple.free_temps(code)
5270 5271
        for temp in exc_vars:
            code.funcstate.release_temp(temp)
5272

William Stein's avatar
William Stein committed
5273 5274 5275
        code.putln(
            "}")

5276 5277 5278 5279
    def generate_function_definitions(self, env, code):
        if self.target is not None:
            self.target.generate_function_definitions(env, code)
        self.body.generate_function_definitions(env, code)
5280

5281
    def annotate(self, code):
5282
        if self.pattern:
5283 5284
            for pattern in self.pattern:
                pattern.annotate(code)
5285 5286 5287 5288
        if self.target:
            self.target.annotate(code)
        self.body.annotate(code)

William Stein's avatar
William Stein committed
5289 5290 5291 5292 5293 5294

class TryFinallyStatNode(StatNode):
    #  try ... finally statement
    #
    #  body             StatNode
    #  finally_clause   StatNode
5295
    #
William Stein's avatar
William Stein committed
5296 5297 5298 5299 5300 5301 5302 5303
    #  The plan is that we funnel all continue, break
    #  return and error gotos into the beginning of the
    #  finally block, setting a variable to remember which
    #  one we're doing. At the end of the finally block, we
    #  switch on the variable to figure out where to go.
    #  In addition, if we're doing an error, we save the
    #  exception on entry to the finally block and restore
    #  it on exit.
5304

5305
    child_attrs = ["body", "finally_clause"]
5306

5307
    preserve_exception = 1
5308

5309 5310 5311
    # handle exception case, in addition to return/break/continue
    handle_error_case = True

William Stein's avatar
William Stein committed
5312 5313 5314 5315
    disallow_continue_in_try_finally = 0
    # There doesn't seem to be any point in disallowing
    # continue in the try block, since we have no problem
    # handling it.
5316 5317 5318 5319 5320

    def create_analysed(pos, env, body, finally_clause):
        node = TryFinallyStatNode(pos, body=body, finally_clause=finally_clause)
        return node
    create_analysed = staticmethod(create_analysed)
5321

5322 5323 5324 5325
    def analyse_control_flow(self, env):
        env.start_branching(self.pos)
        self.body.analyse_control_flow(env)
        env.next_branch(self.body.end_pos())
Robert Bradshaw's avatar
Robert Bradshaw committed
5326
        env.finish_branching(self.body.end_pos())
5327 5328
        self.finally_clause.analyse_control_flow(env)

William Stein's avatar
William Stein committed
5329 5330 5331
    def analyse_declarations(self, env):
        self.body.analyse_declarations(env)
        self.finally_clause.analyse_declarations(env)
5332

William Stein's avatar
William Stein committed
5333 5334 5335
    def analyse_expressions(self, env):
        self.body.analyse_expressions(env)
        self.finally_clause.analyse_expressions(env)
5336

5337
    nogil_check = Node.gil_error
5338 5339
    gil_message = "Try-finally statement"

William Stein's avatar
William Stein committed
5340 5341 5342 5343 5344
    def generate_execution_code(self, code):
        old_error_label = code.error_label
        old_labels = code.all_new_labels()
        new_labels = code.get_all_labels()
        new_error_label = code.error_label
5345 5346
        if not self.handle_error_case:
            code.error_label = old_error_label
William Stein's avatar
William Stein committed
5347 5348 5349 5350
        catch_label = code.new_label()
        code.putln(
            "/*try:*/ {")
        if self.disallow_continue_in_try_finally:
5351 5352
            was_in_try_finally = code.funcstate.in_try_finally
            code.funcstate.in_try_finally = 1
William Stein's avatar
William Stein committed
5353 5354
        self.body.generate_execution_code(code)
        if self.disallow_continue_in_try_finally:
5355
            code.funcstate.in_try_finally = was_in_try_finally
William Stein's avatar
William Stein committed
5356 5357
        code.putln(
            "}")
5358
        temps_to_clean_up = code.funcstate.all_free_managed_temps()
5359
        code.mark_pos(self.finally_clause.pos)
William Stein's avatar
William Stein committed
5360 5361
        code.putln(
            "/*finally:*/ {")
5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377
        cases_used = []
        error_label_used = 0
        for i, new_label in enumerate(new_labels):
            if new_label in code.labels_used:
                cases_used.append(i)
                if new_label == new_error_label:
                    error_label_used = 1
                    error_label_case = i
        if cases_used:
            code.putln(
                    "int __pyx_why;")
            if error_label_used and self.preserve_exception:
                code.putln(
                    "PyObject *%s, *%s, *%s;" % Naming.exc_vars)
                code.putln(
                    "int %s;" % Naming.exc_lineno_name)
5378 5379 5380 5381 5382
                exc_var_init_zero = ''.join(["%s = 0; " % var for var in Naming.exc_vars])
                exc_var_init_zero += '%s = 0;' % Naming.exc_lineno_name
                code.putln(exc_var_init_zero)
            else:
                exc_var_init_zero = None
5383 5384 5385 5386 5387
            code.use_label(catch_label)
            code.putln(
                    "__pyx_why = 0; goto %s;" % catch_label)
            for i in cases_used:
                new_label = new_labels[i]
Stefan Behnel's avatar
Stefan Behnel committed
5388
                #if new_label and new_label != "<try>":
5389
                if new_label == new_error_label and self.preserve_exception:
5390
                    self.put_error_catcher(code,
5391
                        new_error_label, i+1, catch_label, temps_to_clean_up)
5392
                else:
5393 5394 5395 5396
                    code.put('%s: ' % new_label)
                    if exc_var_init_zero:
                        code.putln(exc_var_init_zero)
                    code.putln("__pyx_why = %s; goto %s;" % (
5397 5398 5399
                            i+1,
                            catch_label))
            code.put_label(catch_label)
William Stein's avatar
William Stein committed
5400
        code.set_all_labels(old_labels)
5401 5402 5403
        if error_label_used:
            code.new_error_label()
            finally_error_label = code.error_label
William Stein's avatar
William Stein committed
5404
        self.finally_clause.generate_execution_code(code)
5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418
        if error_label_used:
            if finally_error_label in code.labels_used and self.preserve_exception:
                over_label = code.new_label()
                code.put_goto(over_label);
                code.put_label(finally_error_label)
                code.putln("if (__pyx_why == %d) {" % (error_label_case + 1))
                for var in Naming.exc_vars:
                    code.putln("Py_XDECREF(%s);" % var)
                code.putln("}")
                code.put_goto(old_error_label)
                code.put_label(over_label)
            code.error_label = old_error_label
        if cases_used:
            code.putln(
William Stein's avatar
William Stein committed
5419
                "switch (__pyx_why) {")
5420 5421 5422
            for i in cases_used:
                old_label = old_labels[i]
                if old_label == old_error_label and self.preserve_exception:
William Stein's avatar
William Stein committed
5423 5424
                    self.put_error_uncatcher(code, i+1, old_error_label)
                else:
5425
                    code.use_label(old_label)
William Stein's avatar
William Stein committed
5426 5427 5428
                    code.putln(
                        "case %s: goto %s;" % (
                            i+1,
5429 5430
                            old_label))
            code.putln(
5431
                "}")
William Stein's avatar
William Stein committed
5432 5433 5434
        code.putln(
            "}")

5435 5436 5437 5438
    def generate_function_definitions(self, env, code):
        self.body.generate_function_definitions(env, code)
        self.finally_clause.generate_function_definitions(env, code)

5439
    def put_error_catcher(self, code, error_label, i, catch_label, temps_to_clean_up):
5440
        code.globalstate.use_utility_code(restore_exception_utility_code)
William Stein's avatar
William Stein committed
5441 5442 5443 5444 5445 5446
        code.putln(
            "%s: {" %
                error_label)
        code.putln(
                "__pyx_why = %s;" %
                    i)
5447 5448
        for temp_name, type in temps_to_clean_up:
            code.put_xdecref_clear(temp_name, type)
William Stein's avatar
William Stein committed
5449
        code.putln(
5450
                "__Pyx_ErrFetch(&%s, &%s, &%s);" %
5451
                    Naming.exc_vars)
William Stein's avatar
William Stein committed
5452 5453
        code.putln(
                "%s = %s;" % (
Robert Bradshaw's avatar
Robert Bradshaw committed
5454
                    Naming.exc_lineno_name, Naming.lineno_cname))
5455
        code.put_goto(catch_label)
Robert Bradshaw's avatar
Robert Bradshaw committed
5456
        code.putln("}")
5457

William Stein's avatar
William Stein committed
5458
    def put_error_uncatcher(self, code, i, error_label):
5459
        code.globalstate.use_utility_code(restore_exception_utility_code)
William Stein's avatar
William Stein committed
5460 5461 5462 5463
        code.putln(
            "case %s: {" %
                i)
        code.putln(
5464
                "__Pyx_ErrRestore(%s, %s, %s);" %
5465
                    Naming.exc_vars)
William Stein's avatar
William Stein committed
5466 5467
        code.putln(
                "%s = %s;" % (
5468 5469
                    Naming.lineno_cname, Naming.exc_lineno_name))
        for var in Naming.exc_vars:
William Stein's avatar
William Stein committed
5470 5471 5472
            code.putln(
                "%s = 0;" %
                    var)
5473
        code.put_goto(error_label)
William Stein's avatar
William Stein committed
5474 5475 5476
        code.putln(
            "}")

5477 5478 5479 5480
    def annotate(self, code):
        self.body.annotate(code)
        self.finally_clause.annotate(code)

William Stein's avatar
William Stein committed
5481

5482 5483 5484 5485
class GILStatNode(TryFinallyStatNode):
    #  'with gil' or 'with nogil' statement
    #
    #   state   string   'gil' or 'nogil'
5486 5487

#    child_attrs = []
5488

5489 5490 5491 5492 5493 5494 5495 5496
    preserve_exception = 0

    def __init__(self, pos, state, body):
        self.state = state
        TryFinallyStatNode.__init__(self, pos,
            body = body,
            finally_clause = GILExitNode(pos, state = state))

5497
    def analyse_expressions(self, env):
Stefan Behnel's avatar
Stefan Behnel committed
5498
        env.use_utility_code(force_init_threads_utility_code)
5499 5500 5501 5502 5503
        was_nogil = env.nogil
        env.nogil = 1
        TryFinallyStatNode.analyse_expressions(self, env)
        env.nogil = was_nogil

5504
    nogil_check = None
5505

5506
    def generate_execution_code(self, code):
Stefan Behnel's avatar
Stefan Behnel committed
5507
        code.mark_pos(self.pos)
5508
        code.putln("{")
5509
        if self.state == 'gil':
5510
            code.putln("#ifdef WITH_THREAD")
5511
            code.putln("PyGILState_STATE _save = PyGILState_Ensure();")
5512
            code.putln("#endif")
5513
        else:
5514
            code.putln("#ifdef WITH_THREAD")
5515
            code.putln("PyThreadState *_save = NULL;")
5516
            code.putln("#endif")
5517 5518 5519 5520 5521 5522 5523 5524 5525 5526
            code.putln("Py_UNBLOCK_THREADS")
        TryFinallyStatNode.generate_execution_code(self, code)
        code.putln("}")


class GILExitNode(StatNode):
    #  Used as the 'finally' block in a GILStatNode
    #
    #  state   string   'gil' or 'nogil'

5527 5528
    child_attrs = []

5529 5530 5531 5532 5533
    def analyse_expressions(self, env):
        pass

    def generate_execution_code(self, code):
        if self.state == 'gil':
5534
            code.putln("#ifdef WITH_THREAD")
5535
            code.putln("PyGILState_Release(_save);")
5536
            code.putln("#endif")
5537 5538 5539 5540
        else:
            code.putln("Py_BLOCK_THREADS")


William Stein's avatar
William Stein committed
5541 5542 5543 5544 5545
class CImportStatNode(StatNode):
    #  cimport statement
    #
    #  module_name   string           Qualified name of module being imported
    #  as_name       string or None   Name specified in "as" clause, if any
5546 5547

    child_attrs = []
5548

William Stein's avatar
William Stein committed
5549
    def analyse_declarations(self, env):
5550 5551 5552
        if not env.is_module_scope:
            error(self.pos, "cimport only allowed at module level")
            return
William Stein's avatar
William Stein committed
5553 5554
        module_scope = env.find_module(self.module_name, self.pos)
        if "." in self.module_name:
5555
            names = [EncodedString(name) for name in self.module_name.split(".")]
William Stein's avatar
William Stein committed
5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572
            top_name = names[0]
            top_module_scope = env.context.find_submodule(top_name)
            module_scope = top_module_scope
            for name in names[1:]:
                submodule_scope = module_scope.find_submodule(name)
                module_scope.declare_module(name, submodule_scope, self.pos)
                module_scope = submodule_scope
            if self.as_name:
                env.declare_module(self.as_name, module_scope, self.pos)
            else:
                env.declare_module(top_name, top_module_scope, self.pos)
        else:
            name = self.as_name or self.module_name
            env.declare_module(name, module_scope, self.pos)

    def analyse_expressions(self, env):
        pass
5573

William Stein's avatar
William Stein committed
5574 5575
    def generate_execution_code(self, code):
        pass
5576

William Stein's avatar
William Stein committed
5577 5578 5579 5580

class FromCImportStatNode(StatNode):
    #  from ... cimport statement
    #
5581 5582
    #  module_name     string                        Qualified name of module
    #  imported_names  [(pos, name, as_name, kind)]  Names to be imported
5583

5584 5585
    child_attrs = []

William Stein's avatar
William Stein committed
5586
    def analyse_declarations(self, env):
5587 5588 5589
        if not env.is_module_scope:
            error(self.pos, "cimport only allowed at module level")
            return
William Stein's avatar
William Stein committed
5590 5591
        module_scope = env.find_module(self.module_name, self.pos)
        env.add_imported_module(module_scope)
5592
        for pos, name, as_name, kind in self.imported_names:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5593 5594 5595 5596
            if name == "*":
                for local_name, entry in module_scope.entries.items():
                    env.add_imported_entry(local_name, entry, pos)
            else:
5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608
                entry = module_scope.lookup(name)
                if entry:
                    if kind and not self.declaration_matches(entry, kind):
                        entry.redeclared(pos)
                else:
                    if kind == 'struct' or kind == 'union':
                        entry = module_scope.declare_struct_or_union(name,
                            kind = kind, scope = None, typedef_flag = 0, pos = pos)
                    elif kind == 'class':
                        entry = module_scope.declare_c_class(name, pos = pos,
                            module_name = self.module_name)
                    else:
5609 5610 5611 5612 5613 5614
                        submodule_scope = env.context.find_module(name, relative_to = module_scope, pos = self.pos)
                        if submodule_scope.parent_module is module_scope:
                            env.declare_module(as_name or name, submodule_scope, self.pos)
                        else:
                            error(pos, "Name '%s' not declared in module '%s'"
                                % (name, self.module_name))
5615

Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5616 5617 5618
                if entry:
                    local_name = as_name or name
                    env.add_imported_entry(local_name, entry, pos)
5619

5620
    def declaration_matches(self, entry, kind):
5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632
        if not entry.is_type:
            return 0
        type = entry.type
        if kind == 'class':
            if not type.is_extension_type:
                return 0
        else:
            if not type.is_struct_or_union:
                return 0
            if kind != type.kind:
                return 0
        return 1
William Stein's avatar
William Stein committed
5633 5634 5635

    def analyse_expressions(self, env):
        pass
5636

William Stein's avatar
William Stein committed
5637 5638 5639 5640 5641 5642 5643 5644 5645
    def generate_execution_code(self, code):
        pass


class FromImportStatNode(StatNode):
    #  from ... import statement
    #
    #  module           ImportNode
    #  items            [(string, NameNode)]
5646
    #  interned_items   [(string, NameNode, ExprNode)]
William Stein's avatar
William Stein committed
5647
    #  item             PyTempNode            used internally
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5648
    #  import_star      boolean               used internally
5649 5650

    child_attrs = ["module"]
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5651
    import_star = 0
5652

William Stein's avatar
William Stein committed
5653
    def analyse_declarations(self, env):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5654 5655 5656 5657 5658 5659 5660 5661 5662
        for name, target in self.items:
            if name == "*":
                if not env.is_module_scope:
                    error(self.pos, "import * only allowed at module level")
                    return
                env.has_import_star = 1
                self.import_star = 1
            else:
                target.analyse_target_declaration(env)
5663

William Stein's avatar
William Stein committed
5664 5665 5666
    def analyse_expressions(self, env):
        import ExprNodes
        self.module.analyse_expressions(env)
5667
        self.item = ExprNodes.RawCNameExprNode(self.pos, py_object_type)
William Stein's avatar
William Stein committed
5668 5669
        self.interned_items = []
        for name, target in self.items:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5670 5671 5672 5673 5674 5675
            if name == '*':
                for _, entry in env.entries.items():
                    if not entry.is_type and entry.type.is_extension_type:
                        env.use_utility_code(ExprNodes.type_test_utility_code)
                        break
            else:
5676
                entry =  env.lookup(target.name)
5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689
                # check whether or not entry is already cimported
                if (entry.is_type and entry.type.name == name
                    and hasattr(entry.type, 'module_name')):
                    if entry.type.module_name == self.module.module_name.value:
                        # cimported with absolute name
                        continue
                    try:
                        # cimported with relative name
                        module = env.find_module(self.module.module_name.value,
                                                 pos=None)
                        if entry.type.module_name == module.qualified_name:
                            continue
                    except AttributeError:
5690
                        pass
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5691
                target.analyse_target_expression(env, None)
5692 5693 5694 5695
                if target.type is py_object_type:
                    coerced_item = None
                else:
                    coerced_item = self.item.coerce_to(target.type, env)
5696
                self.interned_items.append((name, target, coerced_item))
5697

William Stein's avatar
William Stein committed
5698 5699
    def generate_execution_code(self, code):
        self.module.generate_evaluation_code(code)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5700 5701 5702 5703 5704 5705
        if self.import_star:
            code.putln(
                'if (%s(%s) < 0) %s;' % (
                    Naming.import_star,
                    self.module.py_result(),
                    code.error_goto(self.pos)))
5706 5707
        item_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
        self.item.set_cname(item_temp)
5708 5709
        for name, target, coerced_item in self.interned_items:
            cname = code.intern_identifier(name)
5710 5711
            code.putln(
                '%s = PyObject_GetAttr(%s, %s); %s' % (
5712
                    item_temp,
5713 5714
                    self.module.py_result(),
                    cname,
5715 5716
                    code.error_goto_if_null(item_temp, self.pos)))
            code.put_gotref(item_temp)
5717 5718 5719 5720 5721 5722
            if coerced_item is None:
                target.generate_assignment_code(self.item, code)
            else:
                coerced_item.allocate_temp_result(code)
                coerced_item.generate_result_code(code)
                target.generate_assignment_code(coerced_item, code)
5723 5724
            code.put_decref_clear(item_temp, py_object_type)
        code.funcstate.release_temp(item_temp)
William Stein's avatar
William Stein committed
5725
        self.module.generate_disposal_code(code)
5726
        self.module.free_temps(code)
William Stein's avatar
William Stein committed
5727

5728

Mark Florisson's avatar
Mark Florisson committed
5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766
class ParallelNode(Node):
    """
    Base class for cython.parallel constructs.
    """

    nogil_check = None


class ParallelStatNode(StatNode, ParallelNode):
    """
    Base class for 'with cython.parallel.parallel:' and 'for i in prange():'.

    assignments     { Entry(var) : (var.pos, inplace_operator_or_None) }
                    assignments to variables in this parallel section

    parent          parent ParallelStatNode or None
    is_parallel     indicates whether this is a parallel node

    is_parallel is true for:

        #pragma omp parallel
        #pragma omp parallel for

    sections, but NOT for

        #pragma omp for

    We need this to determine the sharing attributes.
    """

    child_attrs = ['body']

    body = None

    is_prange = False

    def __init__(self, pos, **kwargs):
        super(ParallelStatNode, self).__init__(pos, **kwargs)
5767 5768

        # All assignments in this scope
Mark Florisson's avatar
Mark Florisson committed
5769 5770
        self.assignments = kwargs.get('assignments') or {}

5771 5772 5773 5774 5775 5776
        # All seen closure cnames and their temporary cnames
        self.seen_closure_vars = set()

        # Dict of variables that should be declared (first|last|)private or
        # reduction { Entry: op }. If op is not None, it's a reduction.
        self.privates = {}
Mark Florisson's avatar
Mark Florisson committed
5777 5778 5779 5780

    def analyse_declarations(self, env):
        self.body.analyse_declarations(env)

5781 5782 5783 5784
    def analyse_expressions(self, env):
        self.body.analyse_expressions(env)

    def analyse_sharing_attributes(self, env):
Mark Florisson's avatar
Mark Florisson committed
5785
        """
5786 5787 5788
        Analyse the privates for this block and set them in self.privates.
        This should be called in a post-order fashion during the
        analyse_expressions phase
Mark Florisson's avatar
Mark Florisson committed
5789
        """
5790 5791 5792
        for entry, (pos, op) in self.assignments.iteritems():
            if self.is_private(entry):
                self.propagate_var_privatization(entry, op)
Mark Florisson's avatar
Mark Florisson committed
5793 5794 5795 5796 5797 5798

    def is_private(self, entry):
        """
        True if this scope should declare the variable private, lastprivate
        or reduction.
        """
5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830
        return (self.is_parallel or
                (self.parent and entry not in self.parent.privates))

    def propagate_var_privatization(self, entry, op):
        """
        Propagate the sharing attributes of a variable. If the privatization is
        determined by a parent scope, done propagate further.

        If we are a prange, we propagate our sharing attributes outwards to
        other pranges. If we are a prange in parallel block and the parallel
        block does not determine the variable private, we propagate to the
        parent of the parent. Recursion stops at parallel blocks, as they have
        no concept of lastprivate or reduction.

        So the following cases propagate:

            sum is a reduction for all loops:

                for i in prange(n):
                    for j in prange(n):
                        for k in prange(n):
                            sum += i * j * k

            sum is a reduction for both loops, local_var is private to the
            parallel with block:

                for i in prange(n):
                    with parallel:
                        local_var = ... # private to the parallel
                        for j in prange(n):
                            sum += i * j

Mark Florisson's avatar
Mark Florisson committed
5831 5832
        Nested with parallel blocks are disallowed, because they wouldn't
        allow you to propagate lastprivates or reductions:
5833 5834 5835 5836

            #pragma omp parallel for lastprivate(i)
            for i in prange(n):

Mark Florisson's avatar
Mark Florisson committed
5837 5838
                sum = 0

5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861
                #pragma omp parallel private(j, sum)
                with parallel:

                    #pragma omp parallel
                    with parallel:

                        #pragma omp for lastprivate(j) reduction(+:sum)
                        for j in prange(n):
                            sum += i

                    # sum and j are well-defined here

                # sum and j are undefined here

            # sum and j are undefined here
        """
        self.privates[entry] = op
        if self.is_prange:
            if not self.is_parallel and entry not in self.parent.assignments:
                # Parent is a parallel with block
                parent = self.parent.parent
            else:
                parent = self.parent
Mark Florisson's avatar
Mark Florisson committed
5862

5863 5864
            if parent:
                parent.propagate_var_privatization(entry, op)
Mark Florisson's avatar
Mark Florisson committed
5865 5866 5867 5868 5869 5870 5871 5872 5873

    def _allocate_closure_temp(self, code, entry):
        """
        Helper function that allocate a temporary for a closure variable that
        is assigned to.
        """
        if self.parent:
            return self.parent._allocate_closure_temp(code, entry)

5874 5875 5876
        if entry.cname in self.seen_closure_vars:
            return entry.cname

Mark Florisson's avatar
Mark Florisson committed
5877
        cname = code.funcstate.allocate_temp(entry.type, False)
5878 5879 5880 5881 5882 5883

        # Add both the actual cname and the temp cname, as the actual cname
        # will be replaced with the temp cname on the entry
        self.seen_closure_vars.add(entry.cname)
        self.seen_closure_vars.add(cname)

Mark Florisson's avatar
Mark Florisson committed
5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903
        self.modified_entries.append((entry, entry.cname))
        code.putln("%s = %s;" % (cname, entry.cname))
        entry.cname = cname

    def declare_closure_privates(self, code):
        """
        Set self.privates to a dict mapping C variable names that are to be
        declared (first|last)private or reduction, to the reduction operator.
        If the private is not a reduction, the operator is None.
        This is used by subclasses.

        If a variable is in a scope object, we need to allocate a temp and
        assign the value from the temp to the variable in the scope object
        after the parallel section. This kind of copying should be done only
        in the outermost parallel section.
        """
        self.modified_entries = []

        for entry, (pos, op) in self.assignments.iteritems():
            if entry.from_closure or entry.in_closure:
5904
                self._allocate_closure_temp(code, entry)
Mark Florisson's avatar
Mark Florisson committed
5905 5906

    def release_closure_privates(self, code):
5907 5908 5909 5910 5911
        """
        Release any temps used for variables in scope objects. As this is the
        outermost parallel block, we don't need to delete the cnames from
        self.seen_closure_vars
        """
Mark Florisson's avatar
Mark Florisson committed
5912 5913 5914 5915 5916 5917 5918 5919
        for entry, original_cname in self.modified_entries:
            code.putln("%s = %s;" % (original_cname, entry.cname))
            code.funcstate.release_temp(entry.cname)
            entry.cname = original_cname


class ParallelWithBlockNode(ParallelStatNode):
    """
5920
    This node represents a 'with cython.parallel.parallel:' block
Mark Florisson's avatar
Mark Florisson committed
5921 5922 5923 5924
    """

    nogil_check = None

5925 5926 5927 5928
    def analyse_expressions(self, env):
        super(ParallelWithBlockNode, self).analyse_expressions(env)
        self.analyse_sharing_attributes(env)

Mark Florisson's avatar
Mark Florisson committed
5929 5930 5931 5932 5933
    def generate_execution_code(self, code):
        self.declare_closure_privates(code)

        code.putln("#ifdef _OPENMP")
        code.put("#pragma omp parallel ")
5934 5935 5936 5937 5938 5939 5940 5941

        if self.privates:
            code.put(
                'private(%s)' % ', '.join([e.cname for e in self.privates]))

        code.putln("")
        code.putln("#endif /* _OPENMP */")

Mark Florisson's avatar
Mark Florisson committed
5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968
        code.begin_block()
        self.body.generate_execution_code(code)
        code.end_block()

        self.release_closure_privates(code)


class ParallelRangeNode(ParallelStatNode):
    """
    This node represents a 'for i in cython.parallel.prange():' construct.

    target       NameNode       the target iteration variable
    else_clause  Node or None   the else clause of this loop
    args         tuple          the arguments passed to prange()
    kwargs       DictNode       the keyword arguments passed to prange()
                                (replaced by its compile time value)

    is_nogil     bool           indicates whether this is a nogil prange() node
    """

    child_attrs = ['body', 'target', 'else_clause', 'args']

    body = target = else_clause = args = None

    start = stop = step = None

    is_prange = True
5969
    is_nogil = False
Mark Florisson's avatar
Mark Florisson committed
5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995

    def analyse_declarations(self, env):
        super(ParallelRangeNode, self).analyse_declarations(env)
        self.target.analyse_target_declaration(env)
        if self.else_clause is not None:
            self.else_clause.analyse_declarations(env)

        if not self.args or len(self.args) > 3:
            error(self.pos, "Invalid number of positional arguments to prange")
            return

        if len(self.args) == 1:
            self.stop, = self.args
        elif len(self.args) == 2:
            self.start, self.stop = self.args
        else:
            self.start, self.stop, self.step = self.args

        if self.kwargs:
            self.kwargs = self.kwargs.compile_time_value(env)
        else:
            self.kwargs = {}

        self.is_nogil = self.kwargs.pop('nogil', False)
        self.schedule = self.kwargs.pop('schedule', None)

Mark Florisson's avatar
Mark Florisson committed
5996 5997 5998
        if hasattr(self.schedule, 'decode'):
            self.schedule = self.schedule.decode('ascii')

Mark Florisson's avatar
Mark Florisson committed
5999 6000 6001 6002 6003 6004 6005 6006 6007
        if self.schedule not in (None, 'static', 'dynamic', 'guided',
                                 'runtime'):
            error(self.pos, "Invalid schedule argument to prange: %r" %
                                                        (self.schedule,))

        for kw in self.kwargs:
            error(self.pos, "Invalid keyword argument to prange: %s" % kw)

    def analyse_expressions(self, env):
6008 6009 6010
        if self.target is None:
            error(self.pos, "prange() can only be used as part of a for loop")
            return
Mark Florisson's avatar
Mark Florisson committed
6011

6012
        self.target.analyse_target_types(env)
Mark Florisson's avatar
Mark Florisson committed
6013

6014 6015 6016 6017 6018 6019 6020 6021
        if not self.target.type.is_numeric:
            # Not a valid type, assume one for now anyway

            if not self.target.type.is_pyobject:
                # nogil_check will catch the is_pyobject case
                error(self.target.pos,
                      "Must be of numeric type, not %s" % self.target.type)

6022
            self.index_type = PyrexTypes.c_py_ssize_t_type
6023 6024
        else:
            self.index_type = self.target.type
Mark Florisson's avatar
Mark Florisson committed
6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046

        # Setup start, stop and step, allocating temps if needed
        self.names = 'start', 'stop', 'step'
        start_stop_step = self.start, self.stop, self.step

        for node, name in zip(start_stop_step, self.names):
            if node is not None:
                node.analyse_types(env)
                if not node.type.is_numeric:
                    error(node.pos, "%s argument must be numeric or a pointer "
                                    "(perhaps if a numeric literal is too "
                                    "big, use 1000LL)" % name)

                if not node.is_literal:
                    node = node.coerce_to_temp(env)
                    setattr(self, name, node)

                # As we range from 0 to nsteps, computing the index along the
                # way, we need a fitting type for 'i' and 'nsteps'
                self.index_type = PyrexTypes.widest_numeric_type(
                                        self.index_type, node.type)

6047
        super(ParallelRangeNode, self).analyse_expressions(env)
Mark Florisson's avatar
Mark Florisson committed
6048 6049 6050
        if self.else_clause is not None:
            self.else_clause.analyse_expressions(env)

6051 6052 6053 6054 6055 6056 6057 6058 6059 6060
        # Although not actually an assignment in this scope, it should be
        # treated as such to ensure it is unpacked if a closure temp, and to
        # ensure lastprivate behaviour and propagation. If the target index is
        # not a NameNode, it won't have an entry, and an error was issued by
        # ParallelRangeTransform
        if hasattr(self.target, 'entry'):
            self.assignments[self.target.entry] = self.target.pos, None

        self.analyse_sharing_attributes(env)

Mark Florisson's avatar
Mark Florisson committed
6061 6062
    def nogil_check(self, env):
        names = 'start', 'stop', 'step', 'target'
6063
        nodes = self.start, self.stop, self.step, self.target
Mark Florisson's avatar
Mark Florisson committed
6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108
        for name, node in zip(names, nodes):
            if node is not None and node.type.is_pyobject:
                error(node.pos, "%s may not be a Python object "
                                "as we don't have the GIL" % name)

    def generate_execution_code(self, code):
        """
        Generate code in the following steps

            1)  copy any closure variables determined thread-private
                into temporaries

            2)  allocate temps for start, stop and step

            3)  generate a loop that calculates the total number of steps,
                which then computes the target iteration variable for every step:

                    for i in prange(start, stop, step):
                        ...

                becomes

                    nsteps = (stop - start) / step;
                    i = start;

                    #pragma omp parallel for lastprivate(i)
                    for (temp = 0; temp < nsteps; temp++) {
                        i = start + step * temp;
                        ...
                    }

                Note that accumulation of 'i' would have a data dependency
                between iterations.

                Also, you can't do this

                    for (i = start; i < stop; i += step)
                        ...

                as the '<' operator should become '>' for descending loops.
                'for i from x < i < y:' does not suffer from this problem
                as the relational operator is known at compile time!

            4) release our temps and write back any private closure variables
        """
6109
        self.declare_closure_privates(code)
Mark Florisson's avatar
Mark Florisson committed
6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146

        # This can only be a NameNode
        target_index_cname = self.target.entry.cname

        # This will be used as the dict to format our code strings, holding
        # the start, stop , step, temps and target cnames
        fmt_dict = {
            'target': target_index_cname,
        }

        # Setup start, stop and step, allocating temps if needed
        start_stop_step = self.start, self.stop, self.step
        defaults = '0', '0', '1'
        for node, name, default in zip(start_stop_step, self.names, defaults):
            if node is None:
                result = default
            elif node.is_literal:
                result = node.get_constant_c_result_code()
            else:
                node.generate_evaluation_code(code)
                result = node.result()

            fmt_dict[name] = result

        fmt_dict['i'] = code.funcstate.allocate_temp(self.index_type, False)
        fmt_dict['nsteps'] = code.funcstate.allocate_temp(self.index_type, False)

        # TODO: check if the step is 0 and if so, raise an exception in a
        # 'with gil' block. For now, just abort
        code.putln("if (%(step)s == 0) abort();" % fmt_dict)

        # Guard for never-ending loops: prange(0, 10, -1) or prange(10, 0, 1)
        # range() returns [] in these cases
        code.put("if ( (%(start)s < %(stop)s && %(step)s > 0) || "
                      "(%(start)s > %(stop)s && %(step)s < 0) ) " % fmt_dict)
        code.begin_block()

6147
        code.putln_openmp("#pragma omp critical")
Mark Florisson's avatar
Mark Florisson committed
6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174
        code.putln("%(nsteps)s = (%(stop)s - %(start)s) / %(step)s;" % fmt_dict)

        self.generate_loop(code, fmt_dict)

        # And finally, release our privates and write back any closure
        # variables
        for temp in start_stop_step:
            if temp is not None:
                temp.generate_disposal_code(code)
                temp.free_temps(code)

        code.funcstate.release_temp(fmt_dict['i'])
        code.funcstate.release_temp(fmt_dict['nsteps'])

        self.release_closure_privates(code)

        # end the 'if' block that guards against infinite loops
        code.end_block()

    def generate_loop(self, code, fmt_dict):
        code.putln("#ifdef _OPENMP")

        if not self.is_parallel:
            code.put("#pragma omp for")
        else:
            code.put("#pragma omp parallel for")

6175
        for entry, op in self.privates.iteritems():
Mark Florisson's avatar
Mark Florisson committed
6176
            # Don't declare the index variable as a reduction
6177 6178 6179 6180
            if op and op in "+*-&^|" and entry != self.target.entry:
                code.put(" reduction(%s:%s)" % (op, entry.cname))
            else:
                code.put(" lastprivate(%s)" % entry.cname)
Mark Florisson's avatar
Mark Florisson committed
6181 6182 6183 6184

        if self.schedule:
            code.put(" schedule(%s)" % self.schedule)

6185 6186
        code.putln("")
        code.putln("#endif /* _OPENMP */")
Mark Florisson's avatar
Mark Florisson committed
6187 6188 6189 6190 6191 6192 6193

        code.put("for (%(i)s = 0; %(i)s < %(nsteps)s; %(i)s++)" % fmt_dict)
        code.begin_block()
        code.putln("%(target)s = %(start)s + %(step)s * %(i)s;" % fmt_dict)
        self.body.generate_execution_code(code)
        code.end_block()

6194

6195 6196


William Stein's avatar
William Stein committed
6197 6198 6199 6200 6201 6202 6203 6204
#------------------------------------------------------------------------------------
#
#  Runtime support code
#
#------------------------------------------------------------------------------------

utility_function_predeclarations = \
"""
6205
/* inline attribute */
6206
#ifndef CYTHON_INLINE
6207
  #if defined(__GNUC__)
6208
    #define CYTHON_INLINE __inline__
6209
  #elif defined(_MSC_VER)
6210
    #define CYTHON_INLINE __inline
Robert Bradshaw's avatar
Robert Bradshaw committed
6211 6212
  #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
    #define CYTHON_INLINE inline
6213
  #else
6214
    #define CYTHON_INLINE
6215
  #endif
6216 6217
#endif

6218 6219 6220 6221
/* unused attribute */
#ifndef CYTHON_UNUSED
# if defined(__GNUC__)
#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
6222
#     define CYTHON_UNUSED __attribute__ ((__unused__))
6223 6224 6225 6226
#   else
#     define CYTHON_UNUSED
#   endif
# elif defined(__ICC) || defined(__INTEL_COMPILER)
6227
#   define CYTHON_UNUSED __attribute__ ((__unused__))
6228
# else
6229
#   define CYTHON_UNUSED
6230 6231 6232
# endif
#endif

6233
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*/
6234

Robert Bradshaw's avatar
Robert Bradshaw committed
6235
"""
Robert Bradshaw's avatar
Robert Bradshaw committed
6236 6237 6238 6239

if Options.gcc_branch_hints:
    branch_prediction_macros = \
    """
6240
#ifdef __GNUC__
6241
/* Test for GCC > 2.95 */
6242
#if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))
Robert Bradshaw's avatar
Robert Bradshaw committed
6243 6244
#define likely(x)   __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
6245 6246 6247 6248
#else /* __GNUC__ > 2 ... */
#define likely(x)   (x)
#define unlikely(x) (x)
#endif /* __GNUC__ > 2 ... */
6249 6250 6251 6252
#else /* __GNUC__ */
#define likely(x)   (x)
#define unlikely(x) (x)
#endif /* __GNUC__ */
Robert Bradshaw's avatar
Robert Bradshaw committed
6253 6254 6255 6256 6257 6258 6259
    """
else:
    branch_prediction_macros = \
    """
#define likely(x)   (x)
#define unlikely(x) (x)
    """
William Stein's avatar
William Stein committed
6260

6261 6262
#get_name_predeclaration = \
#"static PyObject *__Pyx_GetName(PyObject *dict, char *name); /*proto*/"
William Stein's avatar
William Stein committed
6263

6264 6265
#get_name_interned_predeclaration = \
#"static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/"
William Stein's avatar
William Stein committed
6266 6267 6268

#------------------------------------------------------------------------------------

6269 6270
printing_utility_code = UtilityCode(
proto = """
6271
static int __Pyx_Print(PyObject*, PyObject *, int); /*proto*/
6272
#if PY_MAJOR_VERSION >= 3
6273 6274 6275
static PyObject* %s = 0;
static PyObject* %s = 0;
#endif
6276
""" % (Naming.print_function, Naming.print_function_kwargs),
6277 6278 6279 6280 6281 6282
cleanup = """
#if PY_MAJOR_VERSION >= 3
Py_CLEAR(%s);
Py_CLEAR(%s);
#endif
""" % (Naming.print_function, Naming.print_function_kwargs),
6283
impl = r"""
6284
#if PY_MAJOR_VERSION < 3
William Stein's avatar
William Stein committed
6285
static PyObject *__Pyx_GetStdout(void) {
6286
    PyObject *f = PySys_GetObject((char *)"stdout");
William Stein's avatar
William Stein committed
6287 6288 6289 6290 6291 6292
    if (!f) {
        PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
    }
    return f;
}

6293
static int __Pyx_Print(PyObject* f, PyObject *arg_tuple, int newline) {
6294 6295
    PyObject* v;
    int i;
6296

6297 6298 6299 6300
    if (!f) {
        if (!(f = __Pyx_GetStdout()))
            return -1;
    }
6301 6302 6303 6304 6305 6306 6307
    for (i=0; i < PyTuple_GET_SIZE(arg_tuple); i++) {
        if (PyFile_SoftSpace(f, 1)) {
            if (PyFile_WriteString(" ", f) < 0)
                return -1;
        }
        v = PyTuple_GET_ITEM(arg_tuple, i);
        if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0)
William Stein's avatar
William Stein committed
6308
            return -1;
6309 6310 6311 6312 6313 6314 6315 6316
        if (PyString_Check(v)) {
            char *s = PyString_AsString(v);
            Py_ssize_t len = PyString_Size(v);
            if (len > 0 &&
                isspace(Py_CHARMASK(s[len-1])) &&
                s[len-1] != ' ')
                    PyFile_SoftSpace(f, 0);
        }
William Stein's avatar
William Stein committed
6317
    }
6318 6319 6320 6321
    if (newline) {
        if (PyFile_WriteString("\n", f) < 0)
            return -1;
        PyFile_SoftSpace(f, 0);
William Stein's avatar
William Stein committed
6322 6323 6324 6325
    }
    return 0;
}

6326
#else /* Python 3 has a print function */
6327

6328
static int __Pyx_Print(PyObject* stream, PyObject *arg_tuple, int newline) {
6329 6330 6331
    PyObject* kwargs = 0;
    PyObject* result = 0;
    PyObject* end_string;
6332
    if (unlikely(!%(PRINT_FUNCTION)s)) {
6333
        %(PRINT_FUNCTION)s = __Pyx_GetAttrString(%(BUILTINS)s, "print");
6334
        if (!%(PRINT_FUNCTION)s)
6335
            return -1;
6336
    }
6337 6338 6339 6340 6341 6342
    if (stream) {
        kwargs = PyDict_New();
        if (unlikely(!kwargs))
            return -1;
        if (unlikely(PyDict_SetItemString(kwargs, "file", stream) < 0))
            goto bad;
6343 6344 6345 6346 6347 6348 6349 6350 6351
        if (!newline) {
            end_string = PyUnicode_FromStringAndSize(" ", 1);
            if (unlikely(!end_string))
                goto bad;
            if (PyDict_SetItemString(kwargs, "end", end_string) < 0) {
                Py_DECREF(end_string);
                goto bad;
            }
            Py_DECREF(end_string);
6352
        }
6353 6354
    } else if (!newline) {
        if (unlikely(!%(PRINT_KWARGS)s)) {
6355
            %(PRINT_KWARGS)s = PyDict_New();
6356
            if (unlikely(!%(PRINT_KWARGS)s))
6357
                return -1;
6358 6359
            end_string = PyUnicode_FromStringAndSize(" ", 1);
            if (unlikely(!end_string))
Stefan Behnel's avatar
Stefan Behnel committed
6360
                return -1;
6361 6362
            if (PyDict_SetItemString(%(PRINT_KWARGS)s, "end", end_string) < 0) {
                Py_DECREF(end_string);
Stefan Behnel's avatar
Stefan Behnel committed
6363
                return -1;
6364
            }
6365 6366
            Py_DECREF(end_string);
        }
6367
        kwargs = %(PRINT_KWARGS)s;
6368 6369
    }
    result = PyObject_Call(%(PRINT_FUNCTION)s, arg_tuple, kwargs);
6370
    if (unlikely(kwargs) && (kwargs != %(PRINT_KWARGS)s))
6371
        Py_DECREF(kwargs);
6372
    if (!result)
William Stein's avatar
William Stein committed
6373
        return -1;
6374
    Py_DECREF(result);
William Stein's avatar
William Stein committed
6375
    return 0;
6376
bad:
6377
    if (kwargs != %(PRINT_KWARGS)s)
6378 6379
        Py_XDECREF(kwargs);
    return -1;
William Stein's avatar
William Stein committed
6380
}
6381

6382 6383 6384 6385 6386 6387 6388 6389 6390
#endif
""" % {'BUILTINS'       : Naming.builtins_cname,
       'PRINT_FUNCTION' : Naming.print_function,
       'PRINT_KWARGS'   : Naming.print_function_kwargs}
)


printing_one_utility_code = UtilityCode(
proto = """
6391
static int __Pyx_PrintOne(PyObject* stream, PyObject *o); /*proto*/
6392 6393 6394 6395
""",
impl = r"""
#if PY_MAJOR_VERSION < 3

6396 6397 6398 6399 6400
static int __Pyx_PrintOne(PyObject* f, PyObject *o) {
    if (!f) {
        if (!(f = __Pyx_GetStdout()))
            return -1;
    }
6401 6402 6403 6404 6405 6406 6407 6408 6409
    if (PyFile_SoftSpace(f, 0)) {
        if (PyFile_WriteString(" ", f) < 0)
            return -1;
    }
    if (PyFile_WriteObject(o, f, Py_PRINT_RAW) < 0)
        return -1;
    if (PyFile_WriteString("\n", f) < 0)
        return -1;
    return 0;
6410 6411
    /* the line below is just to avoid compiler
     * compiler warnings about unused functions */
6412
    return __Pyx_Print(f, NULL, 0);
6413 6414 6415 6416
}

#else /* Python 3 has a print function */

6417
static int __Pyx_PrintOne(PyObject* stream, PyObject *o) {
6418 6419 6420 6421 6422 6423
    int res;
    PyObject* arg_tuple = PyTuple_New(1);
    if (unlikely(!arg_tuple))
        return -1;
    Py_INCREF(o);
    PyTuple_SET_ITEM(arg_tuple, 0, o);
6424
    res = __Pyx_Print(stream, arg_tuple, 1);
6425 6426 6427 6428
    Py_DECREF(arg_tuple);
    return res;
}

6429
#endif
Robert Bradshaw's avatar
Robert Bradshaw committed
6430 6431
""",
requires=[printing_utility_code])
6432 6433


William Stein's avatar
William Stein committed
6434 6435 6436

#------------------------------------------------------------------------------------

6437 6438 6439 6440 6441 6442 6443 6444 6445
# Exception raising code
#
# Exceptions are raised by __Pyx_Raise() and stored as plain
# type/value/tb in PyThreadState->curexc_*.  When being caught by an
# 'except' statement, curexc_* is moved over to exc_* by
# __Pyx_GetException()

restore_exception_utility_code = UtilityCode(
proto = """
6446 6447
static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
6448 6449
""",
impl = """
6450
static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) {
6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464
    PyObject *tmp_type, *tmp_value, *tmp_tb;
    PyThreadState *tstate = PyThreadState_GET();

    tmp_type = tstate->curexc_type;
    tmp_value = tstate->curexc_value;
    tmp_tb = tstate->curexc_traceback;
    tstate->curexc_type = type;
    tstate->curexc_value = value;
    tstate->curexc_traceback = tb;
    Py_XDECREF(tmp_type);
    Py_XDECREF(tmp_value);
    Py_XDECREF(tmp_tb);
}

6465
static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) {
6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480
    PyThreadState *tstate = PyThreadState_GET();
    *type = tstate->curexc_type;
    *value = tstate->curexc_value;
    *tb = tstate->curexc_traceback;

    tstate->curexc_type = 0;
    tstate->curexc_value = 0;
    tstate->curexc_traceback = 0;
}

""")

# The following function is based on do_raise() from ceval.c. There
# are separate versions for Python2 and Python3 as exception handling
# has changed quite a lot between the two versions.
William Stein's avatar
William Stein committed
6481

6482 6483
raise_utility_code = UtilityCode(
proto = """
Haoyu Bai's avatar
Haoyu Bai committed
6484
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/
6485 6486
""",
impl = """
6487
#if PY_MAJOR_VERSION < 3
Haoyu Bai's avatar
Haoyu Bai committed
6488 6489
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) {
    /* cause is unused */
William Stein's avatar
William Stein committed
6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507
    Py_XINCREF(type);
    Py_XINCREF(value);
    Py_XINCREF(tb);
    /* First, check the traceback argument, replacing None with NULL. */
    if (tb == Py_None) {
        Py_DECREF(tb);
        tb = 0;
    }
    else if (tb != NULL && !PyTraceBack_Check(tb)) {
        PyErr_SetString(PyExc_TypeError,
            "raise: arg 3 must be a traceback or None");
        goto raise_error;
    }
    /* Next, replace a missing value with None */
    if (value == NULL) {
        value = Py_None;
        Py_INCREF(value);
    }
6508 6509 6510 6511 6512 6513
    #if PY_VERSION_HEX < 0x02050000
    if (!PyClass_Check(type))
    #else
    if (!PyType_Check(type))
    #endif
    {
William Stein's avatar
William Stein committed
6514 6515 6516
        /* Raising an instance.  The value should be a dummy. */
        if (value != Py_None) {
            PyErr_SetString(PyExc_TypeError,
6517
                "instance exception may not have a separate value");
William Stein's avatar
William Stein committed
6518 6519
            goto raise_error;
        }
6520 6521 6522
        /* Normalize to raise <class>, <instance> */
        Py_DECREF(value);
        value = type;
6523 6524 6525 6526 6527 6528
        #if PY_VERSION_HEX < 0x02050000
            if (PyInstance_Check(type)) {
                type = (PyObject*) ((PyInstanceObject*)type)->in_class;
                Py_INCREF(type);
            }
            else {
6529
                type = 0;
6530 6531 6532 6533 6534
                PyErr_SetString(PyExc_TypeError,
                    "raise: exception must be an old-style class or instance");
                goto raise_error;
            }
        #else
6535
            type = (PyObject*) Py_TYPE(type);
6536 6537 6538 6539 6540 6541 6542
            Py_INCREF(type);
            if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
                PyErr_SetString(PyExc_TypeError,
                    "raise: exception class must be a subclass of BaseException");
                goto raise_error;
            }
        #endif
William Stein's avatar
William Stein committed
6543
    }
6544

6545
    __Pyx_ErrRestore(type, value, tb);
6546 6547 6548
    return;
raise_error:
    Py_XDECREF(value);
William Stein's avatar
William Stein committed
6549 6550 6551 6552
    Py_XDECREF(type);
    Py_XDECREF(tb);
    return;
}
6553

6554
#else /* Python 3+ */
6555

Haoyu Bai's avatar
Haoyu Bai committed
6556
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) {
6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580
    if (tb == Py_None) {
        tb = 0;
    } else if (tb && !PyTraceBack_Check(tb)) {
        PyErr_SetString(PyExc_TypeError,
            "raise: arg 3 must be a traceback or None");
        goto bad;
    }
    if (value == Py_None)
        value = 0;

    if (PyExceptionInstance_Check(type)) {
        if (value) {
            PyErr_SetString(PyExc_TypeError,
                "instance exception may not have a separate value");
            goto bad;
        }
        value = type;
        type = (PyObject*) Py_TYPE(value);
    } else if (!PyExceptionClass_Check(type)) {
        PyErr_SetString(PyExc_TypeError,
            "raise: exception class must be a subclass of BaseException");
        goto bad;
    }

Haoyu Bai's avatar
Haoyu Bai committed
6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603
    if (cause) {
        PyObject *fixed_cause;
        if (PyExceptionClass_Check(cause)) {
            fixed_cause = PyObject_CallObject(cause, NULL);
            if (fixed_cause == NULL)
                goto bad;
        }
        else if (PyExceptionInstance_Check(cause)) {
            fixed_cause = cause;
            Py_INCREF(fixed_cause);
        }
        else {
            PyErr_SetString(PyExc_TypeError,
                            "exception causes must derive from "
                            "BaseException");
            goto bad;
        }
        if (!value) {
            value = PyObject_CallObject(type, NULL);
        }
        PyException_SetCause(value, fixed_cause);
    }

6604 6605 6606 6607
    PyErr_SetObject(type, value);

    if (tb) {
        PyThreadState *tstate = PyThreadState_GET();
6608 6609 6610 6611 6612
        PyObject* tmp_tb = tstate->curexc_traceback;
        if (tb != tmp_tb) {
            Py_INCREF(tb);
            tstate->curexc_traceback = tb;
            Py_XDECREF(tmp_tb);
6613 6614
        }
    }
6615

6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640
bad:
    return;
}
#endif
""",
requires=[restore_exception_utility_code])

#------------------------------------------------------------------------------------

get_exception_utility_code = UtilityCode(
proto = """
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
""",
impl = """
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) {
    PyObject *local_type, *local_value, *local_tb;
    PyObject *tmp_type, *tmp_value, *tmp_tb;
    PyThreadState *tstate = PyThreadState_GET();
    local_type = tstate->curexc_type;
    local_value = tstate->curexc_value;
    local_tb = tstate->curexc_traceback;
    tstate->curexc_type = 0;
    tstate->curexc_value = 0;
    tstate->curexc_traceback = 0;
    PyErr_NormalizeException(&local_type, &local_value, &local_tb);
6641 6642 6643 6644
    if (unlikely(tstate->curexc_type))
        goto bad;
    #if PY_MAJOR_VERSION >= 3
    if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0))
6645
        goto bad;
6646
    #endif
6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681
    *type = local_type;
    *value = local_value;
    *tb = local_tb;
    Py_INCREF(local_type);
    Py_INCREF(local_value);
    Py_INCREF(local_tb);
    tmp_type = tstate->exc_type;
    tmp_value = tstate->exc_value;
    tmp_tb = tstate->exc_traceback;
    tstate->exc_type = local_type;
    tstate->exc_value = local_value;
    tstate->exc_traceback = local_tb;
    /* Make sure tstate is in a consistent state when we XDECREF
       these objects (XDECREF may run arbitrary code). */
    Py_XDECREF(tmp_type);
    Py_XDECREF(tmp_value);
    Py_XDECREF(tmp_tb);
    return 0;
bad:
    *type = 0;
    *value = 0;
    *tb = 0;
    Py_XDECREF(local_type);
    Py_XDECREF(local_value);
    Py_XDECREF(local_tb);
    return -1;
}

""")

#------------------------------------------------------------------------------------

get_exception_tuple_utility_code = UtilityCode(proto="""
static PyObject *__Pyx_GetExceptionTuple(void); /*proto*/
""",
6682 6683 6684
# I doubt that calling __Pyx_GetException() here is correct as it moves
# the exception from tstate->curexc_* to tstate->exc_*, which prevents
# exception handlers later on from receiving it.
6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708
impl = """
static PyObject *__Pyx_GetExceptionTuple(void) {
    PyObject *type = NULL, *value = NULL, *tb = NULL;
    if (__Pyx_GetException(&type, &value, &tb) == 0) {
        PyObject* exc_info = PyTuple_New(3);
        if (exc_info) {
            Py_INCREF(type);
            Py_INCREF(value);
            Py_INCREF(tb);
            PyTuple_SET_ITEM(exc_info, 0, type);
            PyTuple_SET_ITEM(exc_info, 1, value);
            PyTuple_SET_ITEM(exc_info, 2, tb);
            return exc_info;
        }
    }
    return NULL;
}
""",
requires=[get_exception_utility_code])

#------------------------------------------------------------------------------------

reset_exception_utility_code = UtilityCode(
proto = """
6709
static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
6710 6711 6712
static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
""",
impl = """
6713
static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) {
6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735
    PyThreadState *tstate = PyThreadState_GET();
    *type = tstate->exc_type;
    *value = tstate->exc_value;
    *tb = tstate->exc_traceback;
    Py_XINCREF(*type);
    Py_XINCREF(*value);
    Py_XINCREF(*tb);
}

static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) {
    PyObject *tmp_type, *tmp_value, *tmp_tb;
    PyThreadState *tstate = PyThreadState_GET();
    tmp_type = tstate->exc_type;
    tmp_value = tstate->exc_value;
    tmp_tb = tstate->exc_traceback;
    tstate->exc_type = type;
    tstate->exc_value = value;
    tstate->exc_traceback = tb;
    Py_XDECREF(tmp_type);
    Py_XDECREF(tmp_value);
    Py_XDECREF(tmp_tb);
}
6736
""")
William Stein's avatar
William Stein committed
6737 6738 6739

#------------------------------------------------------------------------------------

6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764
swap_exception_utility_code = UtilityCode(
proto = """
static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
""",
impl = """
static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) {
    PyObject *tmp_type, *tmp_value, *tmp_tb;
    PyThreadState *tstate = PyThreadState_GET();

    tmp_type = tstate->exc_type;
    tmp_value = tstate->exc_value;
    tmp_tb = tstate->exc_traceback;

    tstate->exc_type = *type;
    tstate->exc_value = *value;
    tstate->exc_traceback = *tb;

    *type = tmp_type;
    *value = tmp_value;
    *tb = tmp_tb;
}
""")

#------------------------------------------------------------------------------------

6765 6766
arg_type_test_utility_code = UtilityCode(
proto = """
6767 6768
static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
    const char *name, int exact); /*proto*/
6769 6770
""",
impl = """
6771 6772 6773
static int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
    const char *name, int exact)
{
William Stein's avatar
William Stein committed
6774 6775 6776 6777
    if (!type) {
        PyErr_Format(PyExc_SystemError, "Missing type object");
        return 0;
    }
Robert Bradshaw's avatar
Robert Bradshaw committed
6778 6779
    if (none_allowed && obj == Py_None) return 1;
    else if (exact) {
6780
        if (Py_TYPE(obj) == type) return 1;
Robert Bradshaw's avatar
Robert Bradshaw committed
6781 6782
    }
    else {
Robert Bradshaw's avatar
Robert Bradshaw committed
6783
        if (PyObject_TypeCheck(obj, type)) return 1;
Robert Bradshaw's avatar
Robert Bradshaw committed
6784
    }
William Stein's avatar
William Stein committed
6785 6786
    PyErr_Format(PyExc_TypeError,
        "Argument '%s' has incorrect type (expected %s, got %s)",
6787
        name, type->tp_name, Py_TYPE(obj)->tp_name);
William Stein's avatar
William Stein committed
6788 6789
    return 0;
}
6790
""")
William Stein's avatar
William Stein committed
6791 6792 6793

#------------------------------------------------------------------------------------
#
6794 6795 6796
#  __Pyx_RaiseArgtupleInvalid raises the correct exception when too
#  many or too few positional arguments were found.  This handles
#  Py_ssize_t formatting correctly.
6797

6798 6799
raise_argtuple_invalid_utility_code = UtilityCode(
proto = """
6800
static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
6801
    Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/
6802 6803
""",
impl = """
6804
static void __Pyx_RaiseArgtupleInvalid(
6805
    const char* func_name,
6806
    int exact,
6807 6808
    Py_ssize_t num_min,
    Py_ssize_t num_max,
6809
    Py_ssize_t num_found)
William Stein's avatar
William Stein committed
6810
{
6811
    Py_ssize_t num_expected;
Stefan Behnel's avatar
Stefan Behnel committed
6812
    const char *number, *more_or_less;
6813 6814 6815 6816

    if (num_found < num_min) {
        num_expected = num_min;
        more_or_less = "at least";
6817
    } else {
6818
        num_expected = num_max;
6819
        more_or_less = "at most";
6820
    }
6821 6822
    if (exact) {
        more_or_less = "exactly";
6823
    }
6824
    number = (num_expected == 1) ? "" : "s";
Stefan Behnel's avatar
Stefan Behnel committed
6825 6826 6827 6828 6829 6830 6831
    PyErr_Format(PyExc_TypeError,
        #if PY_VERSION_HEX < 0x02050000
            "%s() takes %s %d positional argument%s (%d given)",
        #else
            "%s() takes %s %zd positional argument%s (%zd given)",
        #endif
        func_name, more_or_less, num_expected, number, num_found);
6832
}
6833
""")
6834

6835 6836
raise_keyword_required_utility_code = UtilityCode(
proto = """
6837
static CYTHON_INLINE void __Pyx_RaiseKeywordRequired(const char* func_name, PyObject* kw_name); /*proto*/
6838 6839
""",
impl = """
6840
static CYTHON_INLINE void __Pyx_RaiseKeywordRequired(
6841
    const char* func_name,
6842
    PyObject* kw_name)
6843 6844
{
    PyErr_Format(PyExc_TypeError,
6845 6846 6847 6848 6849 6850
        #if PY_MAJOR_VERSION >= 3
        "%s() needs keyword-only argument %U", func_name, kw_name);
        #else
        "%s() needs keyword-only argument %s", func_name,
        PyString_AS_STRING(kw_name));
        #endif
6851
}
6852
""")
6853

6854 6855
raise_double_keywords_utility_code = UtilityCode(
proto = """
6856
static void __Pyx_RaiseDoubleKeywordsError(
6857
    const char* func_name, PyObject* kw_name); /*proto*/
6858 6859
""",
impl = """
6860
static void __Pyx_RaiseDoubleKeywordsError(
6861
    const char* func_name,
6862
    PyObject* kw_name)
6863
{
6864
    PyErr_Format(PyExc_TypeError,
6865 6866 6867 6868 6869 6870
        #if PY_MAJOR_VERSION >= 3
        "%s() got multiple values for keyword argument '%U'", func_name, kw_name);
        #else
        "%s() got multiple values for keyword argument '%s'", func_name,
        PyString_AS_STRING(kw_name));
        #endif
6871
}
6872
""")
6873

6874 6875
#------------------------------------------------------------------------------------
#
6876 6877 6878
#  __Pyx_CheckKeywordStrings raises an error if non-string keywords
#  were passed to a function, or if any keywords were passed to a
#  function that does not accept them.
6879

6880 6881
keyword_string_check_utility_code = UtilityCode(
proto = """
6882
static CYTHON_INLINE int __Pyx_CheckKeywordStrings(PyObject *kwdict,
6883
    const char* function_name, int kw_allowed); /*proto*/
6884 6885
""",
impl = """
6886
static CYTHON_INLINE int __Pyx_CheckKeywordStrings(
6887 6888 6889 6890
    PyObject *kwdict,
    const char* function_name,
    int kw_allowed)
{
6891 6892
    PyObject* key = 0;
    Py_ssize_t pos = 0;
6893
    while (PyDict_Next(kwdict, &pos, &key, 0)) {
6894
        #if PY_MAJOR_VERSION < 3
6895
        if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key)))
6896
        #else
6897
        if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key)))
6898
        #endif
6899
            goto invalid_keyword_type;
6900
    }
6901 6902
    if ((!kw_allowed) && unlikely(key))
        goto invalid_keyword;
6903
    return 1;
6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917
invalid_keyword_type:
    PyErr_Format(PyExc_TypeError,
        "%s() keywords must be strings", function_name);
    return 0;
invalid_keyword:
    PyErr_Format(PyExc_TypeError,
    #if PY_MAJOR_VERSION < 3
        "%s() got an unexpected keyword argument '%s'",
        function_name, PyString_AsString(key));
    #else
        "%s() got an unexpected keyword argument '%U'",
        function_name, key);
    #endif
    return 0;
6918
}
6919
""")
6920

6921 6922
#------------------------------------------------------------------------------------
#
6923 6924 6925
#  __Pyx_ParseOptionalKeywords copies the optional/unknown keyword
#  arguments from the kwds dict into kwds2.  If kwds2 is NULL, unknown
#  keywords will raise an invalid keyword error.
6926
#
Stefan Behnel's avatar
Stefan Behnel committed
6927 6928
#  Three kinds of errors are checked: 1) non-string keywords, 2)
#  unexpected keywords and 3) overlap with positional arguments.
6929
#
Stefan Behnel's avatar
Stefan Behnel committed
6930 6931 6932 6933 6934
#  If num_posargs is greater 0, it denotes the number of positional
#  arguments that were passed and that must therefore not appear
#  amongst the keywords as well.
#
#  This method does not check for required keyword arguments.
6935 6936
#

6937
parse_keywords_utility_code = UtilityCode(
6938
proto = """
6939
static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \
6940 6941
    PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \
    const char* function_name); /*proto*/
6942 6943
""",
impl = """
6944
static int __Pyx_ParseOptionalKeywords(
6945
    PyObject *kwds,
Stefan Behnel's avatar
Stefan Behnel committed
6946 6947
    PyObject **argnames[],
    PyObject *kwds2,
6948
    PyObject *values[],
Stefan Behnel's avatar
Stefan Behnel committed
6949
    Py_ssize_t num_pos_args,
6950
    const char* function_name)
6951
{
6952
    PyObject *key = 0, *value = 0;
6953
    Py_ssize_t pos = 0;
6954
    PyObject*** name;
6955
    PyObject*** first_kw_arg = argnames + num_pos_args;
6956

Stefan Behnel's avatar
Stefan Behnel committed
6957
    while (PyDict_Next(kwds, &pos, &key, &value)) {
6958 6959
        name = first_kw_arg;
        while (*name && (**name != key)) name++;
6960
        if (*name) {
6961
            values[name-argnames] = value;
Stefan Behnel's avatar
Stefan Behnel committed
6962
        } else {
6963 6964 6965 6966 6967 6968
            #if PY_MAJOR_VERSION < 3
            if (unlikely(!PyString_CheckExact(key)) && unlikely(!PyString_Check(key))) {
            #else
            if (unlikely(!PyUnicode_CheckExact(key)) && unlikely(!PyUnicode_Check(key))) {
            #endif
                goto invalid_keyword_type;
6969 6970
            } else {
                for (name = first_kw_arg; *name; name++) {
6971
                    #if PY_MAJOR_VERSION >= 3
Stefan Behnel's avatar
Stefan Behnel committed
6972
                    if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) &&
6973
                        PyUnicode_Compare(**name, key) == 0) break;
6974
                    #else
6975
                    if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) &&
6976
                        _PyString_Eq(**name, key)) break;
6977 6978
                    #endif
                }
6979
                if (*name) {
6980 6981 6982 6983 6984 6985 6986 6987 6988 6989
                    values[name-argnames] = value;
                } else {
                    /* unexpected keyword found */
                    for (name=argnames; name != first_kw_arg; name++) {
                        if (**name == key) goto arg_passed_twice;
                        #if PY_MAJOR_VERSION >= 3
                        if (PyUnicode_GET_SIZE(**name) == PyUnicode_GET_SIZE(key) &&
                            PyUnicode_Compare(**name, key) == 0) goto arg_passed_twice;
                        #else
                        if (PyString_GET_SIZE(**name) == PyString_GET_SIZE(key) &&
6990
                            _PyString_Eq(**name, key)) goto arg_passed_twice;
6991 6992
                        #endif
                    }
Stefan Behnel's avatar
Stefan Behnel committed
6993 6994 6995
                    if (kwds2) {
                        if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
                    } else {
6996
                        goto invalid_keyword;
Stefan Behnel's avatar
Stefan Behnel committed
6997 6998
                    }
                }
6999
            }
7000
        }
7001
    }
7002
    return 0;
7003
arg_passed_twice:
Stefan Behnel's avatar
Stefan Behnel committed
7004 7005
    __Pyx_RaiseDoubleKeywordsError(function_name, **name);
    goto bad;
7006 7007 7008 7009 7010
invalid_keyword_type:
    PyErr_Format(PyExc_TypeError,
        "%s() keywords must be strings", function_name);
    goto bad;
invalid_keyword:
7011
    PyErr_Format(PyExc_TypeError,
7012
    #if PY_MAJOR_VERSION < 3
7013 7014
        "%s() got an unexpected keyword argument '%s'",
        function_name, PyString_AsString(key));
7015
    #else
7016 7017
        "%s() got an unexpected keyword argument '%U'",
        function_name, key);
7018
    #endif
William Stein's avatar
William Stein committed
7019 7020 7021
bad:
    return -1;
}
7022 7023
""",
requires=[raise_double_keywords_utility_code])
William Stein's avatar
William Stein committed
7024 7025 7026

#------------------------------------------------------------------------------------

7027 7028
traceback_utility_code = UtilityCode(
proto = """
7029
static void __Pyx_AddTraceback(const char *funcname); /*proto*/
7030 7031
""",
impl = """
William Stein's avatar
William Stein committed
7032 7033 7034 7035
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"

7036
static void __Pyx_AddTraceback(const char *funcname) {
William Stein's avatar
William Stein committed
7037 7038 7039 7040 7041
    PyObject *py_srcfile = 0;
    PyObject *py_funcname = 0;
    PyObject *py_globals = 0;
    PyCodeObject *py_code = 0;
    PyFrameObject *py_frame = 0;
7042 7043

    #if PY_MAJOR_VERSION < 3
William Stein's avatar
William Stein committed
7044
    py_srcfile = PyString_FromString(%(FILENAME)s);
7045 7046 7047
    #else
    py_srcfile = PyUnicode_FromString(%(FILENAME)s);
    #endif
William Stein's avatar
William Stein committed
7048
    if (!py_srcfile) goto bad;
Robert Bradshaw's avatar
Robert Bradshaw committed
7049
    if (%(CLINENO)s) {
7050
        #if PY_MAJOR_VERSION < 3
7051
        py_funcname = PyString_FromFormat( "%%s (%%s:%%d)", funcname, %(CFILENAME)s, %(CLINENO)s);
7052
        #else
7053
        py_funcname = PyUnicode_FromFormat( "%%s (%%s:%%d)", funcname, %(CFILENAME)s, %(CLINENO)s);
7054
        #endif
Robert Bradshaw's avatar
Robert Bradshaw committed
7055 7056
    }
    else {
7057
        #if PY_MAJOR_VERSION < 3
Robert Bradshaw's avatar
Robert Bradshaw committed
7058
        py_funcname = PyString_FromString(funcname);
7059 7060 7061
        #else
        py_funcname = PyUnicode_FromString(funcname);
        #endif
Robert Bradshaw's avatar
Robert Bradshaw committed
7062
    }
William Stein's avatar
William Stein committed
7063 7064 7065 7066 7067
    if (!py_funcname) goto bad;
    py_globals = PyModule_GetDict(%(GLOBALS)s);
    if (!py_globals) goto bad;
    py_code = PyCode_New(
        0,            /*int argcount,*/
7068 7069 7070
        #if PY_MAJOR_VERSION >= 3
        0,            /*int kwonlyargcount,*/
        #endif
William Stein's avatar
William Stein committed
7071 7072 7073
        0,            /*int nlocals,*/
        0,            /*int stacksize,*/
        0,            /*int flags,*/
Robert Bradshaw's avatar
Robert Bradshaw committed
7074
        %(EMPTY_BYTES)s, /*PyObject *code,*/
Stefan Behnel's avatar
Stefan Behnel committed
7075 7076 7077 7078 7079
        %(EMPTY_TUPLE)s,  /*PyObject *consts,*/
        %(EMPTY_TUPLE)s,  /*PyObject *names,*/
        %(EMPTY_TUPLE)s,  /*PyObject *varnames,*/
        %(EMPTY_TUPLE)s,  /*PyObject *freevars,*/
        %(EMPTY_TUPLE)s,  /*PyObject *cellvars,*/
William Stein's avatar
William Stein committed
7080 7081 7082
        py_srcfile,   /*PyObject *filename,*/
        py_funcname,  /*PyObject *name,*/
        %(LINENO)s,   /*int firstlineno,*/
Robert Bradshaw's avatar
Robert Bradshaw committed
7083
        %(EMPTY_BYTES)s  /*PyObject *lnotab*/
William Stein's avatar
William Stein committed
7084 7085 7086
    );
    if (!py_code) goto bad;
    py_frame = PyFrame_New(
7087
        PyThreadState_GET(), /*PyThreadState *tstate,*/
William Stein's avatar
William Stein committed
7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103
        py_code,             /*PyCodeObject *code,*/
        py_globals,          /*PyObject *globals,*/
        0                    /*PyObject *locals*/
    );
    if (!py_frame) goto bad;
    py_frame->f_lineno = %(LINENO)s;
    PyTraceBack_Here(py_frame);
bad:
    Py_XDECREF(py_srcfile);
    Py_XDECREF(py_funcname);
    Py_XDECREF(py_code);
    Py_XDECREF(py_frame);
}
""" % {
    'FILENAME': Naming.filename_cname,
    'LINENO':  Naming.lineno_cname,
Robert Bradshaw's avatar
Robert Bradshaw committed
7104 7105
    'CFILENAME': Naming.cfilenm_cname,
    'CLINENO':  Naming.clineno_cname,
Stefan Behnel's avatar
Stefan Behnel committed
7106 7107
    'GLOBALS': Naming.module_cname,
    'EMPTY_TUPLE' : Naming.empty_tuple,
Robert Bradshaw's avatar
Robert Bradshaw committed
7108
    'EMPTY_BYTES' : Naming.empty_bytes,
7109
})
William Stein's avatar
William Stein committed
7110

7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136
#------------------------------------------------------------------------------------

unraisable_exception_utility_code = UtilityCode(
proto = """
static void __Pyx_WriteUnraisable(const char *name); /*proto*/
""",
impl = """
static void __Pyx_WriteUnraisable(const char *name) {
    PyObject *old_exc, *old_val, *old_tb;
    PyObject *ctx;
    __Pyx_ErrFetch(&old_exc, &old_val, &old_tb);
    #if PY_MAJOR_VERSION < 3
    ctx = PyString_FromString(name);
    #else
    ctx = PyUnicode_FromString(name);
    #endif
    __Pyx_ErrRestore(old_exc, old_val, old_tb);
    if (!ctx) {
        PyErr_WriteUnraisable(Py_None);
    } else {
        PyErr_WriteUnraisable(ctx);
        Py_DECREF(ctx);
    }
}
""",
requires=[restore_exception_utility_code])
7137

William Stein's avatar
William Stein committed
7138 7139
#------------------------------------------------------------------------------------

7140 7141
set_vtable_utility_code = UtilityCode(
proto = """
7142
static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/
7143 7144
""",
impl = """
William Stein's avatar
William Stein committed
7145
static int __Pyx_SetVtable(PyObject *dict, void *vtable) {
7146
#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0)
7147
    PyObject *ob = PyCapsule_New(vtable, 0, 0);
7148 7149
#else
    PyObject *ob = PyCObject_FromVoidPtr(vtable, 0);
7150 7151
#endif
    if (!ob)
William Stein's avatar
William Stein committed
7152
        goto bad;
7153
    if (PyDict_SetItemString(dict, "__pyx_vtable__", ob) < 0)
William Stein's avatar
William Stein committed
7154
        goto bad;
7155 7156
    Py_DECREF(ob);
    return 0;
William Stein's avatar
William Stein committed
7157
bad:
7158 7159
    Py_XDECREF(ob);
    return -1;
William Stein's avatar
William Stein committed
7160
}
7161
""")
William Stein's avatar
William Stein committed
7162 7163 7164

#------------------------------------------------------------------------------------

7165 7166
get_vtable_utility_code = UtilityCode(
proto = """
7167
static void* __Pyx_GetVtable(PyObject *dict); /*proto*/
7168 7169
""",
impl = r"""
7170 7171
static void* __Pyx_GetVtable(PyObject *dict) {
    void* ptr;
7172 7173
    PyObject *ob = PyMapping_GetItemString(dict, (char *)"__pyx_vtable__");
    if (!ob)
William Stein's avatar
William Stein committed
7174
        goto bad;
7175
#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0)
7176
    ptr = PyCapsule_GetPointer(ob, 0);
7177
#else
7178
    ptr = PyCObject_AsVoidPtr(ob);
7179
#endif
7180 7181
    if (!ptr && !PyErr_Occurred())
        PyErr_SetString(PyExc_RuntimeError, "invalid vtable found for imported type");
7182
    Py_DECREF(ob);
7183
    return ptr;
William Stein's avatar
William Stein committed
7184
bad:
7185
    Py_XDECREF(ob);
7186
    return NULL;
William Stein's avatar
William Stein committed
7187
}
7188
""")
William Stein's avatar
William Stein committed
7189 7190 7191

#------------------------------------------------------------------------------------

7192 7193
init_string_tab_utility_code = UtilityCode(
proto = """
7194
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/
7195 7196
""",
impl = """
William Stein's avatar
William Stein committed
7197 7198
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
    while (t->p) {
7199
        #if PY_MAJOR_VERSION < 3
7200
        if (t->is_unicode) {
7201
            *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
7202 7203
        } else if (t->intern) {
            *t->p = PyString_InternFromString(t->s);
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
7204 7205
        } else {
            *t->p = PyString_FromStringAndSize(t->s, t->n - 1);
Stefan Behnel's avatar
Stefan Behnel committed
7206
        }
7207
        #else  /* Python 3+ has unicode identifiers */
7208 7209 7210 7211 7212 7213 7214 7215
        if (t->is_unicode | t->is_str) {
            if (t->intern) {
                *t->p = PyUnicode_InternFromString(t->s);
            } else if (t->encoding) {
                *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
            } else {
                *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
            }
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
7216 7217
        } else {
            *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
Stefan Behnel's avatar
Stefan Behnel committed
7218
        }
7219
        #endif
William Stein's avatar
William Stein committed
7220 7221 7222 7223 7224 7225
        if (!*t->p)
            return -1;
        ++t;
    }
    return 0;
}
7226
""")
William Stein's avatar
William Stein committed
7227 7228

#------------------------------------------------------------------------------------
7229

Stefan Behnel's avatar
Stefan Behnel committed
7230
force_init_threads_utility_code = UtilityCode(
7231 7232
proto="""
#ifndef __PYX_FORCE_INIT_THREADS
7233 7234 7235 7236 7237
  #if PY_VERSION_HEX < 0x02040200
    #define __PYX_FORCE_INIT_THREADS 1
  #else
    #define __PYX_FORCE_INIT_THREADS 0
  #endif
7238 7239 7240 7241
#endif
""")

#------------------------------------------------------------------------------------
Robert Bradshaw's avatar
Robert Bradshaw committed
7242

7243 7244
# Note that cPython ignores PyTrace_EXCEPTION,
# but maybe some other profilers don't.
Robert Bradshaw's avatar
Robert Bradshaw committed
7245

7246 7247
profile_utility_code = UtilityCode(proto="""
#ifndef CYTHON_PROFILE
7248
  #define CYTHON_PROFILE 1
7249 7250
#endif

7251
#ifndef CYTHON_PROFILE_REUSE_FRAME
7252
  #define CYTHON_PROFILE_REUSE_FRAME 0
7253
#endif
Robert Bradshaw's avatar
Robert Bradshaw committed
7254

7255
#if CYTHON_PROFILE
Robert Bradshaw's avatar
Robert Bradshaw committed
7256

7257 7258 7259
  #include "compile.h"
  #include "frameobject.h"
  #include "traceback.h"
7260

7261 7262 7263 7264 7265 7266 7267
  #if CYTHON_PROFILE_REUSE_FRAME
    #define CYTHON_FRAME_MODIFIER static
    #define CYTHON_FRAME_DEL
  #else
    #define CYTHON_FRAME_MODIFIER
    #define CYTHON_FRAME_DEL Py_DECREF(%(FRAME)s)
  #endif
Robert Bradshaw's avatar
Robert Bradshaw committed
7268

7269 7270 7271
  #define __Pyx_TraceDeclarations                                  \\
  static PyCodeObject *%(FRAME_CODE)s = NULL;                      \\
  CYTHON_FRAME_MODIFIER PyFrameObject *%(FRAME)s = NULL;           \\
7272
  int __Pyx_use_tracing = 0;
7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297

  #define __Pyx_TraceCall(funcname, srcfile, firstlineno)                            \\
  if (unlikely(PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc)) {      \\
      __Pyx_use_tracing = __Pyx_TraceSetupAndCall(&%(FRAME_CODE)s, &%(FRAME)s, funcname, srcfile, firstlineno);  \\
  }

  #define __Pyx_TraceException()                                                           \\
  if (unlikely(__Pyx_use_tracing( && PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc) {  \\
      PyObject *exc_info = __Pyx_GetExceptionTuple();                                      \\
      if (exc_info) {                                                                      \\
          PyThreadState_GET()->c_profilefunc(                                              \\
              PyThreadState_GET()->c_profileobj, %(FRAME)s, PyTrace_EXCEPTION, exc_info);  \\
          Py_DECREF(exc_info);                                                             \\
      }                                                                                    \\
  }

  #define __Pyx_TraceReturn(result)                                                  \\
  if (unlikely(__Pyx_use_tracing) && PyThreadState_GET()->use_tracing && PyThreadState_GET()->c_profilefunc) {  \\
      PyThreadState_GET()->c_profilefunc(                                            \\
          PyThreadState_GET()->c_profileobj, %(FRAME)s, PyTrace_RETURN, (PyObject*)result);     \\
      CYTHON_FRAME_DEL;                                                               \\
  }

  static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno); /*proto*/
  static int __Pyx_TraceSetupAndCall(PyCodeObject** code, PyFrameObject** frame, const char *funcname, const char *srcfile, int firstlineno); /*proto*/
Robert Bradshaw's avatar
Robert Bradshaw committed
7298

7299
#else
Robert Bradshaw's avatar
Robert Bradshaw committed
7300

7301
  #define __Pyx_TraceDeclarations
7302 7303 7304
  #define __Pyx_TraceCall(funcname, srcfile, firstlineno)
  #define __Pyx_TraceException()
  #define __Pyx_TraceReturn(result)
Robert Bradshaw's avatar
Robert Bradshaw committed
7305

7306
#endif /* CYTHON_PROFILE */
7307
"""
Robert Bradshaw's avatar
Robert Bradshaw committed
7308 7309 7310 7311 7312 7313
% {
    "FRAME": Naming.frame_cname,
    "FRAME_CODE": Naming.frame_code_cname,
},
impl = """

7314
#if CYTHON_PROFILE
Robert Bradshaw's avatar
Robert Bradshaw committed
7315 7316 7317 7318 7319 7320

static int __Pyx_TraceSetupAndCall(PyCodeObject** code,
                                   PyFrameObject** frame,
                                   const char *funcname,
                                   const char *srcfile,
                                   int firstlineno) {
7321
    if (*frame == NULL || !CYTHON_PROFILE_REUSE_FRAME) {
Robert Bradshaw's avatar
Robert Bradshaw committed
7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373
        if (*code == NULL) {
            *code = __Pyx_createFrameCodeObject(funcname, srcfile, firstlineno);
            if (*code == NULL) return 0;
        }
        *frame = PyFrame_New(
            PyThreadState_GET(),            /*PyThreadState *tstate*/
            *code,                          /*PyCodeObject *code*/
            PyModule_GetDict(%(MODULE)s),      /*PyObject *globals*/
            0                               /*PyObject *locals*/
        );
        if (*frame == NULL) return 0;
    }
    else {
        (*frame)->f_tstate = PyThreadState_GET();
    }
    return PyThreadState_GET()->c_profilefunc(PyThreadState_GET()->c_profileobj, *frame, PyTrace_CALL, NULL) == 0;
}

static PyCodeObject *__Pyx_createFrameCodeObject(const char *funcname, const char *srcfile, int firstlineno) {
    PyObject *py_srcfile = 0;
    PyObject *py_funcname = 0;
    PyCodeObject *py_code = 0;

    #if PY_MAJOR_VERSION < 3
    py_funcname = PyString_FromString(funcname);
    py_srcfile = PyString_FromString(srcfile);
    #else
    py_funcname = PyUnicode_FromString(funcname);
    py_srcfile = PyUnicode_FromString(srcfile);
    #endif
    if (!py_funcname | !py_srcfile) goto bad;

    py_code = PyCode_New(
        0,                /*int argcount,*/
        #if PY_MAJOR_VERSION >= 3
        0,                /*int kwonlyargcount,*/
        #endif
        0,                /*int nlocals,*/
        0,                /*int stacksize,*/
        0,                /*int flags,*/
        %(EMPTY_BYTES)s,  /*PyObject *code,*/
        %(EMPTY_TUPLE)s,  /*PyObject *consts,*/
        %(EMPTY_TUPLE)s,  /*PyObject *names,*/
        %(EMPTY_TUPLE)s,  /*PyObject *varnames,*/
        %(EMPTY_TUPLE)s,  /*PyObject *freevars,*/
        %(EMPTY_TUPLE)s,  /*PyObject *cellvars,*/
        py_srcfile,       /*PyObject *filename,*/
        py_funcname,      /*PyObject *name,*/
        firstlineno,      /*int firstlineno,*/
        %(EMPTY_BYTES)s   /*PyObject *lnotab*/
    );

7374
bad:
Robert Bradshaw's avatar
Robert Bradshaw committed
7375 7376
    Py_XDECREF(py_srcfile);
    Py_XDECREF(py_funcname);
7377

Robert Bradshaw's avatar
Robert Bradshaw committed
7378 7379 7380
    return py_code;
}

7381
#endif /* CYTHON_PROFILE */
Robert Bradshaw's avatar
Robert Bradshaw committed
7382 7383 7384 7385 7386
""" % {
    'EMPTY_TUPLE' : Naming.empty_tuple,
    'EMPTY_BYTES' : Naming.empty_bytes,
    "MODULE": Naming.module_cname,
})