ExprNodes.py 374 KB
Newer Older
William Stein's avatar
William Stein committed
1
#
2
#   Parse tree nodes for expressions
William Stein's avatar
William Stein committed
3 4
#

5 6
import cython
cython.declare(error=object, warning=object, warn_once=object, InternalError=object,
7 8
               CompileError=object, UtilityCode=object, TempitaUtilityCode=object,
               StringEncoding=object, operator=object,
9
               Naming=object, Nodes=object, PyrexTypes=object, py_object_type=object,
Stefan Behnel's avatar
Stefan Behnel committed
10
               list_type=object, tuple_type=object, set_type=object, dict_type=object,
11 12 13 14
               unicode_type=object, str_type=object, bytes_type=object, type_type=object,
               Builtin=object, Symtab=object, Utils=object, find_coercion_error=object,
               debug_disposal_code=object, debug_temp_alloc=object, debug_coercion=object)

15
import sys
16
import copy
17
import operator
William Stein's avatar
William Stein committed
18

19
from Errors import error, warning, warn_once, InternalError, CompileError
20
from Errors import hold_errors, release_errors, held_errors, report_error
21
from Code import UtilityCode, TempitaUtilityCode
22
import StringEncoding
William Stein's avatar
William Stein committed
23
import Naming
Robert Bradshaw's avatar
Robert Bradshaw committed
24
import Nodes
William Stein's avatar
William Stein committed
25 26
from Nodes import Node
import PyrexTypes
27
from PyrexTypes import py_object_type, c_long_type, typecast, error_type, \
28
     unspecified_type, cython_memoryview_ptr_type
29
import TypeSlots
30 31
from Builtin import list_type, tuple_type, set_type, dict_type, \
     unicode_type, str_type, bytes_type, type_type
32
import Builtin
William Stein's avatar
William Stein committed
33 34
import Symtab
import Options
35
from Cython import Utils
36
from Annotate import AnnotationItem
William Stein's avatar
William Stein committed
37

William Stein's avatar
William Stein committed
38
from Cython.Debugging import print_call_chain
William Stein's avatar
William Stein committed
39 40 41
from DebugFlags import debug_disposal_code, debug_temp_alloc, \
    debug_coercion

42 43 44 45 46
try:
    from __builtin__ import basestring
except ImportError:
    basestring = str # Python 3

Stefan Behnel's avatar
Stefan Behnel committed
47
class NotConstant(object):
48 49 50 51 52 53 54 55
    _obj = None

    def __new__(cls):
        if NotConstant._obj is None:
            NotConstant._obj = super(NotConstant, cls).__new__(cls)

        return NotConstant._obj

Stefan Behnel's avatar
Stefan Behnel committed
56 57 58
    def __repr__(self):
        return "<NOT CONSTANT>"

59
not_a_constant = NotConstant()
60
constant_value_not_set = object()
61

62 63 64 65 66 67 68 69 70 71
# error messages when coercing from key[0] to key[1]
find_coercion_error = {
    # string related errors
    (Builtin.unicode_type, Builtin.bytes_type) : "Cannot convert Unicode string to 'bytes' implicitly, encoding required.",
    (Builtin.unicode_type, Builtin.str_type)   : "Cannot convert Unicode string to 'str' implicitly. This is not portable and requires explicit encoding.",
    (Builtin.unicode_type, PyrexTypes.c_char_ptr_type) : "Unicode objects do not support coercion to C types.",
    (Builtin.bytes_type, Builtin.unicode_type) : "Cannot convert 'bytes' object to unicode implicitly, decoding required",
    (Builtin.bytes_type, Builtin.str_type) : "Cannot convert 'bytes' object to str implicitly. This is not portable to Py3.",
    (Builtin.str_type, Builtin.unicode_type) : "str objects do not support coercion to unicode, use a unicode string literal instead (u'')",
    (Builtin.str_type, Builtin.bytes_type) : "Cannot convert 'str' to 'bytes' implicitly. This is not portable.",
72
    (Builtin.str_type, PyrexTypes.c_char_ptr_type) : "'str' objects do not support coercion to C types (use 'bytes'?).",
73 74 75 76 77
    (PyrexTypes.c_char_ptr_type, Builtin.unicode_type) : "Cannot convert 'char*' to unicode implicitly, decoding required",
    (PyrexTypes.c_uchar_ptr_type, Builtin.unicode_type) : "Cannot convert 'char*' to unicode implicitly, decoding required",
    }.get


William Stein's avatar
William Stein committed
78 79 80 81 82 83
class ExprNode(Node):
    #  subexprs     [string]     Class var holding names of subexpr node attrs
    #  type         PyrexType    Type of the result
    #  result_code  string       Code fragment
    #  result_ctype string       C type of result_code if different from type
    #  is_temp      boolean      Result is in a temporary variable
84
    #  is_sequence_constructor
William Stein's avatar
William Stein committed
85
    #               boolean      Is a list or tuple constructor expression
86
    #  is_starred   boolean      Is a starred expression (e.g. '*a')
William Stein's avatar
William Stein committed
87 88 89
    #  saved_subexpr_nodes
    #               [ExprNode or [ExprNode or None] or None]
    #                            Cached result of subexpr_nodes()
90
    #  use_managed_ref boolean   use ref-counted temps/assignments/etc.
91 92 93
    #  result_is_used  boolean   indicates that the result will be dropped and the
    #                            result_code/temp_result can safely be set to None

William Stein's avatar
William Stein committed
94
    result_ctype = None
95
    type = None
96 97
    temp_code = None
    old_temp = None # error checker for multiple frees etc.
98
    use_managed_ref = True # can be set by optimisation transforms
99
    result_is_used = True
William Stein's avatar
William Stein committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

    #  The Analyse Expressions phase for expressions is split
    #  into two sub-phases:
    #
    #    Analyse Types
    #      Determines the result type of the expression based
    #      on the types of its sub-expressions, and inserts
    #      coercion nodes into the expression tree where needed.
    #      Marks nodes which will need to have temporary variables
    #      allocated.
    #
    #    Allocate Temps
    #      Allocates temporary variables where needed, and fills
    #      in the result_code field of each node.
    #
    #  ExprNode provides some convenience routines which
    #  perform both of the above phases. These should only
    #  be called from statement nodes, and only when no
    #  coercion nodes need to be added around the expression
    #  being analysed. In that case, the above two phases
    #  should be invoked separately.
    #
    #  Framework code in ExprNode provides much of the common
    #  processing for the various phases. It makes use of the
    #  'subexprs' class attribute of ExprNodes, which should
    #  contain a list of the names of attributes which can
    #  hold sub-nodes or sequences of sub-nodes.
127 128
    #
    #  The framework makes use of a number of abstract methods.
William Stein's avatar
William Stein committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    #  Their responsibilities are as follows.
    #
    #    Declaration Analysis phase
    #
    #      analyse_target_declaration
    #        Called during the Analyse Declarations phase to analyse
    #        the LHS of an assignment or argument of a del statement.
    #        Nodes which cannot be the LHS of an assignment need not
    #        implement it.
    #
    #    Expression Analysis phase
    #
    #      analyse_types
    #        - Call analyse_types on all sub-expressions.
    #        - Check operand types, and wrap coercion nodes around
    #          sub-expressions where needed.
    #        - Set the type of this node.
    #        - If a temporary variable will be required for the
    #          result, set the is_temp flag of this node.
    #
    #      analyse_target_types
    #        Called during the Analyse Types phase to analyse
151
    #        the LHS of an assignment or argument of a del
William Stein's avatar
William Stein committed
152 153
    #        statement. Similar responsibilities to analyse_types.
    #
154 155 156 157
    #      target_code
    #        Called by the default implementation of allocate_target_temps.
    #        Should return a C lvalue for assigning to the node. The default
    #        implementation calls calculate_result_code.
William Stein's avatar
William Stein committed
158 159 160 161
    #
    #      check_const
    #        - Check that this node and its subnodes form a
    #          legal constant expression. If so, do nothing,
162
    #          otherwise call not_const.
William Stein's avatar
William Stein committed
163
    #
164
    #        The default implementation of check_const
William Stein's avatar
William Stein committed
165 166 167 168 169 170 171 172
    #        assumes that the expression is not constant.
    #
    #      check_const_addr
    #        - Same as check_const, except check that the
    #          expression is a C lvalue whose address is
    #          constant. Otherwise, call addr_not_const.
    #
    #        The default implementation of calc_const_addr
173
    #        assumes that the expression is not a constant
William Stein's avatar
William Stein committed
174 175 176 177 178 179 180 181 182 183 184 185
    #        lvalue.
    #
    #   Code Generation phase
    #
    #      generate_evaluation_code
    #        - Call generate_evaluation_code for sub-expressions.
    #        - Perform the functions of generate_result_code
    #          (see below).
    #        - If result is temporary, call generate_disposal_code
    #          on all sub-expressions.
    #
    #        A default implementation of generate_evaluation_code
186
    #        is provided which uses the following abstract methods:
William Stein's avatar
William Stein committed
187 188 189 190 191 192
    #
    #          generate_result_code
    #            - Generate any C statements necessary to calculate
    #              the result of this node from the results of its
    #              sub-expressions.
    #
193
    #          calculate_result_code
194 195
    #            - Should return a C code fragment evaluating to the
    #              result. This is only called when the result is not
196 197
    #              a temporary.
    #
William Stein's avatar
William Stein committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    #      generate_assignment_code
    #        Called on the LHS of an assignment.
    #        - Call generate_evaluation_code for sub-expressions.
    #        - Generate code to perform the assignment.
    #        - If the assignment absorbed a reference, call
    #          generate_post_assignment_code on the RHS,
    #          otherwise call generate_disposal_code on it.
    #
    #      generate_deletion_code
    #        Called on an argument of a del statement.
    #        - Call generate_evaluation_code for sub-expressions.
    #        - Generate code to perform the deletion.
    #        - Call generate_disposal_code on all sub-expressions.
    #
    #
213

William Stein's avatar
William Stein committed
214
    is_sequence_constructor = 0
215
    is_string_literal = 0
William Stein's avatar
William Stein committed
216
    is_attribute = 0
217

William Stein's avatar
William Stein committed
218 219
    saved_subexpr_nodes = None
    is_temp = 0
220
    is_target = 0
221
    is_starred = 0
William Stein's avatar
William Stein committed
222

223 224
    constant_result = constant_value_not_set

225 226 227
    # whether this node with a memoryview type should be broadcast
    memslice_broadcast = False

228 229 230 231
    try:
        _get_child_attrs = operator.attrgetter('subexprs')
    except AttributeError:
        # Python 2.3
232
        def __get_child_attrs(self):
233
            return self.subexprs
234
        _get_child_attrs = __get_child_attrs
235
    child_attrs = property(fget=_get_child_attrs)
236

William Stein's avatar
William Stein committed
237 238 239 240
    def not_implemented(self, method_name):
        print_call_chain(method_name, "not implemented") ###
        raise InternalError(
            "%s.%s not implemented" %
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
241
                (self.__class__.__name__, method_name))
242

William Stein's avatar
William Stein committed
243 244
    def is_lvalue(self):
        return 0
245

246
    def is_addressable(self):
247
        return self.is_lvalue() and not self.type.is_memoryviewslice
248

William Stein's avatar
William Stein committed
249 250 251 252 253 254 255 256 257 258 259
    def is_ephemeral(self):
        #  An ephemeral node is one whose result is in
        #  a Python temporary and we suspect there are no
        #  other references to it. Certain operations are
        #  disallowed on such values, since they are
        #  likely to result in a dangling pointer.
        return self.type.is_pyobject and self.is_temp

    def subexpr_nodes(self):
        #  Extract a list of subexpression nodes based
        #  on the contents of the subexprs class attribute.
260 261 262
        nodes = []
        for name in self.subexprs:
            item = getattr(self, name)
Stefan Behnel's avatar
Stefan Behnel committed
263 264
            if item is not None:
                if type(item) is list:
265
                    nodes.extend(item)
Stefan Behnel's avatar
Stefan Behnel committed
266 267
                else:
                    nodes.append(item)
268
        return nodes
269

270
    def result(self):
271 272 273
        if self.is_temp:
            return self.temp_code
        else:
274
            return self.calculate_result_code()
275

William Stein's avatar
William Stein committed
276 277
    def result_as(self, type = None):
        #  Return the result code cast to the specified C type.
278
        return typecast(type, self.ctype(), self.result())
279

William Stein's avatar
William Stein committed
280 281 282
    def py_result(self):
        #  Return the result code cast to PyObject *.
        return self.result_as(py_object_type)
283

William Stein's avatar
William Stein committed
284 285 286 287
    def ctype(self):
        #  Return the native C type of the result (i.e. the
        #  C type of the result_code expression).
        return self.result_ctype or self.type
288

289
    def get_constant_c_result_code(self):
290
        # Return the constant value of this node as a result code
291 292 293 294 295 296 297
        # string, or None if the node is not constant.  This method
        # can be called when the constant result code is required
        # before the code generation phase.
        #
        # The return value is a string that can represent a simple C
        # value, a constant C name or a constant C expression.  If the
        # node type depends on Python code, this must return None.
298 299
        return None

300
    def calculate_constant_result(self):
301 302 303 304 305
        # Calculate the constant compile time result value of this
        # expression and store it in ``self.constant_result``.  Does
        # nothing by default, thus leaving ``self.constant_result``
        # unknown.  If valid, the result can be an arbitrary Python
        # value.
306 307 308 309 310 311
        #
        # This must only be called when it is assured that all
        # sub-expressions have a valid constant_result value.  The
        # ConstantFolding transform will do this.
        pass

312 313 314 315
    def has_constant_result(self):
        return self.constant_result is not constant_value_not_set and \
               self.constant_result is not not_a_constant

316 317 318
    def compile_time_value(self, denv):
        #  Return value of compile-time expression, or report error.
        error(self.pos, "Invalid compile-time expression")
319

320 321 322
    def compile_time_value_error(self, e):
        error(self.pos, "Error in compile-time expression: %s: %s" % (
            e.__class__.__name__, e))
323

William Stein's avatar
William Stein committed
324
    # ------------- Declaration Analysis ----------------
325

William Stein's avatar
William Stein committed
326 327
    def analyse_target_declaration(self, env):
        error(self.pos, "Cannot assign to or delete this")
328

William Stein's avatar
William Stein committed
329
    # ------------- Expression Analysis ----------------
330

William Stein's avatar
William Stein committed
331 332 333 334 335 336
    def analyse_const_expression(self, env):
        #  Called during the analyse_declarations phase of a
        #  constant expression. Analyses the expression's type,
        #  checks whether it is a legal const expression,
        #  and determines its value.
        self.analyse_types(env)
337
        return self.check_const()
338

William Stein's avatar
William Stein committed
339 340
    def analyse_expressions(self, env):
        #  Convenience routine performing both the Type
341
        #  Analysis and Temp Allocation phases for a whole
William Stein's avatar
William Stein committed
342 343
        #  expression.
        self.analyse_types(env)
344

345
    def analyse_target_expression(self, env, rhs):
William Stein's avatar
William Stein committed
346 347 348 349
        #  Convenience routine performing both the Type
        #  Analysis and Temp Allocation phases for the LHS of
        #  an assignment.
        self.analyse_target_types(env)
350

William Stein's avatar
William Stein committed
351 352 353 354 355
    def analyse_boolean_expression(self, env):
        #  Analyse expression and coerce to a boolean.
        self.analyse_types(env)
        bool = self.coerce_to_boolean(env)
        return bool
356

William Stein's avatar
William Stein committed
357 358 359 360 361 362 363 364 365
    def analyse_temp_boolean_expression(self, env):
        #  Analyse boolean expression and coerce result into
        #  a temporary. This is used when a branch is to be
        #  performed on the result and we won't have an
        #  opportunity to ensure disposal code is executed
        #  afterwards. By forcing the result into a temporary,
        #  we ensure that all disposal has been done by the
        #  time we get the result.
        self.analyse_types(env)
Stefan Behnel's avatar
Stefan Behnel committed
366 367
        return self.coerce_to_boolean(env).coerce_to_simple(env)

368
    # --------------- Type Inference -----------------
369

Robert Bradshaw's avatar
Robert Bradshaw committed
370
    def type_dependencies(self, env):
371 372 373 374
        # Returns the list of entries whose types must be determined
        # before the type of self can be infered.
        if hasattr(self, 'type') and self.type is not None:
            return ()
Robert Bradshaw's avatar
Robert Bradshaw committed
375
        return sum([node.type_dependencies(env) for node in self.subexpr_nodes()], ())
376

377
    def infer_type(self, env):
378 379
        # Attempt to deduce the type of self.
        # Differs from analyse_types as it avoids unnecessary
380 381 382 383 384 385 386 387
        # analysis of subexpressions, but can assume everything
        # in self.type_dependencies() has been resolved.
        if hasattr(self, 'type') and self.type is not None:
            return self.type
        elif hasattr(self, 'entry') and self.entry is not None:
            return self.entry.type
        else:
            self.not_implemented("infer_type")
388

389 390 391
    def nonlocally_immutable(self):
        # Returns whether this variable is a safe reference, i.e.
        # can't be modified as part of globals or closures.
392
        return self.is_temp or self.type.is_array or self.type.is_cfunction
393

William Stein's avatar
William Stein committed
394
    # --------------- Type Analysis ------------------
395

William Stein's avatar
William Stein committed
396 397 398 399
    def analyse_as_module(self, env):
        # If this node can be interpreted as a reference to a
        # cimported module, return its scope, else None.
        return None
400

401 402 403 404
    def analyse_as_type(self, env):
        # If this node can be interpreted as a reference to a
        # type, return that type, else None.
        return None
405

William Stein's avatar
William Stein committed
406 407 408 409
    def analyse_as_extension_type(self, env):
        # If this node can be interpreted as a reference to an
        # extension type, return its type, else None.
        return None
410

William Stein's avatar
William Stein committed
411 412
    def analyse_types(self, env):
        self.not_implemented("analyse_types")
413

William Stein's avatar
William Stein committed
414 415
    def analyse_target_types(self, env):
        self.analyse_types(env)
416

417
    def nogil_check(self, env):
418 419 420
        # By default, any expression based on Python objects is
        # prevented in nogil environments.  Subtypes must override
        # this if they can work without the GIL.
421
        if self.type and self.type.is_pyobject:
422
            self.gil_error()
423

424 425 426 427
    def gil_assignment_check(self, env):
        if env.nogil and self.type.is_pyobject:
            error(self.pos, "Assignment of Python object not allowed without gil")

William Stein's avatar
William Stein committed
428 429
    def check_const(self):
        self.not_const()
430
        return False
431

William Stein's avatar
William Stein committed
432 433
    def not_const(self):
        error(self.pos, "Not allowed in a constant expression")
434

William Stein's avatar
William Stein committed
435 436
    def check_const_addr(self):
        self.addr_not_const()
437
        return False
438

William Stein's avatar
William Stein committed
439 440
    def addr_not_const(self):
        error(self.pos, "Address is not constant")
441

William Stein's avatar
William Stein committed
442
    # ----------------- Result Allocation -----------------
443

William Stein's avatar
William Stein committed
444 445 446 447 448 449
    def result_in_temp(self):
        #  Return true if result is in a temporary owned by
        #  this node or one of its subexpressions. Overridden
        #  by certain nodes which can share the result of
        #  a subnode.
        return self.is_temp
450

William Stein's avatar
William Stein committed
451 452 453
    def target_code(self):
        #  Return code fragment for use as LHS of a C assignment.
        return self.calculate_result_code()
454

William Stein's avatar
William Stein committed
455 456
    def calculate_result_code(self):
        self.not_implemented("calculate_result_code")
457

Robert Bradshaw's avatar
Robert Bradshaw committed
458 459 460
#    def release_target_temp(self, env):
#        #  Release temporaries used by LHS of an assignment.
#        self.release_subexpr_temps(env)
William Stein's avatar
William Stein committed
461

462 463
    def allocate_temp_result(self, code):
        if self.temp_code:
464
            raise RuntimeError("Temp allocated multiple times in %r: %r" % (self.__class__.__name__, self.pos))
465 466 467 468 469
        type = self.type
        if not type.is_void:
            if type.is_pyobject:
                type = PyrexTypes.py_object_type
            self.temp_code = code.funcstate.allocate_temp(
470
                type, manage_ref=self.use_managed_ref)
471 472 473 474 475
        else:
            self.temp_code = None

    def release_temp_result(self, code):
        if not self.temp_code:
476 477 478
            if not self.result_is_used:
                # not used anyway, so ignore if not set up
                return
479 480 481 482 483 484 485 486 487 488
            if self.old_temp:
                raise RuntimeError("temp %s released multiple times in %s" % (
                        self.old_temp, self.__class__.__name__))
            else:
                raise RuntimeError("no temp, but release requested in %s" % (
                        self.__class__.__name__))
        code.funcstate.release_temp(self.temp_code)
        self.old_temp = self.temp_code
        self.temp_code = None

William Stein's avatar
William Stein committed
489
    # ---------------- Code Generation -----------------
490

William Stein's avatar
William Stein committed
491
    def make_owned_reference(self, code):
492 493 494 495
        """
        If result is a pyobject, make sure we own a reference to it.
        If the result is in a temp, it is already a new reference.
        """
William Stein's avatar
William Stein committed
496
        if self.type.is_pyobject and not self.result_in_temp():
497
            code.put_incref(self.result(), self.ctype())
498

499 500 501 502 503 504 505 506
    def make_owned_memoryviewslice(self, code):
        """
        Make sure we own the reference to this memoryview slice.
        """
        if not self.result_in_temp():
            code.put_incref_memoryviewslice(self.result(),
                                            have_gil=self.in_nogil_context)

William Stein's avatar
William Stein committed
507
    def generate_evaluation_code(self, code):
508
        code.mark_pos(self.pos)
509

William Stein's avatar
William Stein committed
510 511 512 513
        #  Generate code to evaluate this node and
        #  its sub-expressions, and dispose of any
        #  temporary results of its sub-expressions.
        self.generate_subexpr_evaluation_code(code)
514 515 516 517

        if self.is_temp:
            self.allocate_temp_result(code)

William Stein's avatar
William Stein committed
518 519
        self.generate_result_code(code)
        if self.is_temp:
520 521
            # If we are temp we do not need to wait until this node is disposed
            # before disposing children.
William Stein's avatar
William Stein committed
522
            self.generate_subexpr_disposal_code(code)
523
            self.free_subexpr_temps(code)
524

William Stein's avatar
William Stein committed
525 526 527
    def generate_subexpr_evaluation_code(self, code):
        for node in self.subexpr_nodes():
            node.generate_evaluation_code(code)
528

William Stein's avatar
William Stein committed
529 530
    def generate_result_code(self, code):
        self.not_implemented("generate_result_code")
531

532 533
    def generate_disposal_code(self, code):
        if self.is_temp:
534 535 536 537 538 539
            if self.result():
                if self.type.is_pyobject:
                    code.put_decref_clear(self.result(), self.ctype())
                elif self.type.is_memoryviewslice:
                    code.put_xdecref_memoryviewslice(
                            self.result(), have_gil=not self.in_nogil_context)
William Stein's avatar
William Stein committed
540
        else:
541
            # Already done if self.is_temp
542
            self.generate_subexpr_disposal_code(code)
543

William Stein's avatar
William Stein committed
544 545 546 547 548
    def generate_subexpr_disposal_code(self, code):
        #  Generate code to dispose of temporary results
        #  of all sub-expressions.
        for node in self.subexpr_nodes():
            node.generate_disposal_code(code)
549

William Stein's avatar
William Stein committed
550 551 552
    def generate_post_assignment_code(self, code):
        if self.is_temp:
            if self.type.is_pyobject:
553
                code.putln("%s = 0;" % self.result())
554 555 556
            elif self.type.is_memoryviewslice:
                code.putln("%s.memview = NULL;" % self.result())
                code.putln("%s.data = NULL;" % self.result())
William Stein's avatar
William Stein committed
557 558
        else:
            self.generate_subexpr_disposal_code(code)
559

William Stein's avatar
William Stein committed
560 561
    def generate_assignment_code(self, rhs, code):
        #  Stub method for nodes which are not legal as
562
        #  the LHS of an assignment. An error will have
William Stein's avatar
William Stein committed
563 564
        #  been reported earlier.
        pass
565

William Stein's avatar
William Stein committed
566 567 568 569 570
    def generate_deletion_code(self, code):
        #  Stub method for nodes that are not legal as
        #  the argument of a del statement. An error
        #  will have been reported earlier.
        pass
571 572

    def free_temps(self, code):
573 574 575 576
        if self.is_temp:
            if not self.type.is_void:
                self.release_temp_result(code)
        else:
577
            self.free_subexpr_temps(code)
578

579 580 581 582
    def free_subexpr_temps(self, code):
        for sub in self.subexpr_nodes():
            sub.free_temps(code)

583 584 585
    def generate_function_definitions(self, env, code):
        pass

586
    # ---------------- Annotation ---------------------
587

588 589 590
    def annotate(self, code):
        for node in self.subexpr_nodes():
            node.annotate(code)
591

William Stein's avatar
William Stein committed
592
    # ----------------- Coercion ----------------------
593

William Stein's avatar
William Stein committed
594 595 596 597 598 599 600 601
    def coerce_to(self, dst_type, env):
        #   Coerce the result so that it can be assigned to
        #   something of type dst_type. If processing is necessary,
        #   wraps this node in a coercion node and returns that.
        #   Otherwise, returns this node unchanged.
        #
        #   This method is called during the analyse_expressions
        #   phase of the src_node's processing.
602 603 604 605 606 607 608 609
        #
        #   Note that subclasses that override this (especially
        #   ConstNodes) must not (re-)set their own .type attribute
        #   here.  Since expression nodes may turn up in different
        #   places in the tree (e.g. inside of CloneNodes in cascaded
        #   assignments), this method must return a new node instance
        #   if it changes the type.
        #
William Stein's avatar
William Stein committed
610 611 612 613
        src = self
        src_type = self.type
        src_is_py_type = src_type.is_pyobject
        dst_is_py_type = dst_type.is_pyobject
614

615 616 617
        if self.check_for_coercion_error(dst_type):
            return self

618
        if dst_type.is_reference and not src_type.is_reference:
619
            dst_type = dst_type.ref_base_type
620

621
        if src_type.is_fused or dst_type.is_fused:
622 623 624 625 626 627 628
            # See if we are coercing a fused function to a pointer to a
            # specialized function
            if (src_type.is_cfunction and not dst_type.is_fused and
                    dst_type.is_ptr and dst_type.base_type.is_cfunction):

                dst_type = dst_type.base_type

629
                for signature in src_type.get_all_specialized_function_types():
630
                    if signature.same_as(dst_type):
Mark Florisson's avatar
Mark Florisson committed
631 632 633 634
                        src.type = signature
                        src.entry = src.type.entry
                        src.entry.used = True
                        return self
635

636
            if src_type.is_fused:
Mark Florisson's avatar
Mark Florisson committed
637
                error(self.pos, "Type is not specialized")
638 639 640
            else:
                error(self.pos, "Cannot coerce to a type that is not specialized")

641 642 643
            self.type = error_type
            return self

644 645 646 647 648
        if self.coercion_type is not None:
            # This is purely for error checking purposes!
            node = NameNode(self.pos, name='', type=self.coercion_type)
            node.coerce_to(dst_type, env)

649
        if dst_type.is_memoryviewslice:
650
            import MemoryView
651
            if not src.type.is_memoryviewslice:
652 653
                if src.type.is_pyobject:
                    src = CoerceToMemViewSliceNode(src, dst_type, env)
654 655 656
                elif src.type.is_array:
                    src = CythonArrayNode.from_carray(src, env).coerce_to(
                                                            dst_type, env)
657
                elif not src_type.is_error:
658 659 660
                    error(self.pos,
                          "Cannot convert '%s' to memoryviewslice" %
                                                                (src_type,))
661 662
            elif not MemoryView.src_conforms_to_dst(
                        src.type, dst_type, broadcast=self.memslice_broadcast):
663 664 665 666 667 668 669 670
                if src.type.dtype.same_as(dst_type.dtype):
                    msg = "Memoryview '%s' not conformable to memoryview '%s'."
                    tup = src.type, dst_type
                else:
                    msg = "Different base types for memoryviews (%s, %s)"
                    tup = src.type.dtype, dst_type.dtype

                error(self.pos, msg % tup)
671

672
        elif dst_type.is_pyobject:
William Stein's avatar
William Stein committed
673
            if not src.type.is_pyobject:
674 675 676 677
                if dst_type is bytes_type and src.type.is_int:
                    src = CoerceIntToBytesNode(src, env)
                else:
                    src = CoerceToPyTypeNode(src, env)
William Stein's avatar
William Stein committed
678
            if not src.type.subtype_of(dst_type):
679 680
                if not isinstance(src, NoneNode):
                    src = PyTypeTestNode(src, dst_type, env)
William Stein's avatar
William Stein committed
681 682
        elif src.type.is_pyobject:
            src = CoerceFromPyTypeNode(dst_type, src, env)
683
        elif (dst_type.is_complex
684 685
              and src_type != dst_type
              and dst_type.assignable_from(src_type)):
686
            src = CoerceToComplexNode(src, dst_type, env)
William Stein's avatar
William Stein committed
687
        else: # neither src nor dst are py types
688
            # Added the string comparison, since for c types that
689
            # is enough, but Cython gets confused when the types are
690
            # in different pxi files.
691
            if not (str(src.type) == str(dst_type) or dst_type.assignable_from(src_type)):
692
                self.fail_assignment(dst_type)
William Stein's avatar
William Stein committed
693 694
        return src

695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    def fail_assignment(self, dst_type):
        error(self.pos, "Cannot assign type '%s' to '%s'" % (self.type, dst_type))

    def check_for_coercion_error(self, dst_type, fail=False, default=None):
        if fail and not default:
            default = "Cannot assign type '%(FROM)s' to '%(TO)s'"
        message = find_coercion_error((self.type, dst_type), default)
        if message is not None:
            error(self.pos, message % {'FROM': self.type, 'TO': dst_type})
            return True
        if fail:
            self.fail_assignment(dst_type)
            return True
        return False

William Stein's avatar
William Stein committed
710 711 712 713 714 715
    def coerce_to_pyobject(self, env):
        return self.coerce_to(PyrexTypes.py_object_type, env)

    def coerce_to_boolean(self, env):
        #  Coerce result to something acceptable as
        #  a boolean value.
716 717 718 719 720 721 722

        # if it's constant, calculate the result now
        if self.has_constant_result():
            bool_value = bool(self.constant_result)
            return BoolNode(self.pos, value=bool_value,
                            constant_result=bool_value)

William Stein's avatar
William Stein committed
723 724 725 726
        type = self.type
        if type.is_pyobject or type.is_ptr or type.is_float:
            return CoerceToBooleanNode(self, env)
        else:
727
            if not (type.is_int or type.is_enum or type.is_error):
728
                error(self.pos,
William Stein's avatar
William Stein committed
729 730
                    "Type '%s' not acceptable as a boolean" % type)
            return self
731

William Stein's avatar
William Stein committed
732 733 734 735 736 737
    def coerce_to_integer(self, env):
        # If not already some C integer type, coerce to longint.
        if self.type.is_int:
            return self
        else:
            return self.coerce_to(PyrexTypes.c_long_type, env)
738

William Stein's avatar
William Stein committed
739 740 741 742 743 744
    def coerce_to_temp(self, env):
        #  Ensure that the result is in a temporary.
        if self.result_in_temp():
            return self
        else:
            return CoerceToTempNode(self, env)
745

William Stein's avatar
William Stein committed
746 747 748 749 750 751
    def coerce_to_simple(self, env):
        #  Ensure that the result is simple (see is_simple).
        if self.is_simple():
            return self
        else:
            return self.coerce_to_temp(env)
752

William Stein's avatar
William Stein committed
753 754 755 756 757 758
    def is_simple(self):
        #  A node is simple if its result is something that can
        #  be referred to without performing any operations, e.g.
        #  a constant, local var, C global var, struct member
        #  reference, or temporary.
        return self.result_in_temp()
759 760

    def may_be_none(self):
761 762
        if self.type and not (self.type.is_pyobject or
                              self.type.is_memoryviewslice):
763 764 765 766
            return False
        if self.constant_result not in (not_a_constant, constant_value_not_set):
            return self.constant_result is not None
        return True
767

768
    def as_cython_attribute(self):
769
        return None
William Stein's avatar
William Stein committed
770

771
    def as_none_safe_node(self, message, error="PyExc_TypeError", format_args=()):
772 773 774
        # Wraps the node in a NoneCheckNode if it is not known to be
        # not-None (e.g. because it is a Python literal).
        if self.may_be_none():
775
            return NoneCheckNode(self, error, message, format_args)
776 777 778 779
        else:
            return self


William Stein's avatar
William Stein committed
780
class AtomicExprNode(ExprNode):
781 782
    #  Abstract base class for expression nodes which have
    #  no sub-expressions.
783

784 785 786
    subexprs = []

    # Override to optimize -- we know we have no children
787 788 789 790
    def generate_subexpr_evaluation_code(self, code):
        pass
    def generate_subexpr_disposal_code(self, code):
        pass
791

792
class PyConstNode(AtomicExprNode):
William Stein's avatar
William Stein committed
793
    #  Abstract base class for constant Python values.
794

795
    is_literal = 1
796
    type = py_object_type
797

William Stein's avatar
William Stein committed
798 799
    def is_simple(self):
        return 1
800 801 802 803

    def may_be_none(self):
        return False

William Stein's avatar
William Stein committed
804
    def analyse_types(self, env):
805
        pass
806

William Stein's avatar
William Stein committed
807 808 809 810 811 812 813 814 815
    def calculate_result_code(self):
        return self.value

    def generate_result_code(self, code):
        pass


class NoneNode(PyConstNode):
    #  The constant value None
816

817
    is_none = 1
William Stein's avatar
William Stein committed
818
    value = "Py_None"
819 820

    constant_result = None
821

822
    nogil_check = None
823

824 825
    def compile_time_value(self, denv):
        return None
826 827 828 829 830

    def may_be_none(self):
        return True


William Stein's avatar
William Stein committed
831 832
class EllipsisNode(PyConstNode):
    #  '...' in a subscript list.
833

William Stein's avatar
William Stein committed
834 835
    value = "Py_Ellipsis"

836 837
    constant_result = Ellipsis

838 839 840
    def compile_time_value(self, denv):
        return Ellipsis

William Stein's avatar
William Stein committed
841

842
class ConstNode(AtomicExprNode):
William Stein's avatar
William Stein committed
843 844 845
    # Abstract base type for literal constant nodes.
    #
    # value     string      C code fragment
846

William Stein's avatar
William Stein committed
847
    is_literal = 1
848
    nogil_check = None
849

William Stein's avatar
William Stein committed
850 851
    def is_simple(self):
        return 1
852

853 854 855
    def nonlocally_immutable(self):
        return 1

856 857 858
    def may_be_none(self):
        return False

William Stein's avatar
William Stein committed
859 860
    def analyse_types(self, env):
        pass # Types are held in class variables
861

William Stein's avatar
William Stein committed
862
    def check_const(self):
863
        return True
864

865
    def get_constant_c_result_code(self):
866 867
        return self.calculate_result_code()

William Stein's avatar
William Stein committed
868 869 870 871 872 873 874
    def calculate_result_code(self):
        return str(self.value)

    def generate_result_code(self, code):
        pass


875 876 877
class BoolNode(ConstNode):
    type = PyrexTypes.c_bint_type
    #  The constant value True or False
878 879 880 881

    def calculate_constant_result(self):
        self.constant_result = self.value

882 883
    def compile_time_value(self, denv):
        return self.value
884

885
    def calculate_result_code(self):
886
        return str(int(self.value))
887

888

William Stein's avatar
William Stein committed
889 890
class NullNode(ConstNode):
    type = PyrexTypes.c_null_ptr_type
891
    value = "NULL"
892
    constant_result = 0
William Stein's avatar
William Stein committed
893

894
    def get_constant_c_result_code(self):
895 896
        return self.value

William Stein's avatar
William Stein committed
897 898 899

class CharNode(ConstNode):
    type = PyrexTypes.c_char_type
900 901 902

    def calculate_constant_result(self):
        self.constant_result = ord(self.value)
903

904
    def compile_time_value(self, denv):
905
        return ord(self.value)
906

William Stein's avatar
William Stein committed
907
    def calculate_result_code(self):
908
        return "'%s'" % StringEncoding.escape_char(self.value)
William Stein's avatar
William Stein committed
909 910 911


class IntNode(ConstNode):
912 913 914

    # unsigned     "" or "U"
    # longness     "" or "L" or "LL"
915
    # is_c_literal   True/False/None   creator considers this a C integer literal
916 917 918

    unsigned = ""
    longness = ""
919
    is_c_literal = None # unknown
920 921 922

    def __init__(self, pos, **kwds):
        ExprNode.__init__(self, pos, **kwds)
Robert Bradshaw's avatar
Robert Bradshaw committed
923
        if 'type' not in kwds:
924 925 926 927 928 929 930 931
            self.type = self.find_suitable_type_for_value()

    def find_suitable_type_for_value(self):
        if self.constant_result is constant_value_not_set:
            try:
                self.calculate_constant_result()
            except ValueError:
                pass
932 933 934 935
        # we ignore 'is_c_literal = True' and instead map signed 32bit
        # integers as C long values
        if self.is_c_literal or \
               self.constant_result in (constant_value_not_set, not_a_constant) or \
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
               self.unsigned or self.longness == 'LL':
            # clearly a C literal
            rank = (self.longness == 'LL') and 2 or 1
            suitable_type = PyrexTypes.modifiers_and_name_to_type[not self.unsigned, rank, "int"]
            if self.type:
                suitable_type = PyrexTypes.widest_numeric_type(suitable_type, self.type)
        else:
            # C literal or Python literal - split at 32bit boundary
            if self.constant_result >= -2**31 and self.constant_result < 2**31:
                if self.type and self.type.is_int:
                    suitable_type = self.type
                else:
                    suitable_type = PyrexTypes.c_long_type
            else:
                suitable_type = PyrexTypes.py_object_type
        return suitable_type
William Stein's avatar
William Stein committed
952

953
    def coerce_to(self, dst_type, env):
954
        if self.type is dst_type:
955
            return self
956
        elif dst_type.is_float:
957
            if self.constant_result is not not_a_constant:
958 959
                return FloatNode(self.pos, value='%d.0' % int(self.constant_result), type=dst_type,
                                 constant_result=float(self.constant_result))
960 961 962
            else:
                return FloatNode(self.pos, value=self.value, type=dst_type,
                                 constant_result=not_a_constant)
963
        if dst_type.is_numeric and not dst_type.is_complex:
964
            node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
965 966
                           type = dst_type, is_c_literal = True,
                           unsigned=self.unsigned, longness=self.longness)
967
            return node
968 969
        elif dst_type.is_pyobject:
            node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
970 971
                           type = PyrexTypes.py_object_type, is_c_literal = False,
                           unsigned=self.unsigned, longness=self.longness)
972
        else:
973 974
            # FIXME: not setting the type here to keep it working with
            # complex numbers. Should they be special cased?
975 976
            node = IntNode(self.pos, value=self.value, constant_result=self.constant_result,
                           unsigned=self.unsigned, longness=self.longness)
977 978 979
        # We still need to perform normal coerce_to processing on the
        # result, because we might be coercing to an extension type,
        # in which case a type test node will be needed.
980 981
        return ConstNode.coerce_to(node, dst_type, env)

982
    def coerce_to_boolean(self, env):
983 984 985 986
        return IntNode(
            self.pos, value=self.value,
            type = PyrexTypes.c_bint_type,
            unsigned=self.unsigned, longness=self.longness)
987

988
    def generate_evaluation_code(self, code):
989
        if self.type.is_pyobject:
990
            # pre-allocate a Python version of the number
991 992
            plain_integer_string = self.value_as_c_integer_string(plain_digits=True)
            self.result_code = code.get_py_num(plain_integer_string, self.longness)
993
        else:
994
            self.result_code = self.get_constant_c_result_code()
995

996
    def get_constant_c_result_code(self):
997 998 999
        return self.value_as_c_integer_string() + self.unsigned + self.longness

    def value_as_c_integer_string(self, plain_digits=False):
1000 1001 1002 1003
        value = self.value
        if isinstance(value, basestring) and len(value) > 2:
            # must convert C-incompatible Py3 oct/bin notations
            if value[1] in 'oO':
1004 1005 1006 1007
                if plain_digits:
                    value = int(value[2:], 8)
                else:
                    value = value[0] + value[2:] # '0o123' => '0123'
1008 1009
            elif value[1] in 'bB':
                value = int(value[2:], 2)
1010 1011 1012
            elif plain_digits and value[1] in 'xX':
                value = int(value[2:], 16)
        return str(value)
1013 1014 1015

    def calculate_result_code(self):
        return self.result_code
William Stein's avatar
William Stein committed
1016

1017
    def calculate_constant_result(self):
1018
        self.constant_result = Utils.str_to_number(self.value)
1019

1020
    def compile_time_value(self, denv):
1021
        return Utils.str_to_number(self.value)
1022 1023


William Stein's avatar
William Stein committed
1024 1025 1026
class FloatNode(ConstNode):
    type = PyrexTypes.c_double_type

1027
    def calculate_constant_result(self):
1028
        self.constant_result = float(self.value)
1029

1030 1031
    def compile_time_value(self, denv):
        return float(self.value)
1032

Stefan Behnel's avatar
Stefan Behnel committed
1033
    def calculate_result_code(self):
1034 1035 1036 1037
        strval = self.value
        assert isinstance(strval, (str, unicode))
        cmpval = repr(float(strval))
        if cmpval == 'nan':
1038
            return "(Py_HUGE_VAL * 0)"
1039
        elif cmpval == 'inf':
1040
            return "Py_HUGE_VAL"
1041
        elif cmpval == '-inf':
1042
            return "(-Py_HUGE_VAL)"
Stefan Behnel's avatar
Stefan Behnel committed
1043 1044
        else:
            return strval
1045

William Stein's avatar
William Stein committed
1046

1047
class BytesNode(ConstNode):
1048 1049 1050 1051
    # A char* or bytes literal
    #
    # value      BytesLiteral

1052
    is_string_literal = True
1053 1054
    # start off as Python 'bytes' to support len() in O(1)
    type = bytes_type
1055 1056

    def compile_time_value(self, denv):
1057
        return self.value
1058

1059
    def analyse_as_type(self, env):
1060
        type = PyrexTypes.parse_basic_type(self.value)
1061
        if type is not None:
1062
            return type
1063 1064 1065 1066 1067 1068 1069
        from TreeFragment import TreeFragment
        pos = (self.pos[0], self.pos[1], self.pos[2]-7)
        declaration = TreeFragment(u"sizeof(%s)" % self.value, name=pos[0].filename, initial_pos=pos)
        sizeof_node = declaration.root.stats[0].expr
        sizeof_node.analyse_types(env)
        if isinstance(sizeof_node, SizeofTypeNode):
            return sizeof_node.arg_type
1070

1071 1072 1073
    def can_coerce_to_char_literal(self):
        return len(self.value) == 1

1074
    def coerce_to_boolean(self, env):
1075 1076
        # This is special because testing a C char* for truth directly
        # would yield the wrong result.
1077 1078
        bool_value = bool(self.value)
        return BoolNode(self.pos, value=bool_value, constant_result=bool_value)
1079

William Stein's avatar
William Stein committed
1080
    def coerce_to(self, dst_type, env):
1081 1082
        if self.type == dst_type:
            return self
1083
        if dst_type.is_int:
1084
            if not self.can_coerce_to_char_literal():
1085 1086
                error(self.pos, "Only single-character string literals can be coerced into ints.")
                return self
Stefan Behnel's avatar
Stefan Behnel committed
1087 1088
            if dst_type.is_unicode_char:
                error(self.pos, "Bytes literals cannot coerce to Py_UNICODE/Py_UCS4, use a unicode literal instead.")
1089
                return self
1090 1091
            return CharNode(self.pos, value=self.value)

1092
        node = BytesNode(self.pos, value=self.value)
1093 1094 1095 1096 1097 1098 1099 1100
        if dst_type.is_pyobject:
            if dst_type in (py_object_type, Builtin.bytes_type):
                node.type = Builtin.bytes_type
            else:
                self.check_for_coercion_error(dst_type, fail=True)
                return node
        elif dst_type == PyrexTypes.c_char_ptr_type:
            node.type = dst_type
1101 1102 1103 1104
            return node
        elif dst_type == PyrexTypes.c_uchar_ptr_type:
            node.type = PyrexTypes.c_char_ptr_type
            return CastNode(node, PyrexTypes.c_uchar_ptr_type)
1105 1106
        elif dst_type.assignable_from(PyrexTypes.c_char_ptr_type):
            node.type = dst_type
1107
            return node
1108

William Stein's avatar
William Stein committed
1109 1110 1111 1112 1113
        # We still need to perform normal coerce_to processing on the
        # result, because we might be coercing to an extension type,
        # in which case a type test node will be needed.
        return ConstNode.coerce_to(node, dst_type, env)

1114
    def generate_evaluation_code(self, code):
William Stein's avatar
William Stein committed
1115
        if self.type.is_pyobject:
1116
            self.result_code = code.get_py_string_const(self.value)
William Stein's avatar
William Stein committed
1117
        else:
1118
            self.result_code = code.get_string_const(self.value)
1119

1120
    def get_constant_c_result_code(self):
1121
        return None # FIXME
1122

1123 1124
    def calculate_result_code(self):
        return self.result_code
William Stein's avatar
William Stein committed
1125 1126


1127
class UnicodeNode(PyConstNode):
1128 1129
    # A Python unicode object
    #
1130 1131
    # value        EncodedString
    # bytes_value  BytesLiteral    the literal parsed as bytes string ('-3' unicode literals only)
Robert Bradshaw's avatar
Robert Bradshaw committed
1132

1133
    is_string_literal = True
1134
    bytes_value = None
1135
    type = unicode_type
1136

1137
    def coerce_to(self, dst_type, env):
1138 1139
        if dst_type is self.type:
            pass
Stefan Behnel's avatar
Stefan Behnel committed
1140
        elif dst_type.is_unicode_char:
1141
            if not self.can_coerce_to_char_literal():
Stefan Behnel's avatar
Stefan Behnel committed
1142
                error(self.pos, "Only single-character Unicode string literals or surrogate pairs can be coerced into Py_UCS4/Py_UNICODE.")
1143 1144
                return self
            int_value = ord(self.value)
Stefan Behnel's avatar
Stefan Behnel committed
1145
            return IntNode(self.pos, type=dst_type, value=str(int_value), constant_result=int_value)
1146
        elif not dst_type.is_pyobject:
1147 1148 1149
            if dst_type.is_string and self.bytes_value is not None:
                # special case: '-3' enforced unicode literal used in a C char* context
                return BytesNode(self.pos, value=self.bytes_value).coerce_to(dst_type, env)
Stefan Behnel's avatar
Stefan Behnel committed
1150
            error(self.pos, "Unicode literals do not support coercion to C types other than Py_UNICODE or Py_UCS4.")
1151 1152 1153 1154
        elif dst_type is not py_object_type:
            if not self.check_for_coercion_error(dst_type):
                self.fail_assignment(dst_type)
        return self
1155

1156 1157
    def can_coerce_to_char_literal(self):
        return len(self.value) == 1
Stefan Behnel's avatar
Stefan Behnel committed
1158 1159 1160
            ## or (len(self.value) == 2
            ##     and (0xD800 <= self.value[0] <= 0xDBFF)
            ##     and (0xDC00 <= self.value[1] <= 0xDFFF))
1161

1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
    def contains_surrogates(self):
        # Check if the unicode string contains surrogate code points
        # on a CPython platform with wide (UCS-4) or narrow (UTF-16)
        # Unicode, i.e. characters that would be spelled as two
        # separate code units on a narrow platform.
        for c in map(ord, self.value):
            if c > 65535: # can only happen on wide platforms
                return True
            # We only look for the first code unit (D800-DBFF) of a
            # surrogate pair - if we find one, the other one
            # (DC00-DFFF) is likely there, too.  If we don't find it,
            # any second code unit cannot make for a surrogate pair by
            # itself.
            if c >= 0xD800 and c <= 0xDBFF:
                return True
        return False

1179
    def generate_evaluation_code(self, code):
1180
        self.result_code = code.get_py_string_const(self.value)
1181 1182 1183

    def calculate_result_code(self):
        return self.result_code
1184

1185 1186
    def compile_time_value(self, env):
        return self.value
1187 1188


1189 1190 1191 1192
class StringNode(PyConstNode):
    # A Python str object, i.e. a byte string in Python 2.x and a
    # unicode string in Python 3.x
    #
1193 1194
    # value          BytesLiteral (or EncodedString with ASCII content)
    # unicode_value  EncodedString or None
1195
    # is_identifier  boolean
1196

1197
    type = str_type
1198
    is_string_literal = True
1199
    is_identifier = None
1200
    unicode_value = None
1201

1202
    def coerce_to(self, dst_type, env):
1203
        if dst_type is not py_object_type and not str_type.subtype_of(dst_type):
1204 1205 1206 1207 1208
#            if dst_type is Builtin.bytes_type:
#                # special case: bytes = 'str literal'
#                return BytesNode(self.pos, value=self.value)
            if not dst_type.is_pyobject:
                return BytesNode(self.pos, value=self.value).coerce_to(dst_type, env)
1209
            self.check_for_coercion_error(dst_type, fail=True)
1210
        return self
1211

1212 1213
    def can_coerce_to_char_literal(self):
        return not self.is_identifier and len(self.value) == 1
1214

1215
    def generate_evaluation_code(self, code):
1216
        self.result_code = code.get_py_string_const(
1217 1218
            self.value, identifier=self.is_identifier, is_str=True,
            unicode_value=self.unicode_value)
1219

1220
    def get_constant_c_result_code(self):
1221 1222
        return None

1223
    def calculate_result_code(self):
1224
        return self.result_code
1225

1226 1227
    def compile_time_value(self, env):
        return self.value
1228 1229


1230 1231 1232 1233
class IdentifierStringNode(StringNode):
    # A special str value that represents an identifier (bytes in Py2,
    # unicode in Py3).
    is_identifier = True
1234 1235


1236
class LongNode(AtomicExprNode):
William Stein's avatar
William Stein committed
1237 1238 1239
    #  Python long integer literal
    #
    #  value   string
1240

1241 1242
    type = py_object_type

1243
    def calculate_constant_result(self):
1244
        self.constant_result = Utils.str_to_number(self.value)
1245

1246
    def compile_time_value(self, denv):
1247
        return Utils.str_to_number(self.value)
1248

William Stein's avatar
William Stein committed
1249 1250
    def analyse_types(self, env):
        self.is_temp = 1
1251

1252 1253 1254
    def may_be_none(self):
        return False

1255 1256
    gil_message = "Constructing Python long int"

1257
    def generate_result_code(self, code):
William Stein's avatar
William Stein committed
1258
        code.putln(
1259
            '%s = PyLong_FromString((char *)"%s", 0, 0); %s' % (
1260
                self.result(),
William Stein's avatar
William Stein committed
1261
                self.value,
1262
                code.error_goto_if_null(self.result(), self.pos)))
1263
        code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
1264 1265


1266
class ImagNode(AtomicExprNode):
William Stein's avatar
William Stein committed
1267 1268 1269
    #  Imaginary number literal
    #
    #  value   float    imaginary part
1270

1271
    type = PyrexTypes.c_double_complex_type
1272 1273 1274

    def calculate_constant_result(self):
        self.constant_result = complex(0.0, self.value)
1275

1276 1277
    def compile_time_value(self, denv):
        return complex(0.0, self.value)
1278

William Stein's avatar
William Stein committed
1279
    def analyse_types(self, env):
1280 1281
        self.type.create_declaration_utility_code(env)

1282 1283 1284
    def may_be_none(self):
        return False

1285
    def coerce_to(self, dst_type, env):
1286 1287 1288
        if self.type is dst_type:
            return self
        node = ImagNode(self.pos, value=self.value)
1289
        if dst_type.is_pyobject:
1290 1291
            node.is_temp = 1
            node.type = PyrexTypes.py_object_type
1292 1293 1294
        # We still need to perform normal coerce_to processing on the
        # result, because we might be coercing to an extension type,
        # in which case a type test node will be needed.
1295
        return AtomicExprNode.coerce_to(node, dst_type, env)
1296 1297 1298

    gil_message = "Constructing complex number"

1299 1300 1301 1302 1303 1304
    def calculate_result_code(self):
        if self.type.is_pyobject:
            return self.result()
        else:
            return "%s(0, %r)" % (self.type.from_parts, float(self.value))

1305
    def generate_result_code(self, code):
1306 1307 1308 1309 1310 1311 1312
        if self.type.is_pyobject:
            code.putln(
                "%s = PyComplex_FromDoubles(0.0, %r); %s" % (
                    self.result(),
                    float(self.value),
                    code.error_goto_if_null(self.result(), self.pos)))
            code.put_gotref(self.py_result())
1313

William Stein's avatar
William Stein committed
1314

Danilo Freitas's avatar
Danilo Freitas committed
1315
class NewExprNode(AtomicExprNode):
1316 1317 1318

    # C++ new statement
    #
Robert Bradshaw's avatar
Robert Bradshaw committed
1319
    # cppclass              node                 c++ class to create
1320

Robert Bradshaw's avatar
Robert Bradshaw committed
1321
    type = None
1322

1323
    def infer_type(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
1324 1325
        type = self.cppclass.analyse_as_type(env)
        if type is None or not type.is_cpp_class:
Danilo Freitas's avatar
Danilo Freitas committed
1326
            error(self.pos, "new operator can only be applied to a C++ class")
Robert Bradshaw's avatar
Robert Bradshaw committed
1327
            self.type = error_type
Danilo Freitas's avatar
Danilo Freitas committed
1328
            return
Robert Bradshaw's avatar
Robert Bradshaw committed
1329
        self.cpp_check(env)
1330
        constructor = type.scope.lookup(u'<init>')
Danilo Freitas's avatar
Danilo Freitas committed
1331
        if constructor is None:
1332
            return_type = PyrexTypes.CFuncType(type, [], exception_check='+')
1333
            return_type = PyrexTypes.CPtrType(return_type)
1334 1335
            type.scope.declare_cfunction(u'<init>', return_type, self.pos)
            constructor = type.scope.lookup(u'<init>')
1336
        self.class_type = type
DaniloFreitas's avatar
DaniloFreitas committed
1337
        self.entry = constructor
Robert Bradshaw's avatar
Robert Bradshaw committed
1338
        self.type = constructor.type
1339
        return self.type
1340

1341
    def analyse_types(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
1342 1343
        if self.type is None:
            self.infer_type(env)
1344 1345 1346 1347

    def may_be_none(self):
        return False

Danilo Freitas's avatar
Danilo Freitas committed
1348 1349
    def generate_result_code(self, code):
        pass
1350

Danilo Freitas's avatar
Danilo Freitas committed
1351
    def calculate_result_code(self):
1352
        return "new " + self.class_type.declaration_code("")
Danilo Freitas's avatar
Danilo Freitas committed
1353

William Stein's avatar
William Stein committed
1354

1355
class NameNode(AtomicExprNode):
William Stein's avatar
William Stein committed
1356 1357 1358 1359
    #  Reference to a local or global variable name.
    #
    #  name            string    Python name of the variable
    #  entry           Entry     Symbol table entry
1360
    #  type_entry      Entry     For extension type names, the original type entry
1361 1362
    #  cf_is_null      boolean   Is uninitialized before this node
    #  cf_maybe_null   boolean   Maybe uninitialized before this node
Vitja Makarov's avatar
Vitja Makarov committed
1363
    #  allow_null      boolean   Don't raise UnboundLocalError
1364
    #  nogil           boolean   Whether it is used in a nogil context
1365

1366 1367
    is_name = True
    is_cython_module = False
Robert Bradshaw's avatar
Robert Bradshaw committed
1368
    cython_attribute = None
1369
    lhs_of_first_assignment = False # TODO: remove me
1370
    is_used_as_rvalue = 0
1371
    entry = None
1372
    type_entry = None
1373 1374
    cf_maybe_null = True
    cf_is_null = False
Vitja Makarov's avatar
Vitja Makarov committed
1375
    allow_null = False
1376
    nogil = False
1377

1378
    def as_cython_attribute(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
1379
        return self.cython_attribute
1380

Robert Bradshaw's avatar
Robert Bradshaw committed
1381 1382 1383 1384 1385 1386 1387
    def type_dependencies(self, env):
        if self.entry is None:
            self.entry = env.lookup(self.name)
        if self.entry is not None and self.entry.type.is_unspecified:
            return (self.entry,)
        else:
            return ()
1388

Robert Bradshaw's avatar
Robert Bradshaw committed
1389 1390 1391 1392 1393
    def infer_type(self, env):
        if self.entry is None:
            self.entry = env.lookup(self.name)
        if self.entry is None:
            return py_object_type
Robert Bradshaw's avatar
Robert Bradshaw committed
1394 1395 1396
        elif (self.entry.type.is_extension_type or self.entry.type.is_builtin_type) and \
                self.name == self.entry.type.name:
            # Unfortunately the type attribute of type objects
1397
            # is used for the pointer to the type they represent.
Robert Bradshaw's avatar
Robert Bradshaw committed
1398
            return type_type
1399
        elif self.entry.type.is_cfunction:
1400 1401 1402 1403 1404 1405
            if self.entry.scope.is_builtin_scope:
                # special case: optimised builtin functions must be treated as Python objects
                return py_object_type
            else:
                # special case: referring to a C function must return its pointer
                return PyrexTypes.CPtrType(self.entry.type)
Robert Bradshaw's avatar
Robert Bradshaw committed
1406 1407
        else:
            return self.entry.type
1408

1409 1410 1411 1412
    def compile_time_value(self, denv):
        try:
            return denv.lookup(self.name)
        except KeyError:
Stefan Behnel's avatar
Stefan Behnel committed
1413
            error(self.pos, "Compile-time name '%s' not defined" % self.name)
1414 1415 1416 1417 1418

    def get_constant_c_result_code(self):
        if not self.entry or self.entry.type.is_pyobject:
            return None
        return self.entry.cname
1419

1420 1421 1422 1423 1424 1425 1426
    def coerce_to(self, dst_type, env):
        #  If coercing to a generic pyobject and this is a builtin
        #  C function with a Python equivalent, manufacture a NameNode
        #  referring to the Python builtin.
        #print "NameNode.coerce_to:", self.name, dst_type ###
        if dst_type is py_object_type:
            entry = self.entry
1427
            if entry and entry.is_cfunction:
1428 1429
                var_entry = entry.as_variable
                if var_entry:
1430
                    if var_entry.is_builtin and var_entry.is_const:
1431
                        var_entry = env.declare_builtin(var_entry.name, self.pos)
1432 1433 1434 1435
                    node = NameNode(self.pos, name = self.name)
                    node.entry = var_entry
                    node.analyse_rvalue_entry(env)
                    return node
1436

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1437
        return super(NameNode, self).coerce_to(dst_type, env)
1438

William Stein's avatar
William Stein committed
1439 1440 1441
    def analyse_as_module(self, env):
        # Try to interpret this as a reference to a cimported module.
        # Returns the module scope, or None.
1442 1443 1444
        entry = self.entry
        if not entry:
            entry = env.lookup(self.name)
William Stein's avatar
William Stein committed
1445 1446 1447
        if entry and entry.as_module:
            return entry.as_module
        return None
1448

1449
    def analyse_as_type(self, env):
1450 1451 1452 1453
        if self.cython_attribute:
            type = PyrexTypes.parse_basic_type(self.cython_attribute)
        else:
            type = PyrexTypes.parse_basic_type(self.name)
1454 1455
        if type:
            return type
1456 1457 1458 1459 1460 1461 1462
        entry = self.entry
        if not entry:
            entry = env.lookup(self.name)
        if entry and entry.is_type:
            return entry.type
        else:
            return None
1463

William Stein's avatar
William Stein committed
1464 1465 1466
    def analyse_as_extension_type(self, env):
        # Try to interpret this as a reference to an extension type.
        # Returns the extension type, or None.
1467 1468 1469
        entry = self.entry
        if not entry:
            entry = env.lookup(self.name)
William Stein's avatar
William Stein committed
1470
        if entry and entry.is_type and entry.type.is_extension_type:
1471 1472 1473
            return entry.type
        else:
            return None
1474

William Stein's avatar
William Stein committed
1475
    def analyse_target_declaration(self, env):
1476 1477
        if not self.entry:
            self.entry = env.lookup_here(self.name)
William Stein's avatar
William Stein committed
1478
        if not self.entry:
1479 1480
            if env.directives['warn.undeclared']:
                warning(self.pos, "implicit declaration of '%s'" % self.name, 1)
1481
            if env.directives['infer_types'] != False:
1482 1483 1484 1485
                type = unspecified_type
            else:
                type = py_object_type
            self.entry = env.declare_var(self.name, type, self.pos)
1486 1487
        if self.entry.is_declared_generic:
            self.result_ctype = py_object_type
1488

1489
    def analyse_types(self, env):
1490
        self.initialized_check = env.directives['initializedcheck']
1491 1492
        if self.entry is None:
            self.entry = env.lookup(self.name)
William Stein's avatar
William Stein committed
1493 1494
        if not self.entry:
            self.entry = env.declare_builtin(self.name, self.pos)
1495 1496 1497
        if not self.entry:
            self.type = PyrexTypes.error_type
            return
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
1498 1499 1500 1501 1502 1503 1504 1505
        entry = self.entry
        if entry:
            entry.used = 1
            if entry.type.is_buffer:
                import Buffer
                Buffer.used_buffer_aux_vars(entry)
            if entry.utility_code:
                env.use_utility_code(entry.utility_code)
1506
        self.analyse_rvalue_entry(env)
1507

1508
    def analyse_target_types(self, env):
William Stein's avatar
William Stein committed
1509
        self.analyse_entry(env)
1510 1511 1512

        if (not self.is_lvalue() and self.entry.is_cfunction and
                self.entry.fused_cfunction and self.entry.as_variable):
1513
            # We need this for the fused 'def' TreeFragment
1514 1515 1516
            self.entry = self.entry.as_variable
            self.type = self.entry.type

1517 1518 1519 1520
        if not self.is_lvalue():
            error(self.pos, "Assignment to non-lvalue '%s'"
                % self.name)
            self.type = PyrexTypes.error_type
Stefan Behnel's avatar
Stefan Behnel committed
1521
        self.entry.used = 1
1522
        if self.entry.type.is_buffer:
1523 1524
            import Buffer
            Buffer.used_buffer_aux_vars(self.entry)
1525

1526 1527 1528 1529
    def analyse_rvalue_entry(self, env):
        #print "NameNode.analyse_rvalue_entry:", self.name ###
        #print "Entry:", self.entry.__dict__ ###
        self.analyse_entry(env)
1530
        entry = self.entry
1531

1532
        if entry.is_declared_generic:
William Stein's avatar
William Stein committed
1533
            self.result_ctype = py_object_type
1534

1535
        if entry.is_pyglobal or entry.is_builtin:
1536
            if entry.is_builtin and entry.is_const:
1537 1538 1539
                self.is_temp = 0
            else:
                self.is_temp = 1
1540
                env.use_utility_code(get_name_interned_utility_code)
1541

1542
            self.is_used_as_rvalue = 1
1543 1544 1545
        elif entry.type.is_memoryviewslice:
            self.is_temp = False
            self.is_used_as_rvalue = True
1546
            self.use_managed_ref = True
1547

1548
    def nogil_check(self, env):
1549
        self.nogil = True
1550 1551 1552
        if self.is_used_as_rvalue:
            entry = self.entry
            if entry.is_builtin:
1553
                if not entry.is_const: # cached builtins are ok
1554
                    self.gil_error()
1555
            elif entry.is_pyglobal:
1556
                self.gil_error()
1557 1558 1559 1560
            elif self.entry.type.is_memoryviewslice:
                if self.cf_is_null or self.cf_maybe_null:
                    import MemoryView
                    MemoryView.err_if_nogil_initialized_check(self.pos, env)
1561 1562 1563

    gil_message = "Accessing Python global or builtin"

1564 1565
    def analyse_entry(self, env):
        #print "NameNode.analyse_entry:", self.name ###
William Stein's avatar
William Stein committed
1566
        self.check_identifier_kind()
1567 1568 1569 1570
        entry = self.entry
        type = entry.type
        self.type = type

William Stein's avatar
William Stein committed
1571
    def check_identifier_kind(self):
1572 1573 1574
        # Check that this is an appropriate kind of name for use in an
        # expression.  Also finds the variable entry associated with
        # an extension type.
William Stein's avatar
William Stein committed
1575
        entry = self.entry
1576 1577
        if entry.is_type and entry.type.is_extension_type:
            self.type_entry = entry
1578
        if not (entry.is_const or entry.is_variable
Danilo Freitas's avatar
Danilo Freitas committed
1579 1580
            or entry.is_builtin or entry.is_cfunction
            or entry.is_cpp_class):
William Stein's avatar
William Stein committed
1581 1582 1583
                if self.entry.as_variable:
                    self.entry = self.entry.as_variable
                else:
1584
                    error(self.pos,
1585 1586
                          "'%s' is not a constant, variable or function identifier" % self.name)

William Stein's avatar
William Stein committed
1587 1588 1589
    def is_simple(self):
        #  If it's not a C variable, it'll be in a temp.
        return 1
1590

1591
    def may_be_none(self):
1592 1593
        if self.cf_state and self.type and (self.type.is_pyobject or
                                            self.type.is_memoryviewslice):
1594 1595 1596 1597 1598 1599 1600
            # gard against infinite recursion on self-dependencies
            if getattr(self, '_none_checking', False):
                # self-dependency - either this node receives a None
                # value from *another* node, or it can not reference
                # None at this point => safe to assume "not None"
                return False
            self._none_checking = True
1601 1602
            # evaluate control flow state to see if there were any
            # potential None values assigned to the node so far
1603
            may_be_none = False
1604 1605
            for assignment in self.cf_state:
                if assignment.rhs.may_be_none():
1606 1607 1608 1609
                    may_be_none = True
                    break
            del self._none_checking
            return may_be_none
1610 1611
        return super(NameNode, self).may_be_none()

1612
    def nonlocally_immutable(self):
1613 1614
        if ExprNode.nonlocally_immutable(self):
            return True
1615 1616 1617
        entry = self.entry
        return entry and (entry.is_local or entry.is_arg) and not entry.in_closure

William Stein's avatar
William Stein committed
1618 1619
    def calculate_target_results(self, env):
        pass
1620

William Stein's avatar
William Stein committed
1621 1622
    def check_const(self):
        entry = self.entry
Robert Bradshaw's avatar
Robert Bradshaw committed
1623
        if entry is not None and not (entry.is_const or entry.is_cfunction or entry.is_builtin):
William Stein's avatar
William Stein committed
1624
            self.not_const()
1625 1626
            return False
        return True
1627

William Stein's avatar
William Stein committed
1628 1629
    def check_const_addr(self):
        entry = self.entry
1630
        if not (entry.is_cglobal or entry.is_cfunction or entry.is_builtin):
William Stein's avatar
William Stein committed
1631
            self.addr_not_const()
1632 1633
            return False
        return True
William Stein's avatar
William Stein committed
1634 1635 1636 1637 1638

    def is_lvalue(self):
        return self.entry.is_variable and \
            not self.entry.type.is_array and \
            not self.entry.is_readonly
1639

1640
    def is_addressable(self):
1641
        return self.entry.is_variable and not self.type.is_memoryviewslice
1642

William Stein's avatar
William Stein committed
1643 1644 1645 1646
    def is_ephemeral(self):
        #  Name nodes are never ephemeral, even if the
        #  result is in a temporary.
        return 0
1647

William Stein's avatar
William Stein committed
1648
    def calculate_result_code(self):
Stefan Behnel's avatar
Stefan Behnel committed
1649 1650
        entry = self.entry
        if not entry:
William Stein's avatar
William Stein committed
1651
            return "<error>" # There was an error earlier
Stefan Behnel's avatar
Stefan Behnel committed
1652
        return entry.cname
1653

William Stein's avatar
William Stein committed
1654
    def generate_result_code(self, code):
1655
        assert hasattr(self, 'entry')
William Stein's avatar
William Stein committed
1656 1657 1658
        entry = self.entry
        if entry is None:
            return # There was an error earlier
1659
        if entry.is_builtin and entry.is_const:
1660
            return # Lookup already cached
Stefan Behnel's avatar
Stefan Behnel committed
1661
        elif entry.is_pyclass_attr:
Vitja Makarov's avatar
Vitja Makarov committed
1662 1663 1664 1665 1666 1667
            assert entry.type.is_pyobject, "Python global or builtin not a Python object"
            interned_cname = code.intern_identifier(self.entry.name)
            if entry.is_builtin:
                namespace = Naming.builtins_cname
            else: # entry.is_pyglobal
                namespace = entry.scope.namespace_cname
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
            if not self.cf_is_null:
                code.putln(
                    '%s = PyObject_GetItem(%s, %s);' % (
                        self.result(),
                        namespace,
                        interned_cname))
            if self.cf_maybe_null:
                if not self.cf_is_null:
                    code.putln('if (unlikely(!%s)) {' % self.result())
                    code.putln('PyErr_Clear();')
                code.putln(
                    '%s = __Pyx_GetName(%s, %s);' % (
                    self.result(),
                    Naming.module_cname,
                    interned_cname))
                if not self.cf_is_null:
                    code.putln("}");
            code.putln(code.error_goto_if_null(self.result(), self.pos))
Vitja Makarov's avatar
Vitja Makarov committed
1686
            code.put_gotref(self.py_result())
1687

1688
        elif entry.is_pyglobal or entry.is_builtin:
1689 1690
            assert entry.type.is_pyobject, "Python global or builtin not a Python object"
            interned_cname = code.intern_identifier(self.entry.name)
William Stein's avatar
William Stein committed
1691 1692 1693
            if entry.is_builtin:
                namespace = Naming.builtins_cname
            else: # entry.is_pyglobal
1694
                namespace = entry.scope.namespace_cname
1695
            code.globalstate.use_utility_code(get_name_interned_utility_code)
1696 1697
            code.putln(
                '%s = __Pyx_GetName(%s, %s); %s' % (
1698
                self.result(),
1699
                namespace,
1700
                interned_cname,
1701
                code.error_goto_if_null(self.result(), self.pos)))
1702
            code.put_gotref(self.py_result())
1703

1704
        elif entry.is_local or entry.in_closure or entry.from_closure or entry.type.is_memoryviewslice:
1705 1706 1707 1708
            # Raise UnboundLocalError for objects and memoryviewslices
            raise_unbound = (
                (self.cf_maybe_null or self.cf_is_null) and not self.allow_null)
            null_code = entry.type.check_for_null_code(entry.cname)
1709

1710 1711 1712
            memslice_check = entry.type.is_memoryviewslice and self.initialized_check

            if null_code and raise_unbound and (entry.type.is_pyobject or memslice_check):
1713
                code.put_error_if_unbound(self.pos, entry, self.in_nogil_context)
William Stein's avatar
William Stein committed
1714 1715

    def generate_assignment_code(self, rhs, code):
1716
        #print "NameNode.generate_assignment_code:", self.name ###
William Stein's avatar
William Stein committed
1717 1718 1719
        entry = self.entry
        if entry is None:
            return # There was an error earlier
1720 1721 1722 1723

        if (self.entry.type.is_ptr and isinstance(rhs, ListNode)
            and not self.lhs_of_first_assignment):
            error(self.pos, "Literal list must be assigned to pointer at time of declaration")
1724

1725 1726
        # is_pyglobal seems to be True for module level-globals only.
        # We use this to access class->tp_dict if necessary.
William Stein's avatar
William Stein committed
1727
        if entry.is_pyglobal:
1728 1729
            assert entry.type.is_pyobject, "Python global or builtin not a Python object"
            interned_cname = code.intern_identifier(self.entry.name)
1730
            namespace = self.entry.scope.namespace_cname
1731
            if entry.is_member:
Stefan Behnel's avatar
Stefan Behnel committed
1732
                # if the entry is a member we have to cheat: SetAttr does not work
1733
                # on types, so we create a descriptor which is then added to tp_dict
1734 1735 1736
                code.put_error_if_neg(self.pos,
                    'PyDict_SetItem(%s->tp_dict, %s, %s)' % (
                        namespace,
1737
                        interned_cname,
1738
                        rhs.py_result()))
1739 1740
                rhs.generate_disposal_code(code)
                rhs.free_temps(code)
1741
                # in Py2.6+, we need to invalidate the method cache
1742
                code.putln("PyType_Modified(%s);" %
Vitja Makarov's avatar
Vitja Makarov committed
1743
                            entry.scope.parent_type.typeptr_cname)
Stefan Behnel's avatar
Stefan Behnel committed
1744
            elif entry.is_pyclass_attr:
Vitja Makarov's avatar
Vitja Makarov committed
1745
                code.put_error_if_neg(self.pos,
Stefan Behnel's avatar
Stefan Behnel committed
1746
                    'PyObject_SetItem(%s, %s, %s)' % (
Vitja Makarov's avatar
Vitja Makarov committed
1747 1748 1749 1750 1751 1752
                        namespace,
                        interned_cname,
                        rhs.py_result()))
                rhs.generate_disposal_code(code)
                rhs.free_temps(code)
            else:
1753 1754 1755
                code.put_error_if_neg(self.pos,
                    'PyObject_SetAttr(%s, %s, %s)' % (
                        namespace,
1756
                        interned_cname,
1757
                        rhs.py_result()))
1758
                if debug_disposal_code:
Stefan Behnel's avatar
Stefan Behnel committed
1759 1760
                    print("NameNode.generate_assignment_code:")
                    print("...generating disposal code for %s" % rhs)
1761
                rhs.generate_disposal_code(code)
1762
                rhs.free_temps(code)
William Stein's avatar
William Stein committed
1763
        else:
1764
            if self.type.is_memoryviewslice:
1765
                self.generate_acquire_memoryviewslice(rhs, code)
1766

1767
            elif self.type.is_buffer:
1768 1769 1770 1771 1772 1773 1774 1775 1776
                # Generate code for doing the buffer release/acquisition.
                # This might raise an exception in which case the assignment (done
                # below) will not happen.
                #
                # The reason this is not in a typetest-like node is because the
                # variables that the acquired buffer info is stored to is allocated
                # per entry and coupled with it.
                self.generate_acquire_buffer(rhs, code)

1777
            if self.type.is_pyobject:
William Stein's avatar
William Stein committed
1778 1779 1780 1781
                #print "NameNode.generate_assignment_code: to", self.name ###
                #print "...from", rhs ###
                #print "...LHS type", self.type, "ctype", self.ctype() ###
                #print "...RHS type", rhs.type, "ctype", rhs.ctype() ###
1782 1783
                if self.use_managed_ref:
                    rhs.make_owned_reference(code)
1784
                    is_external_ref = entry.is_cglobal or self.entry.in_closure or self.entry.from_closure
1785 1786 1787 1788 1789 1790
                    if is_external_ref:
                        if not self.cf_is_null:
                            if self.cf_maybe_null:
                                code.put_xgotref(self.py_result())
                            else:
                                code.put_gotref(self.py_result())
1791 1792 1793
                    if entry.is_cglobal:
                        code.put_decref(self.result(), self.ctype())
                    else:
1794 1795
                        if not self.cf_is_null:
                            if self.cf_maybe_null:
1796
                                code.put_xdecref(self.result(), self.ctype())
1797 1798
                            else:
                                code.put_decref(self.result(), self.ctype())
1799
                    if is_external_ref:
1800
                        code.put_giveref(rhs.py_result())
1801
            if not self.type.is_memoryviewslice:
1802
                code.putln('%s = %s;' % (self.result(), rhs.result_as(self.ctype())))
1803 1804 1805 1806
                if debug_disposal_code:
                    print("NameNode.generate_assignment_code:")
                    print("...generating post-assignment code for %s" % rhs)
                rhs.generate_post_assignment_code(code)
1807 1808
            elif rhs.result_in_temp():
                rhs.generate_post_assignment_code(code)
1809

1810
            rhs.free_temps(code)
1811

1812 1813
    def generate_acquire_memoryviewslice(self, rhs, code):
        """
1814 1815
        Slices, coercions from objects, return values etc are new references.
        We have a borrowed reference in case of dst = src
1816 1817 1818 1819 1820 1821 1822 1823 1824
        """
        import MemoryView

        MemoryView.put_acquire_memoryviewslice(
            lhs_cname=self.result(),
            lhs_type=self.type,
            lhs_pos=self.pos,
            rhs=rhs,
            code=code,
1825 1826
            have_gil=not self.in_nogil_context,
            first_assignment=self.cf_is_null)
1827

1828
    def generate_acquire_buffer(self, rhs, code):
1829 1830 1831
        # rhstmp is only used in case the rhs is a complicated expression leading to
        # the object, to avoid repeating the same C expression for every reference
        # to the rhs. It does NOT hold a reference.
1832 1833 1834 1835 1836 1837 1838
        pretty_rhs = isinstance(rhs, NameNode) or rhs.is_temp
        if pretty_rhs:
            rhstmp = rhs.result_as(self.ctype())
        else:
            rhstmp = code.funcstate.allocate_temp(self.entry.type, manage_ref=False)
            code.putln('%s = %s;' % (rhstmp, rhs.result_as(self.ctype())))

1839
        import Buffer
1840
        Buffer.put_assign_to_buffer(self.result(), rhstmp, self.entry,
1841
                                    is_initialized=not self.lhs_of_first_assignment,
1842
                                    pos=self.pos, code=code)
1843

1844 1845 1846
        if not pretty_rhs:
            code.putln("%s = 0;" % rhstmp)
            code.funcstate.release_temp(rhstmp)
1847

William Stein's avatar
William Stein committed
1848 1849 1850
    def generate_deletion_code(self, code):
        if self.entry is None:
            return # There was an error earlier
1851
        elif self.entry.is_pyclass_attr:
Vitja Makarov's avatar
Vitja Makarov committed
1852
            namespace = self.entry.scope.namespace_cname
1853
            interned_cname = code.intern_identifier(self.entry.name)
Vitja Makarov's avatar
Vitja Makarov committed
1854
            code.put_error_if_neg(self.pos,
1855
                'PyObject_DelItem(%s, %s)' % (
Vitja Makarov's avatar
Vitja Makarov committed
1856
                    namespace,
1857
                    interned_cname))
1858 1859 1860 1861 1862
        elif self.entry.is_pyglobal:
            code.put_error_if_neg(self.pos,
                '__Pyx_DelAttrString(%s, "%s")' % (
                    Naming.module_cname,
                    self.entry.name))
1863
        elif self.entry.type.is_pyobject or self.entry.type.is_memoryviewslice:
1864 1865
            if not self.cf_is_null:
                if self.cf_maybe_null:
1866
                    code.put_error_if_unbound(self.pos, self.entry)
1867 1868 1869 1870 1871 1872 1873

                if self.entry.type.is_pyobject:
                    code.put_decref(self.result(), self.ctype())
                    code.putln('%s = NULL;' % self.result())
                else:
                    code.put_xdecref_memoryviewslice(self.entry.cname,
                                                     have_gil=not self.nogil)
Vitja Makarov's avatar
Vitja Makarov committed
1874
        else:
1875
            error(self.pos, "Deletion of C names not supported")
1876

1877 1878 1879 1880 1881 1882 1883
    def annotate(self, code):
        if hasattr(self, 'is_called') and self.is_called:
            pos = (self.pos[0], self.pos[1], self.pos[2] - len(self.name) - 1)
            if self.type.is_pyobject:
                code.annotate(pos, AnnotationItem('py_call', 'python function', size=len(self.name)))
            else:
                code.annotate(pos, AnnotationItem('c_call', 'c function', size=len(self.name)))
1884

1885
class BackquoteNode(ExprNode):
William Stein's avatar
William Stein committed
1886 1887 1888
    #  `expr`
    #
    #  arg    ExprNode
1889

1890
    type = py_object_type
1891

William Stein's avatar
William Stein committed
1892
    subexprs = ['arg']
1893

William Stein's avatar
William Stein committed
1894 1895 1896 1897
    def analyse_types(self, env):
        self.arg.analyse_types(env)
        self.arg = self.arg.coerce_to_pyobject(env)
        self.is_temp = 1
1898 1899 1900

    gil_message = "Backquote expression"

1901 1902 1903
    def calculate_constant_result(self):
        self.constant_result = repr(self.arg.constant_result)

William Stein's avatar
William Stein committed
1904 1905
    def generate_result_code(self, code):
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
1906
            "%s = PyObject_Repr(%s); %s" % (
1907
                self.result(),
William Stein's avatar
William Stein committed
1908
                self.arg.py_result(),
1909
                code.error_goto_if_null(self.result(), self.pos)))
1910
        code.put_gotref(self.py_result())
1911

William Stein's avatar
William Stein committed
1912

1913
class ImportNode(ExprNode):
William Stein's avatar
William Stein committed
1914
    #  Used as part of import statement implementation.
1915
    #  Implements result =
Haoyu Bai's avatar
Haoyu Bai committed
1916
    #    __import__(module_name, globals(), None, name_list, level)
William Stein's avatar
William Stein committed
1917
    #
Haoyu Bai's avatar
Haoyu Bai committed
1918 1919 1920
    #  module_name   StringNode            dotted name of module. Empty module
    #                       name means importing the parent package accourding
    #                       to level
1921
    #  name_list     ListNode or None      list of names to be imported
Haoyu Bai's avatar
Haoyu Bai committed
1922 1923 1924 1925 1926
    #  level         int                   relative import level:
    #                       -1: attempt both relative import and absolute import;
    #                        0: absolute import;
    #                       >0: the number of parent directories to search
    #                           relative to the current module.
1927 1928
    #                     None: decide the level according to language level and
    #                           directives
1929

1930
    type = py_object_type
1931

William Stein's avatar
William Stein committed
1932
    subexprs = ['module_name', 'name_list']
1933

William Stein's avatar
William Stein committed
1934
    def analyse_types(self, env):
1935 1936 1937 1938 1939
        if self.level is None:
            if env.directives['language_level'] < 3 or env.directives['py2_import']:
                self.level = -1
            else:
                self.level = 0
William Stein's avatar
William Stein committed
1940 1941 1942 1943
        self.module_name.analyse_types(env)
        self.module_name = self.module_name.coerce_to_pyobject(env)
        if self.name_list:
            self.name_list.analyse_types(env)
1944
            self.name_list.coerce_to_pyobject(env)
William Stein's avatar
William Stein committed
1945 1946
        self.is_temp = 1
        env.use_utility_code(import_utility_code)
1947 1948 1949

    gil_message = "Python import"

William Stein's avatar
William Stein committed
1950 1951 1952 1953 1954 1955
    def generate_result_code(self, code):
        if self.name_list:
            name_list_code = self.name_list.py_result()
        else:
            name_list_code = "0"
        code.putln(
Haoyu Bai's avatar
Haoyu Bai committed
1956
            "%s = __Pyx_Import(%s, %s, %d); %s" % (
1957
                self.result(),
William Stein's avatar
William Stein committed
1958 1959
                self.module_name.py_result(),
                name_list_code,
Haoyu Bai's avatar
Haoyu Bai committed
1960
                self.level,
1961
                code.error_goto_if_null(self.result(), self.pos)))
1962
        code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
1963 1964


1965
class IteratorNode(ExprNode):
William Stein's avatar
William Stein committed
1966
    #  Used as part of for statement implementation.
1967
    #
William Stein's avatar
William Stein committed
1968 1969 1970
    #  Implements result = iter(sequence)
    #
    #  sequence   ExprNode
1971

1972
    type = py_object_type
1973
    iter_func_ptr = None
1974
    counter_cname = None
1975
    reversed = False      # currently only used for list/tuple types (see Optimize.py)
1976

William Stein's avatar
William Stein committed
1977
    subexprs = ['sequence']
1978

William Stein's avatar
William Stein committed
1979 1980
    def analyse_types(self, env):
        self.sequence.analyse_types(env)
1981 1982
        if (self.sequence.type.is_array or self.sequence.type.is_ptr) and \
                not self.sequence.type.is_string:
1983
            # C array iteration will be transformed later on
1984
            self.type = self.sequence.type
1985 1986
        elif self.sequence.type.is_cpp_class:
            self.analyse_cpp_types(env)
1987 1988
        else:
            self.sequence = self.sequence.coerce_to_pyobject(env)
1989 1990 1991
            if self.sequence.type is list_type or \
                   self.sequence.type is tuple_type:
                self.sequence = self.sequence.as_none_safe_node("'NoneType' object is not iterable")
William Stein's avatar
William Stein committed
1992
        self.is_temp = 1
1993 1994 1995

    gil_message = "Iterating over Python object"

1996 1997 1998 1999
    _func_iternext_type = PyrexTypes.CPtrType(PyrexTypes.CFuncType(
        PyrexTypes.py_object_type, [
            PyrexTypes.CFuncTypeArg("it", PyrexTypes.py_object_type, None),
            ]))
2000

2001 2002 2003
    def type_dependencies(self, env):
        return self.sequence.type_dependencies(env)

2004 2005
    def infer_type(self, env):
        sequence_type = self.sequence.infer_type(env)
2006
        if sequence_type.is_array or sequence_type.is_ptr:
2007 2008 2009 2010 2011
            return sequence_type
        elif sequence_type.is_cpp_class:
            begin = sequence_type.scope.lookup("begin")
            if begin is not None:
                return begin.type.base_type.return_type
2012 2013 2014 2015
        elif sequence_type.is_pyobject:
            return sequence_type
        else:
            return py_object_type
2016
    
2017
    def analyse_cpp_types(self, env):
2018 2019 2020 2021 2022 2023 2024 2025 2026
        sequence_type = self.sequence.type
        if sequence_type.is_ptr:
            sequence_type = sequence_type.base_type
        begin = sequence_type.scope.lookup("begin")
        end = sequence_type.scope.lookup("end")
        if (begin is None
            or not begin.type.is_ptr
            or not begin.type.base_type.is_cfunction
            or begin.type.base_type.args):
2027 2028 2029
            error(self.pos, "missing begin() on %s" % self.sequence.type)
            self.type = error_type
            return
2030 2031 2032 2033
        if (end is None
            or not end.type.is_ptr
            or not end.type.base_type.is_cfunction
            or end.type.base_type.args):
2034 2035 2036 2037 2038
            error(self.pos, "missing end() on %s" % self.sequence.type)
            self.type = error_type
            return
        iter_type = begin.type.base_type.return_type
        if iter_type.is_cpp_class:
2039 2040 2041 2042
            if env.lookup_operator_for_types(
                    self.pos,
                    "!=",
                    [iter_type, end.type.base_type.return_type]) is None:
2043 2044 2045
                error(self.pos, "missing operator!= on result of begin() on %s" % self.sequence.type)
                self.type = error_type
                return
2046
            if env.lookup_operator_for_types(self.pos, '++', [iter_type]) is None:
2047 2048 2049
                error(self.pos, "missing operator++ on result of begin() on %s" % self.sequence.type)
                self.type = error_type
                return
2050
            if env.lookup_operator_for_types(self.pos, '*', [iter_type]) is None:
2051 2052 2053 2054 2055
                error(self.pos, "missing operator* on result of begin() on %s" % self.sequence.type)
                self.type = error_type
                return
            self.type = iter_type
        elif iter_type.is_ptr:
2056 2057
            if not (iter_type == end.type.base_type.return_type):
                error(self.pos, "incompatible types for begin() and end()")
2058 2059 2060 2061 2062 2063
            self.type = iter_type
        else:
            error(self.pos, "result type of begin() on %s must be a C++ class or pointer" % self.sequence.type)
            self.type = error_type
            return
    
William Stein's avatar
William Stein committed
2064
    def generate_result_code(self, code):
Stefan Behnel's avatar
Stefan Behnel committed
2065
        sequence_type = self.sequence.type
2066 2067 2068 2069
        if sequence_type.is_cpp_class:
            # TODO: Limit scope.
            code.putln("%s = %s.begin();" % (self.result(), self.sequence.result()))
            return
Stefan Behnel's avatar
Stefan Behnel committed
2070
        if sequence_type.is_array or sequence_type.is_ptr:
2071
            raise InternalError("for in carray slice not transformed")
Stefan Behnel's avatar
Stefan Behnel committed
2072 2073
        is_builtin_sequence = sequence_type is list_type or \
                              sequence_type is tuple_type
2074 2075 2076
        if not is_builtin_sequence:
            # reversed() not currently optimised (see Optimize.py)
            assert not self.reversed, "internal error: reversed() only implemented for list/tuple objects"
Stefan Behnel's avatar
Stefan Behnel committed
2077 2078
        self.may_be_a_sequence = not sequence_type.is_builtin_type
        if self.may_be_a_sequence:
2079 2080 2081 2082
            code.putln(
                "if (PyList_CheckExact(%s) || PyTuple_CheckExact(%s)) {" % (
                    self.sequence.py_result(),
                    self.sequence.py_result()))
Stefan Behnel's avatar
Stefan Behnel committed
2083
        if is_builtin_sequence or self.may_be_a_sequence:
2084 2085
            self.counter_cname = code.funcstate.allocate_temp(
                PyrexTypes.c_py_ssize_t_type, manage_ref=False)
2086 2087 2088 2089 2090 2091 2092
            if self.reversed:
                if sequence_type is list_type:
                    init_value = 'PyList_GET_SIZE(%s) - 1' % self.result()
                else:
                    init_value = 'PyTuple_GET_SIZE(%s) - 1' % self.result()
            else:
                init_value = '0'
2093
            code.putln(
2094
                "%s = %s; __Pyx_INCREF(%s); %s = %s;" % (
2095 2096
                    self.result(),
                    self.sequence.py_result(),
2097 2098 2099 2100
                    self.result(),
                    self.counter_cname,
                    init_value
                    ))
2101
        if not is_builtin_sequence:
Stefan Behnel's avatar
Stefan Behnel committed
2102
            self.iter_func_ptr = code.funcstate.allocate_temp(self._func_iternext_type, manage_ref=False)
Stefan Behnel's avatar
Stefan Behnel committed
2103
            if self.may_be_a_sequence:
Stefan Behnel's avatar
Stefan Behnel committed
2104
                code.putln("%s = NULL;" % self.iter_func_ptr)
2105
                code.putln("} else {")
2106 2107
                code.put("%s = -1; " % self.counter_cname)
            code.putln("%s = PyObject_GetIter(%s); %s" % (
2108 2109 2110
                    self.result(),
                    self.sequence.py_result(),
                    code.error_goto_if_null(self.result(), self.pos)))
2111
            code.put_gotref(self.py_result())
2112
            code.putln("%s = Py_TYPE(%s)->tp_iternext;" % (self.iter_func_ptr, self.py_result()))
Stefan Behnel's avatar
Stefan Behnel committed
2113 2114 2115 2116
        if self.may_be_a_sequence:
            code.putln("}")

    def generate_next_sequence_item(self, test_name, result_name, code):
2117
        assert self.counter_cname, "internal error: counter_cname temp not prepared"
Stefan Behnel's avatar
Stefan Behnel committed
2118 2119 2120 2121 2122
        code.putln(
            "if (%s >= Py%s_GET_SIZE(%s)) break;" % (
                self.counter_cname,
                test_name,
                self.py_result()))
2123 2124 2125 2126
        if self.reversed:
            inc_dec = '--'
        else:
            inc_dec = '++'
2127
        code.putln("#if CYTHON_COMPILING_IN_CPYTHON")
Stefan Behnel's avatar
Stefan Behnel committed
2128
        code.putln(
2129
            "%s = Py%s_GET_ITEM(%s, %s); __Pyx_INCREF(%s); %s%s;" % (
Stefan Behnel's avatar
Stefan Behnel committed
2130 2131 2132 2133 2134
                result_name,
                test_name,
                self.py_result(),
                self.counter_cname,
                result_name,
2135 2136
                self.counter_cname,
                inc_dec))
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
        code.putln("#else")
        code.putln(
            "%s = PySequence_ITEM(%s, %s); %s%s; %s;" % (
                result_name,
                self.py_result(),
                self.counter_cname,
                self.counter_cname,
                inc_dec,
                code.error_goto_if_null(result_name, self.pos)))
        code.putln("#endif")
Stefan Behnel's avatar
Stefan Behnel committed
2147 2148 2149

    def generate_iter_next_result_code(self, result_name, code):
        sequence_type = self.sequence.type
2150 2151
        if self.reversed:
            code.putln("if (%s < 0) break;" % self.counter_cname)
2152 2153
        if sequence_type.is_cpp_class:
            # TODO: Cache end() call?
2154
            code.putln("if (!(%s != %s.end())) break;" % (
2155 2156 2157 2158 2159 2160 2161 2162
                            self.result(),
                            self.sequence.result()));
            code.putln("%s = *%s;" % (
                            result_name,
                            self.result()))
            code.putln("++%s;" % self.result())
            return
        elif sequence_type is list_type:
Stefan Behnel's avatar
Stefan Behnel committed
2163 2164 2165 2166 2167 2168 2169 2170
            self.generate_next_sequence_item('List', result_name, code)
            return
        elif sequence_type is tuple_type:
            self.generate_next_sequence_item('Tuple', result_name, code)
            return

        if self.may_be_a_sequence:
            for test_name in ('List', 'Tuple'):
2171 2172
                code.putln("if (!%s && Py%s_CheckExact(%s)) {" % (
                    self.iter_func_ptr, test_name, self.py_result()))
Stefan Behnel's avatar
Stefan Behnel committed
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
                self.generate_next_sequence_item(test_name, result_name, code)
                code.put("} else ")

        code.putln("{")
        code.putln(
            "%s = %s(%s);" % (
                result_name,
                self.iter_func_ptr,
                self.py_result()))
        code.putln("if (unlikely(!%s)) {" % result_name)
        code.putln("if (PyErr_Occurred()) {")
        code.putln("if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) PyErr_Clear();")
        code.putln("else %s" % code.error_goto(self.pos))
        code.putln("}")
        code.putln("break;")
        code.putln("}")
        code.put_gotref(result_name)
        code.putln("}")
William Stein's avatar
William Stein committed
2191

2192
    def free_temps(self, code):
2193 2194
        if self.counter_cname:
            code.funcstate.release_temp(self.counter_cname)
2195 2196 2197 2198
        if self.iter_func_ptr:
            code.funcstate.release_temp(self.iter_func_ptr)
            self.iter_func_ptr = None
        ExprNode.free_temps(self, code)
William Stein's avatar
William Stein committed
2199 2200


2201
class NextNode(AtomicExprNode):
William Stein's avatar
William Stein committed
2202 2203 2204 2205 2206
    #  Used as part of for statement implementation.
    #  Implements result = iterator.next()
    #  Created during analyse_types phase.
    #  The iterator is not owned by this node.
    #
2207
    #  iterator   IteratorNode
2208

2209
    def __init__(self, iterator):
William Stein's avatar
William Stein committed
2210 2211
        self.pos = iterator.pos
        self.iterator = iterator
2212 2213 2214 2215

    def type_dependencies(self, env):
        return self.iterator.type_dependencies(env)

2216 2217 2218
    def infer_type(self, env, iterator_type = None):
        if iterator_type is None:
            iterator_type = self.iterator.infer_type(env)
2219
        if iterator_type.is_ptr or iterator_type.is_array:
2220
            return iterator_type.base_type
2221
        elif iterator_type.is_cpp_class:
2222
            item_type = env.lookup_operator_for_types(self.pos, "*", [iterator_type]).type.base_type.return_type
2223 2224 2225
            if item_type.is_reference:
                item_type = item_type.ref_base_type
            return item_type
2226
        else:
2227 2228
            # Avoid duplication of complicated logic.
            fake_index_node = IndexNode(self.pos,
2229
                                        base=self.iterator.sequence,
2230
                                        index=IntNode(self.pos, value='0'))
2231 2232 2233
            # TODO(vile hack): infer_type should be side-effect free
            if isinstance(self.iterator.sequence, SimpleCallNode):
                return py_object_type
2234
            return fake_index_node.infer_type(env)
2235 2236 2237

    def analyse_types(self, env):
        self.type = self.infer_type(env, self.iterator.type)
William Stein's avatar
William Stein committed
2238
        self.is_temp = 1
2239

William Stein's avatar
William Stein committed
2240
    def generate_result_code(self, code):
Stefan Behnel's avatar
Stefan Behnel committed
2241
        self.iterator.generate_iter_next_result_code(self.result(), code)
2242

William Stein's avatar
William Stein committed
2243

2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
class WithExitCallNode(ExprNode):
    # The __exit__() call of a 'with' statement.  Used in both the
    # except and finally clauses.

    # with_stat  WithStatNode                the surrounding 'with' statement
    # args       TupleNode or ResultStatNode the exception info tuple

    subexprs = ['args']

    def analyse_types(self, env):
        self.args.analyse_types(env)
        self.type = PyrexTypes.c_bint_type
        self.is_temp = True

    def generate_result_code(self, code):
        if isinstance(self.args, TupleNode):
            # call only if it was not already called (and decref-cleared)
            code.putln("if (%s) {" % self.with_stat.exit_var)
        result_var = code.funcstate.allocate_temp(py_object_type, manage_ref=False)
        code.putln("%s = PyObject_Call(%s, %s, NULL);" % (
            result_var,
            self.with_stat.exit_var,
            self.args.result()))
        code.put_decref_clear(self.with_stat.exit_var, type=py_object_type)
        code.putln(code.error_goto_if_null(result_var, self.pos))
        code.put_gotref(result_var)
        code.putln("%s = __Pyx_PyObject_IsTrue(%s);" % (self.result(), result_var))
        code.put_decref_clear(result_var, type=py_object_type)
        code.putln(code.error_goto_if_neg(self.result(), self.pos))
        code.funcstate.release_temp(result_var)
        if isinstance(self.args, TupleNode):
            code.putln("}")


2278
class ExcValueNode(AtomicExprNode):
William Stein's avatar
William Stein committed
2279 2280 2281
    #  Node created during analyse_types phase
    #  of an ExceptClauseNode to fetch the current
    #  exception value.
2282

2283
    type = py_object_type
2284

2285
    def __init__(self, pos, env):
William Stein's avatar
William Stein committed
2286
        ExprNode.__init__(self, pos)
2287 2288

    def set_var(self, var):
2289
        self.var = var
2290

2291 2292 2293
    def calculate_result_code(self):
        return self.var

William Stein's avatar
William Stein committed
2294
    def generate_result_code(self, code):
2295
        pass
William Stein's avatar
William Stein committed
2296

2297 2298 2299
    def analyse_types(self, env):
        pass

William Stein's avatar
William Stein committed
2300

2301
class TempNode(ExprNode):
2302 2303 2304 2305 2306 2307 2308
    # Node created during analyse_types phase
    # of some nodes to hold a temporary value.
    #
    # Note: One must call "allocate" and "release" on
    # the node during code generation to get/release the temp.
    # This is because the temp result is often used outside of
    # the regular cycle.
2309 2310

    subexprs = []
2311

2312
    def __init__(self, pos, type, env=None):
William Stein's avatar
William Stein committed
2313 2314 2315 2316 2317
        ExprNode.__init__(self, pos)
        self.type = type
        if type.is_pyobject:
            self.result_ctype = py_object_type
        self.is_temp = 1
2318

2319 2320
    def analyse_types(self, env):
        return self.type
2321

2322 2323 2324
    def analyse_target_declaration(self, env):
        pass

William Stein's avatar
William Stein committed
2325 2326 2327
    def generate_result_code(self, code):
        pass

2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
    def allocate(self, code):
        self.temp_cname = code.funcstate.allocate_temp(self.type, manage_ref=True)

    def release(self, code):
        code.funcstate.release_temp(self.temp_cname)
        self.temp_cname = None

    def result(self):
        try:
            return self.temp_cname
        except:
            assert False, "Remember to call allocate/release on TempNode"
            raise

    # Do not participate in normal temp alloc/dealloc:
    def allocate_temp_result(self, code):
        pass
2345

2346 2347
    def release_temp_result(self, code):
        pass
William Stein's avatar
William Stein committed
2348 2349 2350

class PyTempNode(TempNode):
    #  TempNode holding a Python value.
2351

William Stein's avatar
William Stein committed
2352 2353 2354
    def __init__(self, pos, env):
        TempNode.__init__(self, pos, PyrexTypes.py_object_type, env)

2355 2356
class RawCNameExprNode(ExprNode):
    subexprs = []
2357

2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
    def __init__(self, pos, type=None):
        self.pos = pos
        self.type = type

    def analyse_types(self, env):
        return self.type

    def set_cname(self, cname):
        self.cname = cname

    def result(self):
        return self.cname

    def generate_result_code(self, code):
        pass

William Stein's avatar
William Stein committed
2374

Mark Florisson's avatar
Mark Florisson committed
2375 2376 2377 2378 2379 2380 2381 2382
#-------------------------------------------------------------------
#
#  Parallel nodes (cython.parallel.thread(savailable|id))
#
#-------------------------------------------------------------------

class ParallelThreadsAvailableNode(AtomicExprNode):
    """
Mark Florisson's avatar
Mark Florisson committed
2383 2384
    Note: this is disabled and not a valid directive at this moment

Mark Florisson's avatar
Mark Florisson committed
2385 2386 2387 2388 2389 2390 2391 2392 2393
    Implements cython.parallel.threadsavailable(). If we are called from the
    sequential part of the application, we need to call omp_get_max_threads(),
    and in the parallel part we can just call omp_get_num_threads()
    """

    type = PyrexTypes.c_int_type

    def analyse_types(self, env):
        self.is_temp = True
2394
        # env.add_include_file("omp.h")
Mark Florisson's avatar
Mark Florisson committed
2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
        return self.type

    def generate_result_code(self, code):
        code.putln("#ifdef _OPENMP")
        code.putln("if (omp_in_parallel()) %s = omp_get_max_threads();" %
                                                            self.temp_code)
        code.putln("else %s = omp_get_num_threads();" % self.temp_code)
        code.putln("#else")
        code.putln("%s = 1;" % self.temp_code)
        code.putln("#endif")

    def result(self):
        return self.temp_code


class ParallelThreadIdNode(AtomicExprNode): #, Nodes.ParallelNode):
    """
    Implements cython.parallel.threadid()
    """

    type = PyrexTypes.c_int_type

    def analyse_types(self, env):
        self.is_temp = True
2419
        # env.add_include_file("omp.h")
Mark Florisson's avatar
Mark Florisson committed
2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
        return self.type

    def generate_result_code(self, code):
        code.putln("#ifdef _OPENMP")
        code.putln("%s = omp_get_thread_num();" % self.temp_code)
        code.putln("#else")
        code.putln("%s = 0;" % self.temp_code)
        code.putln("#endif")

    def result(self):
        return self.temp_code


William Stein's avatar
William Stein committed
2433 2434 2435 2436 2437 2438
#-------------------------------------------------------------------
#
#  Trailer nodes
#
#-------------------------------------------------------------------

2439
class IndexNode(ExprNode):
William Stein's avatar
William Stein committed
2440 2441 2442 2443
    #  Sequence indexing.
    #
    #  base     ExprNode
    #  index    ExprNode
2444 2445 2446 2447 2448 2449
    #  indices  [ExprNode]
    #  is_buffer_access boolean Whether this is a buffer access.
    #
    #  indices is used on buffer access, index on non-buffer access.
    #  The former contains a clean list of index parameters, the
    #  latter whatever Python object is needed for index access.
2450 2451 2452
    #
    #  is_fused_index boolean   Whether the index is used to specialize a
    #                           c(p)def function
2453

2454 2455 2456
    subexprs = ['base', 'index', 'indices']
    indices = None

2457 2458
    is_fused_index = False

2459 2460 2461 2462
    # Whether we're assigning to a buffer (in that case it needs to be
    # writable)
    writable_needed = False

2463 2464 2465
    # Whether we are indexing or slicing a memoryviewslice
    memslice_index = False
    memslice_slice = False
2466 2467
    is_memslice_copy = False
    memslice_ellipsis_noop = False
2468
    warned_untyped_idx = False
2469 2470
    # set by SingleAssignmentNode after analyse_types()
    is_memslice_scalar_assignment = False
2471

2472 2473 2474
    def __init__(self, pos, index, *args, **kw):
        ExprNode.__init__(self, pos, index=index, *args, **kw)
        self._index = index
2475 2476 2477 2478 2479

    def calculate_constant_result(self):
        self.constant_result = \
            self.base.constant_result[self.index.constant_result]

2480 2481 2482 2483 2484 2485 2486
    def compile_time_value(self, denv):
        base = self.base.compile_time_value(denv)
        index = self.index.compile_time_value(denv)
        try:
            return base[index]
        except Exception, e:
            self.compile_time_value_error(e)
2487

William Stein's avatar
William Stein committed
2488 2489
    def is_ephemeral(self):
        return self.base.is_ephemeral()
2490

2491
    def is_simple(self):
2492
        if self.is_buffer_access or self.memslice_index:
2493
            return False
2494 2495 2496
        elif self.memslice_slice:
            return True

2497 2498 2499 2500
        base = self.base
        return (base.is_simple() and self.index.is_simple()
                and base.type and (base.type.is_ptr or base.type.is_array))

William Stein's avatar
William Stein committed
2501 2502
    def analyse_target_declaration(self, env):
        pass
2503

2504 2505 2506
    def analyse_as_type(self, env):
        base_type = self.base.analyse_as_type(env)
        if base_type and not base_type.is_pyobject:
2507
            if base_type.is_cpp_class:
2508
                if isinstance(self.index, TupleNode):
2509 2510 2511 2512 2513
                    template_values = self.index.args
                else:
                    template_values = [self.index]
                import Nodes
                type_node = Nodes.TemplatedTypeNode(
2514 2515
                    pos = self.pos,
                    positional_args = template_values,
2516 2517 2518 2519
                    keyword_args = None)
                return type_node.analyse(env, base_type = base_type)
            else:
                return PyrexTypes.CArrayType(base_type, int(self.index.compile_time_value(env)))
2520
        return None
2521

Robert Bradshaw's avatar
Robert Bradshaw committed
2522
    def type_dependencies(self, env):
2523
        return self.base.type_dependencies(env) + self.index.type_dependencies(env)
2524

2525
    def infer_type(self, env):
2526 2527 2528 2529
        base_type = self.base.infer_type(env)
        if isinstance(self.index, SliceNode):
            # slicing!
            if base_type.is_string:
2530
                # sliced C strings must coerce to Python
2531
                return bytes_type
2532 2533 2534
            elif base_type in (unicode_type, bytes_type, str_type, list_type, tuple_type):
                # slicing these returns the same type
                return base_type
2535
            else:
2536 2537 2538
                # TODO: Handle buffers (hopefully without too much redundancy).
                return py_object_type

2539 2540
        index_type = self.index.infer_type(env)
        if index_type and index_type.is_int or isinstance(self.index, (IntNode, LongNode)):
2541 2542
            # indexing!
            if base_type is unicode_type:
2543 2544 2545
                # Py_UCS4 will automatically coerce to a unicode string
                # if required, so this is safe.  We only infer Py_UCS4
                # when the index is a C integer type.  Otherwise, we may
2546 2547 2548 2549
                # need to use normal Python item access, in which case
                # it's faster to return the one-char unicode string than
                # to receive it, throw it away, and potentially rebuild it
                # on a subsequent PyObject coercion.
2550
                return PyrexTypes.c_py_ucs4_type
2551 2552 2553
            elif base_type is str_type:
                # always returns str - Py2: bytes, Py3: unicode
                return base_type
2554 2555 2556 2557 2558 2559
            elif isinstance(self.base, BytesNode):
                #if env.global_scope().context.language_level >= 3:
                #    # infering 'char' can be made to work in Python 3 mode
                #    return PyrexTypes.c_char_type
                # Py2/3 return different types on indexing bytes objects
                return py_object_type
2560 2561
            elif base_type.is_ptr or base_type.is_array:
                return base_type.base_type
2562

2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
        if base_type.is_cpp_class:
            class FakeOperand:
                def __init__(self, **kwds):
                    self.__dict__.update(kwds)
            operands = [
                FakeOperand(pos=self.pos, type=base_type),
                FakeOperand(pos=self.pos, type=index_type),
            ]
            index_func = env.lookup_operator('[]', operands)
            if index_func is not None:
                return index_func.type.base_type.return_type

2575
        # may be slicing or indexing, we don't know
2576 2577
        if base_type in (unicode_type, str_type):
            # these types always returns their own type on Python indexing/slicing
2578
            return base_type
2579 2580 2581
        else:
            # TODO: Handle buffers (hopefully without too much redundancy).
            return py_object_type
2582

William Stein's avatar
William Stein committed
2583
    def analyse_types(self, env):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
2584
        self.analyse_base_and_index_types(env, getting = 1)
2585

Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
2586 2587
    def analyse_target_types(self, env):
        self.analyse_base_and_index_types(env, setting = 1)
2588 2589
        if not self.is_lvalue():
            error(self.pos, "Assignment to non-lvalue of type '%s'" % self.type)
2590

2591
    def analyse_base_and_index_types(self, env, getting = 0, setting = 0, analyse_base = True):
2592 2593 2594
        # Note: This might be cleaned up by having IndexNode
        # parsed in a saner way and only construct the tuple if
        # needed.
2595 2596 2597 2598

        # Note that this function must leave IndexNode in a cloneable state.
        # For buffers, self.index is packed out on the initial analysis, and
        # when cloning self.indices is copied.
2599 2600
        self.is_buffer_access = False

2601
        # a[...] = b
2602
        self.is_memslice_copy = False
2603 2604 2605 2606
        # incomplete indexing, Ellipsis indexing or slicing
        self.memslice_slice = False
        # integer indexing
        self.memslice_index = False
2607

2608 2609 2610
        if analyse_base:
            self.base.analyse_types(env)

2611 2612 2613 2614 2615
        if self.base.type.is_error:
            # Do not visit child tree if base is undeclared to avoid confusing
            # error messages
            self.type = PyrexTypes.error_type
            return
2616

2617
        is_slice = isinstance(self.index, SliceNode)
2618

2619
        # Potentially overflowing index value.
2620
        if not is_slice and isinstance(self.index, IntNode) and Utils.long_literal(self.index.value):
2621
            self.index = self.index.coerce_to_pyobject(env)
2622

2623 2624
        is_memslice = self.base.type.is_memoryviewslice

2625
        # Handle the case where base is a literal char* (and we expect a string, not an int)
2626
        if not is_memslice and (isinstance(self.base, BytesNode) or is_slice):
Robert Bradshaw's avatar
Robert Bradshaw committed
2627
            if self.base.type.is_string or not (self.base.type.is_ptr or self.base.type.is_array):
2628
                self.base = self.base.coerce_to_pyobject(env)
2629 2630 2631

        skip_child_analysis = False
        buffer_access = False
Mark Florisson's avatar
Mark Florisson committed
2632

2633 2634 2635 2636 2637 2638 2639
        if self.indices:
            indices = self.indices
        elif isinstance(self.index, TupleNode):
            indices = self.index.args
        else:
            indices = [self.index]

2640
        if (is_memslice and not self.indices and
Mark Florisson's avatar
Mark Florisson committed
2641
                isinstance(self.index, EllipsisNode)):
2642
            # Memoryviewslice copying
2643
            self.is_memslice_copy = True
2644 2645 2646 2647 2648 2649

        elif is_memslice:
            # memoryviewslice indexing or slicing
            import MemoryView

            skip_child_analysis = True
2650
            newaxes = [newaxis for newaxis in indices if newaxis.is_none]
2651
            have_slices, indices = MemoryView.unellipsify(indices,
2652
                                                          newaxes,
2653
                                                          self.base.type.ndim)
2654 2655 2656

            self.memslice_index = (not newaxes and
                                   len(indices) == self.base.type.ndim)
2657 2658 2659 2660 2661
            axes = []

            index_type = PyrexTypes.c_py_ssize_t_type
            new_indices = []

2662
            if len(indices) - len(newaxes) > self.base.type.ndim:
2663 2664 2665 2666 2667
                self.type = error_type
                return error(indices[self.base.type.ndim].pos,
                             "Too many indices specified for type %s" %
                                                        self.base.type)

2668
            axis_idx = 0
2669 2670
            for i, index in enumerate(indices[:]):
                index.analyse_types(env)
2671 2672 2673 2674
                if not index.is_none:
                    access, packing = self.base.type.axes[axis_idx]
                    axis_idx += 1

2675 2676
                if isinstance(index, SliceNode):
                    self.memslice_slice = True
2677 2678
                    if index.step.is_none:
                        axes.append((access, packing))
2679 2680
                    else:
                        axes.append((access, 'strided'))
2681 2682 2683 2684 2685 2686

                    # Coerce start, stop and step to temps of the right type
                    for attr in ('start', 'stop', 'step'):
                        value = getattr(index, attr)
                        if not value.is_none:
                            value = value.coerce_to(index_type, env)
2687
                            #value = value.coerce_to_temp(env)
2688 2689 2690
                            setattr(index, attr, value)
                            new_indices.append(value)

2691 2692 2693 2694 2695
                elif index.is_none:
                    self.memslice_slice = True
                    new_indices.append(index)
                    axes.append(('direct', 'strided'))

2696 2697 2698 2699 2700
                elif index.type.is_int or index.type.is_pyobject:
                    if index.type.is_pyobject and not self.warned_untyped_idx:
                        warning(index.pos, "Index should be typed for more "
                                           "efficient access", level=2)
                        IndexNode.warned_untyped_idx = True
2701

2702
                    self.memslice_index = True
2703
                    index = index.coerce_to(index_type, env)
2704 2705 2706
                    indices[i] = index
                    new_indices.append(index)

2707
                else:
2708 2709
                    self.type = error_type
                    return error(index.pos, "Invalid index for memoryview specified")
2710

2711 2712
            self.memslice_index = self.memslice_index and not self.memslice_slice
            self.original_indices = indices
2713 2714
            # All indices with all start/stop/step for slices.
            # We need to keep this around
2715
            self.indices = new_indices
2716 2717
            self.env = env

2718 2719
        elif self.base.type.is_buffer:
            # Buffer indexing
2720
            if len(indices) == self.base.type.ndim:
2721 2722 2723 2724 2725 2726
                buffer_access = True
                skip_child_analysis = True
                for x in indices:
                    x.analyse_types(env)
                    if not x.type.is_int:
                        buffer_access = False
2727

2728
            if buffer_access and not self.base.type.is_memoryviewslice:
Robert Bradshaw's avatar
Robert Bradshaw committed
2729
                assert hasattr(self.base, "entry") # Must be a NameNode-like node
2730

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2731 2732 2733
        # On cloning, indices is cloned. Otherwise, unpack index into indices
        assert not (buffer_access and isinstance(self.index, CloneNode))

2734 2735
        self.nogil = env.nogil

2736
        if buffer_access or self.memslice_index:
2737 2738 2739
            #if self.base.type.is_memoryviewslice and not self.base.is_name:
            #    self.base = self.base.coerce_to_temp(env)
            self.base = self.base.coerce_to_simple(env)
2740

2741
            self.indices = indices
2742
            self.index = None
2743 2744
            self.type = self.base.type.dtype
            self.is_buffer_access = True
2745
            self.buffer_type = self.base.type #self.base.entry.type
2746 2747

            if getting and self.type.is_pyobject:
2748
                self.is_temp = True
2749 2750

            if setting and self.base.type.is_memoryviewslice:
2751
                self.base.type.writable_needed = True
2752
            elif setting:
2753 2754 2755
                if not self.base.entry.type.writable:
                    error(self.pos, "Writing to readonly buffer")
                else:
2756
                    self.writable_needed = True
2757
                    if self.base.type.is_buffer:
2758
                        self.base.entry.buffer_aux.writable_needed = True
2759

2760
        elif self.is_memslice_copy:
Mark Florisson's avatar
Mark Florisson committed
2761 2762
            self.type = self.base.type
            if getting:
2763 2764 2765
                self.memslice_ellipsis_noop = True
            else:
                self.memslice_broadcast = True
2766

2767
        elif self.memslice_slice:
2768
            self.index = None
2769
            self.is_temp = True
2770
            self.use_managed_ref = True
2771 2772 2773 2774 2775

            if not MemoryView.validate_axes(self.pos, axes):
                self.type = error_type
                return

2776 2777
            self.type = PyrexTypes.MemoryViewSliceType(
                            self.base.type.dtype, axes)
2778 2779 2780 2781 2782 2783

            if (self.base.type.is_memoryviewslice and not
                    self.base.is_name and not
                    self.base.result_in_temp()):
                self.base = self.base.coerce_to_temp(env)

2784 2785
            if setting:
                self.memslice_broadcast = True
2786

2787
        else:
2788
            base_type = self.base.type
2789 2790 2791 2792 2793 2794 2795 2796 2797

            fused_index_operation = base_type.is_cfunction and base_type.is_fused
            if not fused_index_operation:
                if isinstance(self.index, TupleNode):
                    self.index.analyse_types(env, skip_children=skip_child_analysis)
                elif not skip_child_analysis:
                    self.index.analyse_types(env)
                self.original_index_type = self.index.type

Stefan Behnel's avatar
Stefan Behnel committed
2798 2799
            if base_type.is_unicode_char:
                # we infer Py_UNICODE/Py_UCS4 for unicode strings in some
2800 2801 2802 2803 2804 2805 2806
                # cases, but indexing must still work for them
                if self.index.constant_result in (0, -1):
                    # FIXME: we know that this node is redundant -
                    # currently, this needs to get handled in Optimize.py
                    pass
                self.base = self.base.coerce_to_pyobject(env)
                base_type = self.base.type
2807
            if base_type.is_pyobject:
2808
                if self.index.type.is_int:
2809
                    if (not setting
2810
                        and (base_type in (list_type, tuple_type))
2811 2812
                        and (not self.index.type.signed
                             or not env.directives['wraparound']
2813 2814
                             or (isinstance(self.index, IntNode) and
                                 self.index.has_constant_result() and self.index.constant_result >= 0))
2815 2816 2817 2818
                        and not env.directives['boundscheck']):
                        self.is_temp = 0
                    else:
                        self.is_temp = 1
2819 2820 2821
                    self.index = self.index.coerce_to(PyrexTypes.c_py_ssize_t_type, env).coerce_to_simple(env)
                else:
                    self.index = self.index.coerce_to_pyobject(env)
2822
                    self.is_temp = 1
2823
                if self.index.type.is_int and base_type is unicode_type:
Stefan Behnel's avatar
Stefan Behnel committed
2824
                    # Py_UNICODE/Py_UCS4 will automatically coerce to a unicode string
2825
                    # if required, so this is fast and safe
2826
                    self.type = PyrexTypes.c_py_ucs4_type
2827 2828
                elif is_slice and base_type in (bytes_type, str_type, unicode_type, list_type, tuple_type):
                    self.type = base_type
2829
                else:
2830 2831 2832
                    if base_type in (list_type, tuple_type, dict_type):
                        # do the None check explicitly (not in a helper) to allow optimising it away
                        self.base = self.base.as_none_safe_node("'NoneType' object is not subscriptable")
2833
                    self.type = py_object_type
William Stein's avatar
William Stein committed
2834
            else:
2835 2836
                if base_type.is_ptr or base_type.is_array:
                    self.type = base_type.base_type
2837 2838 2839
                    if is_slice:
                        self.type = base_type
                    elif self.index.type.is_pyobject:
Robert Bradshaw's avatar
Robert Bradshaw committed
2840 2841
                        self.index = self.index.coerce_to(
                            PyrexTypes.c_py_ssize_t_type, env)
2842
                    elif not self.index.type.is_int:
Robert Bradshaw's avatar
Robert Bradshaw committed
2843 2844 2845
                        error(self.pos,
                            "Invalid index type '%s'" %
                                self.index.type)
2846
                elif base_type.is_cpp_class:
2847
                    function = env.lookup_operator("[]", [self.base, self.index])
Robert Bradshaw's avatar
Robert Bradshaw committed
2848
                    if function is None:
2849
                        error(self.pos, "Indexing '%s' not supported for index type '%s'" % (base_type, self.index.type))
Robert Bradshaw's avatar
Robert Bradshaw committed
2850 2851 2852 2853 2854 2855 2856 2857 2858
                        self.type = PyrexTypes.error_type
                        self.result_code = "<error>"
                        return
                    func_type = function.type
                    if func_type.is_ptr:
                        func_type = func_type.base_type
                    self.index = self.index.coerce_to(func_type.args[0].type, env)
                    self.type = func_type.return_type
                    if setting and not func_type.return_type.is_reference:
Robert Bradshaw's avatar
Robert Bradshaw committed
2859
                        error(self.pos, "Can't set non-reference result '%s'" % self.type)
2860 2861
                elif fused_index_operation:
                    self.parse_indexed_fused_cdef(env)
2862 2863 2864
                else:
                    error(self.pos,
                        "Attempting to index non-array type '%s'" %
2865
                            base_type)
2866
                    self.type = PyrexTypes.error_type
Stefan Behnel's avatar
Stefan Behnel committed
2867

2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
        self.wrap_in_nonecheck_node(env, getting)

    def wrap_in_nonecheck_node(self, env, getting):
        if not env.directives['nonecheck'] or not self.base.may_be_none():
            return

        if self.base.type.is_memoryviewslice:
            if self.is_memslice_copy and not getting:
                msg = "Cannot assign to None memoryview slice"
            elif self.memslice_slice:
                msg = "Cannot slice None memoryview slice"
            else:
                msg = "Cannot index None memoryview slice"
        else:
            msg = "'NoneType' object is not subscriptable"

        self.base = self.base.as_none_safe_node(msg)

2886 2887 2888 2889 2890 2891 2892 2893 2894
    def parse_indexed_fused_cdef(self, env):
        """
        Interpret fused_cdef_func[specific_type1, ...]

        Note that if this method is called, we are an indexed cdef function
        with fused argument types, and this IndexNode will be replaced by the
        NameNode with specific entry just after analysis of expressions by
        AnalyseExpressionsTransform.
        """
2895
        self.type = PyrexTypes.error_type
2896

2897 2898
        self.is_fused_index = True

Mark Florisson's avatar
Mark Florisson committed
2899
        base_type = self.base.type
2900 2901 2902
        specific_types = []
        positions = []

2903
        if self.index.is_name or self.index.is_attribute:
2904 2905 2906 2907 2908
            positions.append(self.index.pos)
            specific_types.append(self.index.analyse_as_type(env))
        elif isinstance(self.index, TupleNode):
            for arg in self.index.args:
                positions.append(arg.pos)
2909 2910
                specific_type = arg.analyse_as_type(env)
                specific_types.append(specific_type)
2911
        else:
2912
            specific_types = [False]
2913

2914 2915 2916 2917
        if not Utils.all(specific_types):
            self.index.analyse_types(env)

            if not self.base.entry.as_variable:
2918
                error(self.pos, "Can only index fused functions with types")
2919 2920
            else:
                # A cpdef function indexed with Python objects
2921 2922
                self.base.entry = self.entry = self.base.entry.as_variable
                self.base.type = self.type = self.entry.type
2923

2924 2925 2926 2927 2928 2929
                self.base.is_temp = True
                self.is_temp = True

                self.entry.used = True

            self.is_fused_index = False
2930 2931
            return

Mark Florisson's avatar
Mark Florisson committed
2932 2933 2934
        for i, type in enumerate(specific_types):
            specific_types[i] = type.specialize_fused(env)

2935 2936
        fused_types = base_type.get_fused_types()
        if len(specific_types) > len(fused_types):
2937 2938 2939 2940 2941
            return error(self.pos, "Too many types specified")
        elif len(specific_types) < len(fused_types):
            t = fused_types[len(specific_types)]
            return error(self.pos, "Not enough types specified to specialize "
                                   "the function, %s is still fused" % t)
2942 2943 2944 2945 2946 2947 2948

        # See if our index types form valid specializations
        for pos, specific_type, fused_type in zip(positions,
                                                  specific_types,
                                                  fused_types):
            if not Utils.any([specific_type.same_as(t)
                                  for t in fused_type.types]):
2949
                return error(pos, "Type not in fused type")
2950 2951 2952 2953 2954 2955 2956

            if specific_type is None or specific_type.is_error:
                return

        fused_to_specific = dict(zip(fused_types, specific_types))
        type = base_type.specialize(fused_to_specific)

2957 2958 2959 2960 2961
        if type.is_fused:
            # Only partially specific, this is invalid
            error(self.pos,
                  "Index operation makes function only partially specific")
        else:
2962
            # Fully specific, find the signature with the specialized entry
2963
            for signature in self.base.type.get_all_specialized_function_types():
2964 2965
                if type.same_as(signature):
                    self.type = signature
Mark Florisson's avatar
Mark Florisson committed
2966 2967 2968 2969 2970

                    if self.base.is_attribute:
                        # Pretend to be a normal attribute, for cdef extension
                        # methods
                        self.entry = signature.entry
2971
                        self.is_attribute = True
Mark Florisson's avatar
Mark Florisson committed
2972
                        self.obj = self.base.obj
2973 2974 2975 2976

                    self.type.entry.used = True
                    self.base.type = signature
                    self.base.entry = signature.entry
Mark Florisson's avatar
Mark Florisson committed
2977

2978 2979
                    break
            else:
Mark Florisson's avatar
Mark Florisson committed
2980 2981
                # This is a bug
                raise InternalError("Couldn't find the right signature")
2982

2983 2984
    gil_message = "Indexing Python object"

2985
    def nogil_check(self, env):
2986 2987
        if self.is_buffer_access or self.memslice_index or self.memslice_slice:
            if not self.memslice_slice and env.directives['boundscheck']:
2988 2989 2990 2991 2992
                # error(self.pos, "Cannot check buffer index bounds without gil; "
                #                 "use boundscheck(False) directive")
                warning(self.pos, "Use boundscheck(False) for faster access",
                        level=1)
            if self.type.is_pyobject:
2993 2994
                error(self.pos, "Cannot access buffer with object dtype without gil")
                return
2995
        super(IndexNode, self).nogil_check(env)
2996 2997


William Stein's avatar
William Stein committed
2998
    def check_const_addr(self):
2999
        return self.base.check_const_addr() and self.index.check_const()
3000

William Stein's avatar
William Stein committed
3001
    def is_lvalue(self):
3002 3003 3004 3005 3006
        base_type = self.base.type
        if self.type.is_ptr or self.type.is_array:
            return not base_type.base_type.is_array
        else:
            return True
Dag Sverre Seljebotn's avatar
merge  
Dag Sverre Seljebotn committed
3007

William Stein's avatar
William Stein committed
3008
    def calculate_result_code(self):
3009
        if self.is_buffer_access:
3010
            return "(*%s)" % self.buffer_ptr_code
3011 3012
        elif self.is_memslice_copy:
            return self.base.result()
3013 3014 3015 3016
        elif self.base.type is list_type:
            return "PyList_GET_ITEM(%s, %s)" % (self.base.result(), self.index.result())
        elif self.base.type is tuple_type:
            return "PyTuple_GET_ITEM(%s, %s)" % (self.base.result(), self.index.result())
3017 3018
        elif (self.type.is_ptr or self.type.is_array) and self.type == self.base.type:
            error(self.pos, "Invalid use of pointer slice")
3019 3020
        else:
            return "(%s[%s])" % (
3021
                self.base.result(), self.index.result())
3022

3023
    def extra_index_params(self):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3024 3025
        if self.index.type.is_int:
            if self.original_index_type.signed:
3026
                size_adjustment = ""
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3027
            else:
3028 3029
                size_adjustment = "+1"
            return ", sizeof(%s)%s, %s" % (self.original_index_type.declaration_code(""), size_adjustment, self.original_index_type.to_py_function)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3030 3031
        else:
            return ""
3032 3033 3034

    def generate_subexpr_evaluation_code(self, code):
        self.base.generate_evaluation_code(code)
3035
        if self.indices is None:
3036 3037
            self.index.generate_evaluation_code(code)
        else:
3038 3039
            for i in self.indices:
                i.generate_evaluation_code(code)
3040

3041 3042
    def generate_subexpr_disposal_code(self, code):
        self.base.generate_disposal_code(code)
3043
        if self.indices is None:
3044 3045
            self.index.generate_disposal_code(code)
        else:
3046 3047
            for i in self.indices:
                i.generate_disposal_code(code)
3048

3049 3050
    def free_subexpr_temps(self, code):
        self.base.free_temps(code)
3051
        if self.indices is None:
3052 3053 3054 3055 3056
            self.index.free_temps(code)
        else:
            for i in self.indices:
                i.free_temps(code)

William Stein's avatar
William Stein committed
3057
    def generate_result_code(self, code):
3058
        if self.is_buffer_access or self.memslice_index:
3059
            buffer_entry, self.buffer_ptr_code = self.buffer_lookup_code(code)
3060 3061 3062
            if self.type.is_pyobject:
                # is_temp is True, so must pull out value and incref it.
                code.putln("%s = *%s;" % (self.result(), self.buffer_ptr_code))
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
3063
                code.putln("__Pyx_INCREF((PyObject*)%s);" % self.result())
3064 3065 3066 3067

        elif self.memslice_slice:
            self.put_memoryviewslice_slice_code(code)

3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
        elif self.is_temp:
            if self.type.is_pyobject:
                if self.index.type.is_int:
                    index_code = self.index.result()
                    if self.base.type is list_type:
                        function = "__Pyx_GetItemInt_List"
                    elif self.base.type is tuple_type:
                        function = "__Pyx_GetItemInt_Tuple"
                    else:
                        function = "__Pyx_GetItemInt"
3078 3079
                    code.globalstate.use_utility_code(
                        TempitaUtilityCode.load_cached("GetItemInt", "ObjectHandling.c"))
3080
                else:
3081 3082 3083
                    index_code = self.index.py_result()
                    if self.base.type is dict_type:
                        function = "__Pyx_PyDict_GetItem"
3084 3085
                        code.globalstate.use_utility_code(
                            UtilityCode.load_cached("DictGetItem", "ObjectHandling.c"))
3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
                    else:
                        function = "PyObject_GetItem"
                code.putln(
                    "%s = %s(%s, %s%s); if (!%s) %s" % (
                        self.result(),
                        function,
                        self.base.py_result(),
                        index_code,
                        self.extra_index_params(),
                        self.result(),
                        code.error_goto(self.pos)))
                code.put_gotref(self.py_result())
Stefan Behnel's avatar
Stefan Behnel committed
3098
            elif self.type.is_unicode_char and self.base.type is unicode_type:
3099 3100 3101
                assert self.index.type.is_int
                index_code = self.index.result()
                function = "__Pyx_GetItemInt_Unicode"
3102 3103
                code.globalstate.use_utility_code(getitem_int_pyunicode_utility_code)
                code.putln(
3104
                    "%s = %s(%s, %s%s); if (unlikely(%s == (Py_UCS4)-1)) %s;" % (
3105 3106 3107 3108 3109 3110 3111
                        self.result(),
                        function,
                        self.base.py_result(),
                        index_code,
                        self.extra_index_params(),
                        self.result(),
                        code.error_goto(self.pos)))
3112

Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3113 3114 3115
    def generate_setitem_code(self, value_code, code):
        if self.index.type.is_int:
            function = "__Pyx_SetItemInt"
3116
            index_code = self.index.result()
3117 3118
            code.globalstate.use_utility_code(
                UtilityCode.load_cached("SetItemInt", "ObjectHandling.c"))
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3119 3120
        else:
            index_code = self.index.py_result()
3121 3122
            if self.base.type is dict_type:
                function = "PyDict_SetItem"
Craig Citro's avatar
Craig Citro committed
3123
            # It would seem that we could specialized lists/tuples, but that
3124
            # shouldn't happen here.
Stefan Behnel's avatar
Stefan Behnel committed
3125 3126 3127 3128 3129
            # Both PyList_SetItem() and PyTuple_SetItem() take a Py_ssize_t as
            # index instead of an object, and bad conversion here would give
            # the wrong exception. Also, tuples are supposed to be immutable,
            # and raise a TypeError when trying to set their entries
            # (PyTuple_SetItem() is for creating new tuples from scratch).
3130 3131
            else:
                function = "PyObject_SetItem"
3132
        code.putln(
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3133 3134
            "if (%s(%s, %s, %s%s) < 0) %s" % (
                function,
3135
                self.base.py_result(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3136 3137
                index_code,
                value_code,
3138
                self.extra_index_params(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3139
                code.error_goto(self.pos)))
3140 3141 3142

    def generate_buffer_setitem_code(self, rhs, code, op=""):
        # Used from generate_assignment_code and InPlaceAssignmentNode
3143 3144
        buffer_entry, ptrexpr = self.buffer_lookup_code(code)

3145 3146 3147
        if self.buffer_type.dtype.is_pyobject:
            # Must manage refcounts. Decref what is already there
            # and incref what we put in.
3148 3149
            ptr = code.funcstate.allocate_temp(buffer_entry.buf_ptr_type,
                                               manage_ref=False)
3150
            rhs_code = rhs.result()
3151
            code.putln("%s = %s;" % (ptr, ptrexpr))
3152
            code.put_gotref("*%s" % ptr)
3153 3154
            code.putln("__Pyx_INCREF(%s); __Pyx_DECREF(*%s);" % (
                rhs_code, ptr))
3155
            code.putln("*%s %s= %s;" % (ptr, op, rhs_code))
3156
            code.put_giveref("*%s" % ptr)
3157
            code.funcstate.release_temp(ptr)
3158
        else:
3159
            # Simple case
3160
            code.putln("*%s %s= %s;" % (ptrexpr, op, rhs.result()))
3161

William Stein's avatar
William Stein committed
3162
    def generate_assignment_code(self, rhs, code):
3163 3164 3165 3166 3167 3168 3169
        generate_evaluation_code = (self.is_memslice_scalar_assignment or
                                    self.memslice_slice)
        if generate_evaluation_code:
            self.generate_evaluation_code(code)
        else:
            self.generate_subexpr_evaluation_code(code)

3170
        if self.is_buffer_access or self.memslice_index:
3171
            self.generate_buffer_setitem_code(rhs, code)
3172 3173
        elif self.is_memslice_scalar_assignment:
            self.generate_memoryviewslice_assign_scalar_code(rhs, code)
3174
        elif self.memslice_slice or self.is_memslice_copy:
3175
            self.generate_memoryviewslice_setslice_code(rhs, code)
3176
        elif self.type.is_pyobject:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3177
            self.generate_setitem_code(rhs.py_result(), code)
William Stein's avatar
William Stein committed
3178 3179 3180
        else:
            code.putln(
                "%s = %s;" % (
3181
                    self.result(), rhs.result()))
3182 3183 3184 3185 3186 3187 3188

        if generate_evaluation_code:
            self.generate_disposal_code(code)
        else:
            self.generate_subexpr_disposal_code(code)
            self.free_subexpr_temps(code)

William Stein's avatar
William Stein committed
3189
        rhs.generate_disposal_code(code)
3190
        rhs.free_temps(code)
3191

William Stein's avatar
William Stein committed
3192 3193
    def generate_deletion_code(self, code):
        self.generate_subexpr_evaluation_code(code)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3194 3195
        #if self.type.is_pyobject:
        if self.index.type.is_int:
3196
            function = "__Pyx_DelItemInt"
3197
            index_code = self.index.result()
3198 3199
            code.globalstate.use_utility_code(
                UtilityCode.load_cached("DelItemInt", "ObjectHandling.c"))
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3200 3201
        else:
            index_code = self.index.py_result()
3202 3203 3204 3205
            if self.base.type is dict_type:
                function = "PyDict_DelItem"
            else:
                function = "PyObject_DelItem"
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3206
        code.putln(
3207
            "if (%s(%s, %s%s) < 0) %s" % (
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3208
                function,
William Stein's avatar
William Stein committed
3209
                self.base.py_result(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3210
                index_code,
3211
                self.extra_index_params(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3212
                code.error_goto(self.pos)))
William Stein's avatar
William Stein committed
3213
        self.generate_subexpr_disposal_code(code)
3214
        self.free_subexpr_temps(code)
3215

3216 3217 3218
    def buffer_entry(self):
        import Buffer, MemoryView

3219 3220 3221 3222 3223 3224
        base = self.base
        if self.base.is_nonecheck:
            base = base.arg

        if base.is_name:
            entry = base.entry
3225
        else:
3226
            # SimpleCallNode is_simple is not consistent with coerce_to_simple
3227 3228
            assert base.is_simple() or base.is_temp
            cname = base.result()
3229 3230 3231 3232 3233 3234 3235 3236 3237
            entry = Symtab.Entry(cname, cname, self.base.type, self.base.pos)

        if entry.type.is_buffer:
            buffer_entry = Buffer.BufferEntry(entry)
        else:
            buffer_entry = MemoryView.MemoryViewSliceBufferEntry(entry)

        return buffer_entry

3238
    def buffer_lookup_code(self, code):
3239
        "ndarray[1, 2, 3] and memslice[1, 2, 3]"
3240
        # Assign indices to temps
3241 3242 3243
        index_temps = [code.funcstate.allocate_temp(i.type, manage_ref=False)
                           for i in self.indices]

3244
        for temp, index in zip(index_temps, self.indices):
3245
            code.putln("%s = %s;" % (temp, index.result()))
3246

3247
        # Generate buffer access code using these temps
3248
        import Buffer, MemoryView
3249

3250
        buffer_entry = self.buffer_entry()
3251

3252
        if buffer_entry.type.is_buffer:
3253
            negative_indices = buffer_entry.type.negative_indices
3254 3255 3256
        else:
            negative_indices = Buffer.buffer_defaults['negative_indices']

3257 3258 3259 3260 3261 3262
        return buffer_entry, Buffer.put_buffer_lookup_code(
               entry=buffer_entry,
               index_signeds=[i.type.signed for i in self.indices],
               index_cnames=index_temps,
               directives=code.globalstate.directives,
               pos=self.pos, code=code,
3263 3264
               negative_indices=negative_indices,
               in_nogil_context=self.in_nogil_context)
William Stein's avatar
William Stein committed
3265

3266
    def put_memoryviewslice_slice_code(self, code):
3267
        "memslice[:]"
3268
        buffer_entry = self.buffer_entry()
3269
        have_gil = not self.in_nogil_context
3270

3271 3272 3273 3274 3275 3276
        if sys.version_info < (3,):
            def next_(it):
                return it.next()
        else:
            next_ = next

3277 3278 3279 3280 3281 3282 3283
        have_slices = False
        it = iter(self.indices)
        for index in self.original_indices:
            is_slice = isinstance(index, SliceNode)
            have_slices = have_slices or is_slice
            if is_slice:
                if not index.start.is_none:
3284
                    index.start = next_(it)
3285
                if not index.stop.is_none:
3286
                    index.stop = next_(it)
3287
                if not index.step.is_none:
3288
                    index.step = next_(it)
3289
            else:
3290
                next_(it)
3291 3292 3293 3294

        assert not list(it)

        buffer_entry.generate_buffer_slice_code(code, self.original_indices,
3295
                                                self.result(),
3296 3297
                                                have_gil=have_gil,
                                                have_slices=have_slices)
William Stein's avatar
William Stein committed
3298

3299
    def generate_memoryviewslice_setslice_code(self, rhs, code):
3300
        "memslice1[...] = memslice2 or memslice1[:] = memslice2"
3301 3302 3303
        import MemoryView
        MemoryView.copy_broadcast_memview_src_to_dst(rhs, self, code)

3304 3305 3306 3307 3308
    def generate_memoryviewslice_assign_scalar_code(self, rhs, code):
        "memslice1[...] = 0.0 or memslice1[:] = 0.0"
        import MemoryView
        MemoryView.assign_scalar(self, rhs, code)

3309

3310
class SliceIndexNode(ExprNode):
William Stein's avatar
William Stein committed
3311 3312 3313 3314 3315
    #  2-element slice indexing
    #
    #  base      ExprNode
    #  start     ExprNode or None
    #  stop      ExprNode or None
3316

William Stein's avatar
William Stein committed
3317
    subexprs = ['base', 'start', 'stop']
3318

3319 3320 3321 3322 3323 3324 3325
    def infer_type(self, env):
        base_type = self.base.infer_type(env)
        if base_type.is_string:
            return bytes_type
        elif base_type in (bytes_type, str_type, unicode_type,
                           list_type, tuple_type):
            return base_type
3326 3327
        elif base_type.is_ptr or base_type.is_array:
            return PyrexTypes.c_array_type(base_type.base_type, None)
3328 3329
        return py_object_type

3330 3331 3332 3333
    def calculate_constant_result(self):
        self.constant_result = self.base.constant_result[
            self.start.constant_result : self.stop.constant_result]

3334 3335
    def compile_time_value(self, denv):
        base = self.base.compile_time_value(denv)
3336 3337 3338 3339 3340 3341 3342 3343
        if self.start is None:
            start = 0
        else:
            start = self.start.compile_time_value(denv)
        if self.stop is None:
            stop = None
        else:
            stop = self.stop.compile_time_value(denv)
3344 3345 3346 3347
        try:
            return base[start:stop]
        except Exception, e:
            self.compile_time_value_error(e)
3348

William Stein's avatar
William Stein committed
3349 3350
    def analyse_target_declaration(self, env):
        pass
3351

3352
    def analyse_target_types(self, env):
3353
        self.analyse_types(env, getting=False)
3354
        # when assigning, we must accept any Python type
3355 3356
        if self.type.is_pyobject:
            self.type = py_object_type
William Stein's avatar
William Stein committed
3357

3358
    def analyse_types(self, env, getting=True):
William Stein's avatar
William Stein committed
3359
        self.base.analyse_types(env)
3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379

        if self.base.type.is_memoryviewslice:
            # Gross hack here! But we do not know the type until this point,
            # and we cannot create and return a new node. So we change the
            # type...
            none_node = NoneNode(self.pos)
            index = SliceNode(self.pos,
                              start=self.start or none_node,
                              stop=self.stop or none_node,
                              step=none_node)
            del self.start
            del self.stop
            self.index = index
            self.__class__ = IndexNode
            self.analyse_base_and_index_types(env,
                                              getting=getting,
                                              setting=not getting,
                                              analyse_base=False)
            return

William Stein's avatar
William Stein committed
3380 3381 3382 3383
        if self.start:
            self.start.analyse_types(env)
        if self.stop:
            self.stop.analyse_types(env)
3384 3385 3386
        base_type = self.base.type
        if base_type.is_string:
            self.type = bytes_type
3387 3388 3389
        elif base_type.is_ptr:
            self.type = base_type
        elif base_type.is_array:
3390 3391 3392
            # we need a ptr type here instead of an array type, as
            # array types can result in invalid type casts in the C
            # code
3393
            self.type = PyrexTypes.CPtrType(base_type.base_type)
3394 3395 3396
        else:
            self.base = self.base.coerce_to_pyobject(env)
            self.type = py_object_type
3397 3398 3399
        if base_type.is_builtin_type:
            # slicing builtin types returns something of the same type
            self.type = base_type
3400
        c_int = PyrexTypes.c_py_ssize_t_type
William Stein's avatar
William Stein committed
3401 3402 3403 3404 3405
        if self.start:
            self.start = self.start.coerce_to(c_int, env)
        if self.stop:
            self.stop = self.stop.coerce_to(c_int, env)
        self.is_temp = 1
3406

3407
    nogil_check = Node.gil_error
3408 3409
    gil_message = "Slicing Python object"

William Stein's avatar
William Stein committed
3410
    def generate_result_code(self, code):
3411 3412 3413 3414
        if not self.type.is_pyobject:
            error(self.pos,
                  "Slicing is not currently supported for '%s'." % self.type)
            return
Robert Bradshaw's avatar
Robert Bradshaw committed
3415 3416 3417
        if self.base.type.is_string:
            if self.stop is None:
                code.putln(
3418
                    "%s = PyBytes_FromString(%s + %s); %s" % (
Robert Bradshaw's avatar
Robert Bradshaw committed
3419 3420 3421 3422 3423 3424
                        self.result(),
                        self.base.result(),
                        self.start_code(),
                        code.error_goto_if_null(self.result(), self.pos)))
            else:
                code.putln(
3425
                    "%s = PyBytes_FromStringAndSize(%s + %s, %s - %s); %s" % (
Robert Bradshaw's avatar
Robert Bradshaw committed
3426 3427 3428 3429 3430 3431 3432 3433
                        self.result(),
                        self.base.result(),
                        self.start_code(),
                        self.stop_code(),
                        self.start_code(),
                        code.error_goto_if_null(self.result(), self.pos)))
        else:
            code.putln(
3434
                "%s = __Pyx_PySequence_GetSlice(%s, %s, %s); %s" % (
Robert Bradshaw's avatar
Robert Bradshaw committed
3435 3436 3437 3438 3439
                    self.result(),
                    self.base.py_result(),
                    self.start_code(),
                    self.stop_code(),
                    code.error_goto_if_null(self.result(), self.pos)))
3440
        code.put_gotref(self.py_result())
3441

William Stein's avatar
William Stein committed
3442 3443
    def generate_assignment_code(self, rhs, code):
        self.generate_subexpr_evaluation_code(code)
3444
        if self.type.is_pyobject:
3445
            code.put_error_if_neg(self.pos,
3446
                "__Pyx_PySequence_SetSlice(%s, %s, %s, %s)" % (
3447 3448 3449
                    self.base.py_result(),
                    self.start_code(),
                    self.stop_code(),
Lisandro Dalcin's avatar
Lisandro Dalcin committed
3450
                    rhs.py_result()))
3451 3452 3453 3454 3455 3456 3457 3458
        else:
            start_offset = ''
            if self.start:
                start_offset = self.start_code()
                if start_offset == '0':
                    start_offset = ''
                else:
                    start_offset += '+'
Stefan Behnel's avatar
Stefan Behnel committed
3459 3460
            if rhs.type.is_array:
                array_length = rhs.type.size
3461
                self.generate_slice_guard_code(code, array_length)
Stefan Behnel's avatar
Stefan Behnel committed
3462
            else:
Stefan Behnel's avatar
Stefan Behnel committed
3463 3464
                error(self.pos,
                      "Slice assignments from pointers are not yet supported.")
Stefan Behnel's avatar
Stefan Behnel committed
3465 3466
                # FIXME: fix the array size according to start/stop
                array_length = self.base.type.size
3467 3468 3469 3470
            for i in range(array_length):
                code.putln("%s[%s%s] = %s[%d];" % (
                        self.base.result(), start_offset, i,
                        rhs.result(), i))
William Stein's avatar
William Stein committed
3471
        self.generate_subexpr_disposal_code(code)
3472
        self.free_subexpr_temps(code)
William Stein's avatar
William Stein committed
3473
        rhs.generate_disposal_code(code)
3474
        rhs.free_temps(code)
William Stein's avatar
William Stein committed
3475 3476

    def generate_deletion_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
3477
        if not self.base.type.is_pyobject:
3478 3479 3480
            error(self.pos,
                  "Deleting slices is only supported for Python types, not '%s'." % self.type)
            return
William Stein's avatar
William Stein committed
3481
        self.generate_subexpr_evaluation_code(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
3482
        code.put_error_if_neg(self.pos,
3483
            "__Pyx_PySequence_DelSlice(%s, %s, %s)" % (
William Stein's avatar
William Stein committed
3484 3485
                self.base.py_result(),
                self.start_code(),
Robert Bradshaw's avatar
Robert Bradshaw committed
3486
                self.stop_code()))
William Stein's avatar
William Stein committed
3487
        self.generate_subexpr_disposal_code(code)
3488
        self.free_subexpr_temps(code)
3489 3490 3491 3492 3493 3494 3495 3496 3497 3498

    def generate_slice_guard_code(self, code, target_size):
        if not self.base.type.is_array:
            return
        slice_size = self.base.type.size
        start = stop = None
        if self.stop:
            stop = self.stop.result()
            try:
                stop = int(stop)
Stefan Behnel's avatar
Stefan Behnel committed
3499
                if stop < 0:
3500
                    slice_size = self.base.type.size + stop
Stefan Behnel's avatar
Stefan Behnel committed
3501 3502
                else:
                    slice_size = stop
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532
                stop = None
            except ValueError:
                pass
        if self.start:
            start = self.start.result()
            try:
                start = int(start)
                if start < 0:
                    start = self.base.type.size + start
                slice_size -= start
                start = None
            except ValueError:
                pass
        check = None
        if slice_size < 0:
            if target_size > 0:
                error(self.pos, "Assignment to empty slice.")
        elif start is None and stop is None:
            # we know the exact slice length
            if target_size != slice_size:
                error(self.pos, "Assignment to slice of wrong length, expected %d, got %d" % (
                        slice_size, target_size))
        elif start is not None:
            if stop is None:
                stop = slice_size
            check = "(%s)-(%s)" % (stop, start)
        else: # stop is not None:
            check = stop
        if check:
            code.putln("if (unlikely((%s) != %d)) {" % (check, target_size))
3533
            code.putln('PyErr_Format(PyExc_ValueError, "Assignment to slice of wrong length, expected %%" PY_FORMAT_SIZE_T "d, got %%" PY_FORMAT_SIZE_T "d", (Py_ssize_t)%d, (Py_ssize_t)(%s));' % (
3534 3535 3536
                        target_size, check))
            code.putln(code.error_goto(self.pos))
            code.putln("}")
3537

William Stein's avatar
William Stein committed
3538 3539
    def start_code(self):
        if self.start:
3540
            return self.start.result()
William Stein's avatar
William Stein committed
3541 3542
        else:
            return "0"
3543

William Stein's avatar
William Stein committed
3544 3545
    def stop_code(self):
        if self.stop:
3546
            return self.stop.result()
3547 3548
        elif self.base.type.is_array:
            return self.base.type.size
William Stein's avatar
William Stein committed
3549
        else:
3550
            return "PY_SSIZE_T_MAX"
3551

William Stein's avatar
William Stein committed
3552
    def calculate_result_code(self):
3553
        # self.result() is not used, but this method must exist
William Stein's avatar
William Stein committed
3554
        return "<unused>"
3555

William Stein's avatar
William Stein committed
3556

3557
class SliceNode(ExprNode):
William Stein's avatar
William Stein committed
3558 3559 3560 3561 3562
    #  start:stop:step in subscript list
    #
    #  start     ExprNode
    #  stop      ExprNode
    #  step      ExprNode
3563

3564 3565
    subexprs = ['start', 'stop', 'step']

3566 3567
    type = py_object_type
    is_temp = 1
3568 3569

    def calculate_constant_result(self):
3570 3571 3572 3573
        self.constant_result = slice(
            self.start.constant_result,
            self.stop.constant_result,
            self.step.constant_result)
3574

3575 3576
    def compile_time_value(self, denv):
        start = self.start.compile_time_value(denv)
Stefan Behnel's avatar
Stefan Behnel committed
3577 3578
        stop = self.stop.compile_time_value(denv)
        step = self.step.compile_time_value(denv)
3579 3580 3581 3582 3583
        try:
            return slice(start, stop, step)
        except Exception, e:
            self.compile_time_value_error(e)

William Stein's avatar
William Stein committed
3584 3585 3586 3587 3588 3589 3590
    def analyse_types(self, env):
        self.start.analyse_types(env)
        self.stop.analyse_types(env)
        self.step.analyse_types(env)
        self.start = self.start.coerce_to_pyobject(env)
        self.stop = self.stop.coerce_to_pyobject(env)
        self.step = self.step.coerce_to_pyobject(env)
3591 3592 3593
        if self.start.is_literal and self.stop.is_literal and self.step.is_literal:
            self.is_literal = True
            self.is_temp = False
3594 3595 3596

    gil_message = "Constructing Python slice object"

3597 3598 3599
    def calculate_result_code(self):
        return self.result_code

William Stein's avatar
William Stein committed
3600
    def generate_result_code(self, code):
3601 3602 3603 3604 3605
        if self.is_literal:
            self.result_code = code.get_py_const(py_object_type, 'slice_', cleanup_level=2)
            code = code.get_cached_constants_writer()
            code.mark_pos(self.pos)

William Stein's avatar
William Stein committed
3606
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
3607
            "%s = PySlice_New(%s, %s, %s); %s" % (
3608
                self.result(),
3609 3610
                self.start.py_result(),
                self.stop.py_result(),
William Stein's avatar
William Stein committed
3611
                self.step.py_result(),
3612
                code.error_goto_if_null(self.result(), self.pos)))
3613
        code.put_gotref(self.py_result())
3614 3615
        if self.is_literal:
            code.put_giveref(self.py_result())
William Stein's avatar
William Stein committed
3616

3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629
    def __deepcopy__(self, memo):
        """
        There is a copy bug in python 2.4 for slice objects.
        """
        return SliceNode(
            self.pos,
            start=copy.deepcopy(self.start, memo),
            stop=copy.deepcopy(self.stop, memo),
            step=copy.deepcopy(self.step, memo),
            is_temp=self.is_temp,
            is_literal=self.is_literal,
            constant_result=self.constant_result)

3630

3631
class CallNode(ExprNode):
3632

Stefan Behnel's avatar
Stefan Behnel committed
3633 3634 3635
    # allow overriding the default 'may_be_none' behaviour
    may_return_none = None

3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656
    def infer_type(self, env):
        function = self.function
        func_type = function.infer_type(env)
        if isinstance(self.function, NewExprNode):
            return PyrexTypes.CPtrType(self.function.class_type)
        if func_type.is_ptr:
            func_type = func_type.base_type
        if func_type.is_cfunction:
            return func_type.return_type
        elif func_type is type_type:
            if function.is_name and function.entry and function.entry.type:
                result_type = function.entry.type
                if result_type.is_extension_type:
                    return result_type
                elif result_type.is_builtin_type:
                    if function.entry.name == 'float':
                        return PyrexTypes.c_double_type
                    elif function.entry.name in Builtin.types_that_construct_their_instance:
                        return result_type
        return py_object_type

Robert Bradshaw's avatar
Robert Bradshaw committed
3657 3658 3659 3660 3661
    def type_dependencies(self, env):
        # TODO: Update when Danilo's C++ code merged in to handle the
        # the case of function overloading.
        return self.function.type_dependencies(env)

Stefan Behnel's avatar
Stefan Behnel committed
3662 3663 3664 3665 3666
    def may_be_none(self):
        if self.may_return_none is not None:
            return self.may_return_none
        return ExprNode.may_be_none(self)

Robert Bradshaw's avatar
Robert Bradshaw committed
3667 3668 3669 3670 3671 3672
    def analyse_as_type_constructor(self, env):
        type = self.function.analyse_as_type(env)
        if type and type.is_struct_or_union:
            args, kwds = self.explicit_args_kwds()
            items = []
            for arg, member in zip(args, type.scope.var_entries):
3673
                items.append(DictItemNode(pos=arg.pos, key=StringNode(pos=arg.pos, value=member.name), value=arg))
Robert Bradshaw's avatar
Robert Bradshaw committed
3674 3675 3676 3677 3678 3679 3680
            if kwds:
                items += kwds.key_value_pairs
            self.key_value_pairs = items
            self.__class__ = DictNode
            self.analyse_types(env)
            self.coerce_to(type, env)
            return True
3681 3682 3683 3684 3685 3686 3687 3688 3689
        elif type and type.is_cpp_class:
            for arg in self.args:
                arg.analyse_types(env)
            constructor = type.scope.lookup("<init>")
            self.function = RawCNameExprNode(self.function.pos, constructor.type)
            self.function.entry = constructor
            self.function.set_cname(type.declaration_code(""))
            self.analyse_c_function_call(env)
            return True
3690

3691 3692
    def is_lvalue(self):
        return self.type.is_reference
3693

3694
    def nogil_check(self, env):
3695 3696
        func_type = self.function_type()
        if func_type.is_pyobject:
3697
            self.gil_error()
3698
        elif not getattr(func_type, 'nogil', False):
3699
            self.gil_error()
3700 3701 3702

    gil_message = "Calling gil-requiring function"

3703 3704

class SimpleCallNode(CallNode):
William Stein's avatar
William Stein committed
3705 3706 3707 3708 3709 3710 3711
    #  Function call without keyword, * or ** args.
    #
    #  function       ExprNode
    #  args           [ExprNode]
    #  arg_tuple      ExprNode or None     used internally
    #  self           ExprNode or None     used internally
    #  coerced_self   ExprNode or None     used internally
3712
    #  wrapper_call   bool                 used internally
3713
    #  has_optional_args   bool            used internally
3714
    #  nogil          bool                 used internally
3715

William Stein's avatar
William Stein committed
3716
    subexprs = ['self', 'coerced_self', 'function', 'args', 'arg_tuple']
3717

William Stein's avatar
William Stein committed
3718 3719 3720
    self = None
    coerced_self = None
    arg_tuple = None
3721
    wrapper_call = False
3722
    has_optional_args = False
3723
    nogil = False
3724
    analysed = False
3725

3726 3727 3728 3729 3730 3731 3732
    def compile_time_value(self, denv):
        function = self.function.compile_time_value(denv)
        args = [arg.compile_time_value(denv) for arg in self.args]
        try:
            return function(*args)
        except Exception, e:
            self.compile_time_value_error(e)
3733

3734
    def analyse_as_type(self, env):
3735
        attr = self.function.as_cython_attribute()
3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747
        if attr == 'pointer':
            if len(self.args) != 1:
                error(self.args.pos, "only one type allowed.")
            else:
                type = self.args[0].analyse_as_type(env)
                if not type:
                    error(self.args[0].pos, "Unknown type")
                else:
                    return PyrexTypes.CPtrType(type)

    def explicit_args_kwds(self):
        return self.args, None
3748

William Stein's avatar
William Stein committed
3749
    def analyse_types(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
3750 3751
        if self.analyse_as_type_constructor(env):
            return
3752 3753 3754
        if self.analysed:
            return
        self.analysed = True
William Stein's avatar
William Stein committed
3755 3756 3757
        function = self.function
        function.is_called = 1
        self.function.analyse_types(env)
Mark Florisson's avatar
Mark Florisson committed
3758

William Stein's avatar
William Stein committed
3759 3760 3761 3762 3763
        if function.is_attribute and function.entry and function.entry.is_cmethod:
            # Take ownership of the object from which the attribute
            # was obtained, because we need to pass it as 'self'.
            self.self = function.obj
            function.obj = CloneNode(self.self)
Mark Florisson's avatar
Mark Florisson committed
3764

William Stein's avatar
William Stein committed
3765 3766
        func_type = self.function_type()
        if func_type.is_pyobject:
3767 3768
            self.arg_tuple = TupleNode(self.pos, args = self.args)
            self.arg_tuple.analyse_types(env)
William Stein's avatar
William Stein committed
3769
            self.args = None
3770 3771 3772
            if func_type is Builtin.type_type and function.is_name and \
                   function.entry and \
                   function.entry.is_builtin and \
3773 3774 3775 3776 3777 3778 3779 3780 3781
                   function.entry.name in Builtin.types_that_construct_their_instance:
                # calling a builtin type that returns a specific object type
                if function.entry.name == 'float':
                    # the following will come true later on in a transform
                    self.type = PyrexTypes.c_double_type
                    self.result_ctype = PyrexTypes.c_double_type
                else:
                    self.type = Builtin.builtin_types[function.entry.name]
                    self.result_ctype = py_object_type
Stefan Behnel's avatar
Stefan Behnel committed
3782
                self.may_return_none = False
3783
            elif function.is_name and function.type_entry:
3784 3785 3786 3787 3788
                # We are calling an extension type constructor.  As
                # long as we do not support __new__(), the result type
                # is clear
                self.type = function.type_entry.type
                self.result_ctype = py_object_type
Stefan Behnel's avatar
Stefan Behnel committed
3789
                self.may_return_none = False
3790 3791
            else:
                self.type = py_object_type
William Stein's avatar
William Stein committed
3792 3793 3794 3795
            self.is_temp = 1
        else:
            for arg in self.args:
                arg.analyse_types(env)
3796

William Stein's avatar
William Stein committed
3797 3798
            if self.self and func_type.args:
                # Coerce 'self' to the type expected by the method.
3799 3800 3801
                self_arg = func_type.args[0]
                if self_arg.not_none: # C methods must do the None test for self at *call* time
                    self.self = self.self.as_none_safe_node(
3802 3803 3804
                        "'NoneType' object has no attribute '%s'",
                        error = 'PyExc_AttributeError',
                        format_args = [self.function.entry.name])
3805
                expected_type = self_arg.type
Stefan Behnel's avatar
Stefan Behnel committed
3806 3807 3808 3809 3810
                if self_arg.accept_builtin_subtypes:
                    self.coerced_self = CMethodSelfCloneNode(self.self)
                else:
                    self.coerced_self = CloneNode(self.self)
                self.coerced_self = self.coerced_self.coerce_to(expected_type, env)
William Stein's avatar
William Stein committed
3811 3812 3813
                # Insert coerced 'self' argument into argument list.
                self.args.insert(0, self.coerced_self)
            self.analyse_c_function_call(env)
3814

William Stein's avatar
William Stein committed
3815 3816
    def function_type(self):
        # Return the type of the function being called, coercing a function
3817 3818
        # pointer to a function if necessary. If the function has fused
        # arguments, return the specific type.
William Stein's avatar
William Stein committed
3819
        func_type = self.function.type
3820

William Stein's avatar
William Stein committed
3821 3822
        if func_type.is_ptr:
            func_type = func_type.base_type
3823

William Stein's avatar
William Stein committed
3824
        return func_type
3825

3826 3827 3828 3829 3830 3831 3832
    def is_simple(self):
        # C function calls could be considered simple, but they may
        # have side-effects that may hit when multiple operations must
        # be effected in order, e.g. when constructing the argument
        # sequence for a function call or comparing values.
        return False

William Stein's avatar
William Stein committed
3833
    def analyse_c_function_call(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
3834
        if self.function.type is error_type:
3835
            self.type = error_type
Robert Bradshaw's avatar
Robert Bradshaw committed
3836
            return
3837

Robert Bradshaw's avatar
Robert Bradshaw committed
3838
        if self.function.type.is_cpp_class:
3839 3840
            overloaded_entry = self.function.type.scope.lookup("operator()")
            if overloaded_entry is None:
Robert Bradshaw's avatar
Robert Bradshaw committed
3841 3842 3843
                self.type = PyrexTypes.error_type
                self.result_code = "<error>"
                return
3844 3845
        elif hasattr(self.function, 'entry'):
            overloaded_entry = self.function.entry
3846
        elif (isinstance(self.function, IndexNode) and
3847
              self.function.is_fused_index):
3848
            overloaded_entry = self.function.type.entry
Robert Bradshaw's avatar
Robert Bradshaw committed
3849
        else:
3850
            overloaded_entry = None
3851

3852
        if overloaded_entry:
3853
            if self.function.type.is_fused:
3854
                functypes = self.function.type.get_all_specialized_function_types()
Mark Florisson's avatar
Mark Florisson committed
3855
                alternatives = [f.entry for f in functypes]
3856 3857 3858 3859 3860
            else:
                alternatives = overloaded_entry.all_alternatives()

            entry = PyrexTypes.best_match(self.args, alternatives, self.pos, env)

3861 3862 3863 3864
            if not entry:
                self.type = PyrexTypes.error_type
                self.result_code = "<error>"
                return
Mark Florisson's avatar
Mark Florisson committed
3865 3866

            entry.used = True
3867 3868
            self.function.entry = entry
            self.function.type = entry.type
3869 3870 3871 3872 3873 3874 3875 3876
            func_type = self.function_type()
        else:
            func_type = self.function_type()
            if not func_type.is_cfunction:
                error(self.pos, "Calling non-function type '%s'" % func_type)
                self.type = PyrexTypes.error_type
                self.result_code = "<error>"
                return
William Stein's avatar
William Stein committed
3877
        # Check no. of args
3878 3879
        max_nargs = len(func_type.args)
        expected_nargs = max_nargs - func_type.optional_arg_count
William Stein's avatar
William Stein committed
3880
        actual_nargs = len(self.args)
3881 3882 3883
        if func_type.optional_arg_count and expected_nargs != actual_nargs:
            self.has_optional_args = 1
            self.is_temp = 1
William Stein's avatar
William Stein committed
3884
        # Coerce arguments
3885
        some_args_in_temps = False
3886
        for i in xrange(min(max_nargs, actual_nargs)):
William Stein's avatar
William Stein committed
3887
            formal_type = func_type.args[i].type
3888
            arg = self.args[i].coerce_to(formal_type, env)
3889
            if arg.is_temp:
3890 3891
                if i > 0:
                    # first argument in temp doesn't impact subsequent arguments
3892
                    some_args_in_temps = True
3893
            elif arg.type.is_pyobject and not env.nogil:
3894 3895
                if i == 0 and self.self is not None:
                    # a method's cloned "self" argument is ok
3896
                    pass
3897
                elif arg.nonlocally_immutable():
3898 3899 3900
                    # plain local variables are ok
                    pass
                else:
3901 3902 3903 3904
                    # we do not safely own the argument's reference,
                    # but we must make sure it cannot be collected
                    # before we return from the function, so we create
                    # an owned temp reference to it
3905 3906
                    if i > 0: # first argument doesn't matter
                        some_args_in_temps = True
3907
                    arg = arg.coerce_to_temp(env)
3908
            self.args[i] = arg
3909
        # handle additional varargs parameters
3910
        for i in xrange(max_nargs, actual_nargs):
3911 3912 3913 3914 3915 3916 3917
            arg = self.args[i]
            if arg.type.is_pyobject:
                arg_ctype = arg.type.default_coerced_ctype()
                if arg_ctype is None:
                    error(self.args[i].pos,
                          "Python object cannot be passed as a varargs parameter")
                else:
3918
                    self.args[i] = arg = arg.coerce_to(arg_ctype, env)
3919 3920
            if arg.is_temp and i > 0:
                some_args_in_temps = True
3921 3922 3923
        if some_args_in_temps:
            # if some args are temps and others are not, they may get
            # constructed in the wrong order (temps first) => make
3924 3925 3926 3927
            # sure they are either all temps or all not temps (except
            # for the last argument, which is evaluated last in any
            # case)
            for i in xrange(actual_nargs-1):
3928 3929
                if i == 0 and self.self is not None:
                    continue # self is ok
3930
                arg = self.args[i]
3931 3932
                if arg.nonlocally_immutable():
                    # locals, C functions, unassignable types are safe.
3933
                    pass
3934 3935
                elif arg.type.is_cpp_class:
                    # Assignment has side effects, avoid.
3936 3937
                    pass
                elif env.nogil and arg.type.is_pyobject:
3938 3939 3940
                    # can't copy a Python reference into a temp in nogil
                    # env (this is safe: a construction would fail in
                    # nogil anyway)
3941 3942
                    pass
                else:
3943 3944 3945 3946 3947
                    #self.args[i] = arg.coerce_to_temp(env)
                    # instead: issue a warning
                    if i > 0 or i == 1 and self.self is not None: # skip first arg
                        warning(arg.pos, "Argument evaluation order in C function call is undefined and may not be as expected", 0)
                        break
3948

William Stein's avatar
William Stein committed
3949
        # Calc result type and code fragment
Robert Bradshaw's avatar
Robert Bradshaw committed
3950
        if isinstance(self.function, NewExprNode):
3951
            self.type = PyrexTypes.CPtrType(self.function.class_type)
Robert Bradshaw's avatar
Robert Bradshaw committed
3952 3953
        else:
            self.type = func_type.return_type
3954

3955 3956 3957
        if self.function.is_name or self.function.is_attribute:
            if self.function.entry and self.function.entry.utility_code:
                self.is_temp = 1 # currently doesn't work for self.calculate_result_code()
3958

Stefan Behnel's avatar
Stefan Behnel committed
3959 3960 3961 3962 3963 3964
        if self.type.is_pyobject:
            self.result_ctype = py_object_type
            self.is_temp = 1
        elif func_type.exception_value is not None \
                 or func_type.exception_check:
            self.is_temp = 1
3965 3966 3967 3968
        elif self.type.is_memoryviewslice:
            self.is_temp = 1
            # func_type.exception_check = True

3969
        # Called in 'nogil' context?
3970
        self.nogil = env.nogil
3971 3972 3973 3974 3975
        if (self.nogil and
            func_type.exception_check and
            func_type.exception_check != '+'):
            env.use_utility_code(pyerr_occurred_withgil_utility_code)
        # C++ exception handler
Robert Bradshaw's avatar
Robert Bradshaw committed
3976 3977
        if func_type.exception_check == '+':
            if func_type.exception_value is None:
3978
                env.use_utility_code(UtilityCode.load_cached("CppExceptionConversion", "CppSupport.cpp"))
Robert Bradshaw's avatar
Robert Bradshaw committed
3979

William Stein's avatar
William Stein committed
3980 3981
    def calculate_result_code(self):
        return self.c_call_code()
3982

William Stein's avatar
William Stein committed
3983 3984
    def c_call_code(self):
        func_type = self.function_type()
3985
        if self.type is PyrexTypes.error_type or not func_type.is_cfunction:
William Stein's avatar
William Stein committed
3986 3987 3988
            return "<error>"
        formal_args = func_type.args
        arg_list_code = []
3989
        args = list(zip(formal_args, self.args))
3990 3991 3992 3993
        max_nargs = len(func_type.args)
        expected_nargs = max_nargs - func_type.optional_arg_count
        actual_nargs = len(self.args)
        for formal_arg, actual_arg in args[:expected_nargs]:
William Stein's avatar
William Stein committed
3994 3995
                arg_code = actual_arg.result_as(formal_arg.type)
                arg_list_code.append(arg_code)
3996

3997 3998
        if func_type.is_overridable:
            arg_list_code.append(str(int(self.wrapper_call or self.function.entry.is_unbound_cmethod)))
3999

4000
        if func_type.optional_arg_count:
4001
            if expected_nargs == actual_nargs:
4002
                optional_args = 'NULL'
4003
            else:
4004
                optional_args = "&%s" % self.opt_arg_struct
4005
            arg_list_code.append(optional_args)
4006

William Stein's avatar
William Stein committed
4007
        for actual_arg in self.args[len(formal_args):]:
4008
            arg_list_code.append(actual_arg.result())
4009 4010

        result = "%s(%s)" % (self.function.result(), ', '.join(arg_list_code))
William Stein's avatar
William Stein committed
4011
        return result
4012

William Stein's avatar
William Stein committed
4013 4014
    def generate_result_code(self, code):
        func_type = self.function_type()
4015 4016 4017
        if self.function.is_name or self.function.is_attribute:
            if self.function.entry and self.function.entry.utility_code:
                code.globalstate.use_utility_code(self.function.entry.utility_code)
William Stein's avatar
William Stein committed
4018
        if func_type.is_pyobject:
4019
            arg_code = self.arg_tuple.py_result()
William Stein's avatar
William Stein committed
4020
            code.putln(
4021
                "%s = PyObject_Call(%s, %s, NULL); %s" % (
4022
                    self.result(),
William Stein's avatar
William Stein committed
4023
                    self.function.py_result(),
4024
                    arg_code,
4025
                    code.error_goto_if_null(self.result(), self.pos)))
4026
            code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
4027
        elif func_type.is_cfunction:
4028 4029 4030
            if self.has_optional_args:
                actual_nargs = len(self.args)
                expected_nargs = len(func_type.args) - func_type.optional_arg_count
4031 4032
                self.opt_arg_struct = code.funcstate.allocate_temp(
                    func_type.op_arg_struct.base_type, manage_ref=True)
4033 4034 4035 4036
                code.putln("%s.%s = %s;" % (
                        self.opt_arg_struct,
                        Naming.pyrex_prefix + "n",
                        len(self.args) - expected_nargs))
4037
                args = list(zip(func_type.args, self.args))
4038 4039 4040
                for formal_arg, actual_arg in args[expected_nargs:actual_nargs]:
                    code.putln("%s.%s = %s;" % (
                            self.opt_arg_struct,
4041
                            func_type.opt_arg_cname(formal_arg.name),
4042
                            actual_arg.result_as(formal_arg.type)))
William Stein's avatar
William Stein committed
4043
            exc_checks = []
4044
            if self.type.is_pyobject and self.is_temp:
4045
                exc_checks.append("!%s" % self.result())
4046 4047 4048
            elif self.type.is_memoryviewslice:
                assert self.is_temp
                exc_checks.append(self.type.error_condition(self.result()))
William Stein's avatar
William Stein committed
4049
            else:
4050 4051
                exc_val = func_type.exception_value
                exc_check = func_type.exception_check
William Stein's avatar
William Stein committed
4052
                if exc_val is not None:
4053
                    exc_checks.append("%s == %s" % (self.result(), exc_val))
William Stein's avatar
William Stein committed
4054
                if exc_check:
4055 4056
                    if self.nogil:
                        exc_checks.append("__Pyx_ErrOccurredWithGIL()")
4057
                    else:
4058
                        exc_checks.append("PyErr_Occurred()")
William Stein's avatar
William Stein committed
4059 4060
            if self.is_temp or exc_checks:
                rhs = self.c_call_code()
4061 4062
                if self.result():
                    lhs = "%s = " % self.result()
William Stein's avatar
William Stein committed
4063 4064 4065
                    if self.is_temp and self.type.is_pyobject:
                        #return_type = self.type # func_type.return_type
                        #print "SimpleCallNode.generate_result_code: casting", rhs, \
Robert Bradshaw's avatar
Robert Bradshaw committed
4066
                        #    "from", return_type, "to pyobject" ###
William Stein's avatar
William Stein committed
4067 4068 4069
                        rhs = typecast(py_object_type, self.type, rhs)
                else:
                    lhs = ""
Felix Wu's avatar
Felix Wu committed
4070
                if func_type.exception_check == '+':
Robert Bradshaw's avatar
Robert Bradshaw committed
4071 4072 4073
                    if func_type.exception_value is None:
                        raise_py_exception = "__Pyx_CppExn2PyErr()"
                    elif func_type.exception_value.type.is_pyobject:
4074 4075 4076
                        raise_py_exception = ' try { throw; } catch(const std::exception& exn) { PyErr_SetString(%s, exn.what()); } catch(...) { PyErr_SetNone(%s); }' % (
                            func_type.exception_value.entry.cname,
                            func_type.exception_value.entry.cname)
Robert Bradshaw's avatar
Robert Bradshaw committed
4077 4078
                    else:
                        raise_py_exception = '%s(); if (!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError , "Error converting c++ exception.")' % func_type.exception_value.entry.cname
4079 4080
                    if self.nogil:
                        raise_py_exception = 'Py_BLOCK_THREADS; %s; Py_UNBLOCK_THREADS' % raise_py_exception
Felix Wu's avatar
Felix Wu committed
4081
                    code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
4082
                    "try {%s%s;} catch(...) {%s; %s}" % (
Felix Wu's avatar
Felix Wu committed
4083 4084
                        lhs,
                        rhs,
Robert Bradshaw's avatar
Robert Bradshaw committed
4085
                        raise_py_exception,
Felix Wu's avatar
Felix Wu committed
4086
                        code.error_goto(self.pos)))
4087 4088 4089 4090 4091 4092
                else:
                    if exc_checks:
                        goto_error = code.error_goto_if(" && ".join(exc_checks), self.pos)
                    else:
                        goto_error = ""
                    code.putln("%s%s; %s" % (lhs, rhs, goto_error))
4093
                if self.type.is_pyobject and self.result():
4094
                    code.put_gotref(self.py_result())
4095 4096
            if self.has_optional_args:
                code.funcstate.release_temp(self.opt_arg_struct)
4097 4098


4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182
class InlinedDefNodeCallNode(CallNode):
    #  Inline call to defnode
    #
    #  function       PyCFunctionNode
    #  function_name  NameNode
    #  args           [ExprNode]

    subexprs = ['args', 'function_name']
    is_temp = 1
    type = py_object_type
    function = None
    function_name = None

    def can_be_inlined(self):
        func_type= self.function.def_node
        if func_type.star_arg or func_type.starstar_arg:
            return False
        if len(func_type.args) != len(self.args):
            return False
        return True

    def analyse_types(self, env):
        self.function_name.analyse_types(env)

        for arg in self.args:
            arg.analyse_types(env)

        func_type = self.function.def_node
        actual_nargs = len(self.args)

        # Coerce arguments
        some_args_in_temps = False
        for i in xrange(actual_nargs):
            formal_type = func_type.args[i].type
            arg = self.args[i].coerce_to(formal_type, env)
            if arg.is_temp:
                if i > 0:
                    # first argument in temp doesn't impact subsequent arguments
                    some_args_in_temps = True
            elif arg.type.is_pyobject and not env.nogil:
                if arg.nonlocally_immutable():
                    # plain local variables are ok
                    pass
                else:
                    # we do not safely own the argument's reference,
                    # but we must make sure it cannot be collected
                    # before we return from the function, so we create
                    # an owned temp reference to it
                    if i > 0: # first argument doesn't matter
                        some_args_in_temps = True
                    arg = arg.coerce_to_temp(env)
            self.args[i] = arg

        if some_args_in_temps:
            # if some args are temps and others are not, they may get
            # constructed in the wrong order (temps first) => make
            # sure they are either all temps or all not temps (except
            # for the last argument, which is evaluated last in any
            # case)
            for i in xrange(actual_nargs-1):
                arg = self.args[i]
                if arg.nonlocally_immutable():
                    # locals, C functions, unassignable types are safe.
                    pass
                elif arg.type.is_cpp_class:
                    # Assignment has side effects, avoid.
                    pass
                elif env.nogil and arg.type.is_pyobject:
                    # can't copy a Python reference into a temp in nogil
                    # env (this is safe: a construction would fail in
                    # nogil anyway)
                    pass
                else:
                    #self.args[i] = arg.coerce_to_temp(env)
                    # instead: issue a warning
                    if i > 0:
                        warning(arg.pos, "Argument evaluation order in C function call is undefined and may not be as expected", 0)
                        break

    def generate_result_code(self, code):
        arg_code = [self.function_name.py_result()]
        func_type = self.function.def_node
        for arg, proto_arg in zip(self.args, func_type.args):
            if arg.type.is_pyobject:
4183
                arg_code.append(arg.result_as(proto_arg.type))
4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
            else:
                arg_code.append(arg.result())
        arg_code = ', '.join(arg_code)
        code.putln(
            "%s = %s(%s); %s" % (
                self.result(),
                self.function.def_node.entry.pyfunc_cname,
                arg_code,
                code.error_goto_if_null(self.result(), self.pos)))
        code.put_gotref(self.py_result())


4196 4197
class PythonCapiFunctionNode(ExprNode):
    subexprs = []
4198
    def __init__(self, pos, py_name, cname, func_type, utility_code = None):
4199
        self.pos = pos
4200 4201
        self.name = py_name
        self.cname = cname
4202 4203 4204
        self.type = func_type
        self.utility_code = utility_code

4205 4206 4207
    def analyse_types(self, env):
        pass

4208 4209 4210 4211 4212
    def generate_result_code(self, code):
        if self.utility_code:
            code.globalstate.use_utility_code(self.utility_code)

    def calculate_result_code(self):
4213
        return self.cname
4214 4215 4216 4217

class PythonCapiCallNode(SimpleCallNode):
    # Python C-API Function call (only created in transforms)

Stefan Behnel's avatar
Stefan Behnel committed
4218 4219 4220 4221 4222 4223
    # By default, we assume that the call never returns None, as this
    # is true for most C-API functions in CPython.  If this does not
    # apply to a call, set the following to True (or None to inherit
    # the default behaviour).
    may_return_none = False

4224
    def __init__(self, pos, function_name, func_type,
4225
                 utility_code = None, py_name=None, **kwargs):
4226 4227 4228
        self.type = func_type.return_type
        self.result_ctype = self.type
        self.function = PythonCapiFunctionNode(
4229
            pos, py_name, function_name, func_type,
4230 4231 4232 4233 4234
            utility_code = utility_code)
        # call this last so that we can override the constructed
        # attributes above with explicit keyword arguments if required
        SimpleCallNode.__init__(self, pos, **kwargs)

William Stein's avatar
William Stein committed
4235

4236
class GeneralCallNode(CallNode):
William Stein's avatar
William Stein committed
4237 4238 4239 4240 4241 4242
    #  General Python function call, including keyword,
    #  * and ** arguments.
    #
    #  function         ExprNode
    #  positional_args  ExprNode          Tuple of positional arguments
    #  keyword_args     ExprNode or None  Dict of keyword arguments
4243

4244
    type = py_object_type
4245

4246
    subexprs = ['function', 'positional_args', 'keyword_args']
William Stein's avatar
William Stein committed
4247

4248
    nogil_check = Node.gil_error
4249

4250 4251 4252 4253 4254 4255 4256 4257
    def compile_time_value(self, denv):
        function = self.function.compile_time_value(denv)
        positional_args = self.positional_args.compile_time_value(denv)
        keyword_args = self.keyword_args.compile_time_value(denv)
        try:
            return function(*positional_args, **keyword_args)
        except Exception, e:
            self.compile_time_value_error(e)
4258

4259
    def explicit_args_kwds(self):
4260 4261
        if (self.keyword_args and not isinstance(self.keyword_args, DictNode) or
            not isinstance(self.positional_args, TupleNode)):
4262
            raise CompileError(self.pos,
4263 4264
                'Compile-time keyword arguments must be explicit.')
        return self.positional_args.args, self.keyword_args
4265

William Stein's avatar
William Stein committed
4266
    def analyse_types(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
4267 4268
        if self.analyse_as_type_constructor(env):
            return
William Stein's avatar
William Stein committed
4269 4270 4271 4272
        self.function.analyse_types(env)
        self.positional_args.analyse_types(env)
        if self.keyword_args:
            self.keyword_args.analyse_types(env)
4273
        if not self.function.type.is_pyobject:
4274 4275
            if self.function.type.is_error:
                self.type = error_type
Stefan Behnel's avatar
Stefan Behnel committed
4276
                return
4277
            if hasattr(self.function, 'entry') and not self.function.entry.as_variable:
4278
                error(self.pos, "Keyword and starred arguments not allowed in cdef functions.")
4279 4280
            else:
                self.function = self.function.coerce_to_pyobject(env)
William Stein's avatar
William Stein committed
4281 4282
        self.positional_args = \
            self.positional_args.coerce_to_pyobject(env)
Stefan Behnel's avatar
Stefan Behnel committed
4283
        function = self.function
4284 4285 4286 4287 4288
        if function.is_name and function.type_entry:
            # We are calling an extension type constructor.  As long
            # as we do not support __new__(), the result type is clear
            self.type = function.type_entry.type
            self.result_ctype = py_object_type
Stefan Behnel's avatar
Stefan Behnel committed
4289
            self.may_return_none = False
4290 4291
        else:
            self.type = py_object_type
William Stein's avatar
William Stein committed
4292
        self.is_temp = 1
4293

William Stein's avatar
William Stein committed
4294
    def generate_result_code(self, code):
4295
        if self.type.is_error: return
4296 4297
        if self.keyword_args:
            kwargs = self.keyword_args.py_result()
William Stein's avatar
William Stein committed
4298
        else:
4299
            kwargs = 'NULL'
William Stein's avatar
William Stein committed
4300
        code.putln(
4301
            "%s = PyObject_Call(%s, %s, %s); %s" % (
4302
                self.result(),
4303 4304 4305
                self.function.py_result(),
                self.positional_args.py_result(),
                kwargs,
4306
                code.error_goto_if_null(self.result(), self.pos)))
4307
        code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
4308 4309


4310
class AsTupleNode(ExprNode):
William Stein's avatar
William Stein committed
4311 4312 4313 4314
    #  Convert argument to tuple. Used for normalising
    #  the * argument of a function call.
    #
    #  arg    ExprNode
4315

William Stein's avatar
William Stein committed
4316
    subexprs = ['arg']
4317 4318 4319

    def calculate_constant_result(self):
        self.constant_result = tuple(self.base.constant_result)
4320

4321 4322 4323 4324 4325 4326 4327
    def compile_time_value(self, denv):
        arg = self.arg.compile_time_value(denv)
        try:
            return tuple(arg)
        except Exception, e:
            self.compile_time_value_error(e)

William Stein's avatar
William Stein committed
4328 4329 4330
    def analyse_types(self, env):
        self.arg.analyse_types(env)
        self.arg = self.arg.coerce_to_pyobject(env)
4331
        self.type = tuple_type
William Stein's avatar
William Stein committed
4332
        self.is_temp = 1
4333

4334 4335 4336
    def may_be_none(self):
        return False

4337
    nogil_check = Node.gil_error
4338 4339
    gil_message = "Constructing Python tuple"

William Stein's avatar
William Stein committed
4340 4341
    def generate_result_code(self, code):
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
4342
            "%s = PySequence_Tuple(%s); %s" % (
4343
                self.result(),
William Stein's avatar
William Stein committed
4344
                self.arg.py_result(),
4345
                code.error_goto_if_null(self.result(), self.pos)))
4346
        code.put_gotref(self.py_result())
4347

William Stein's avatar
William Stein committed
4348

4349
class AttributeNode(ExprNode):
William Stein's avatar
William Stein committed
4350 4351 4352 4353
    #  obj.attribute
    #
    #  obj          ExprNode
    #  attribute    string
4354
    #  needs_none_check boolean        Used if obj is an extension type.
4355
    #                                  If set to True, it is known that the type is not None.
William Stein's avatar
William Stein committed
4356 4357 4358 4359 4360 4361 4362
    #
    #  Used internally:
    #
    #  is_py_attr           boolean   Is a Python getattr operation
    #  member               string    C name of struct member
    #  is_called            boolean   Function call is being done on result
    #  entry                Entry     Symbol table entry of attribute
4363

William Stein's avatar
William Stein committed
4364 4365
    is_attribute = 1
    subexprs = ['obj']
4366

William Stein's avatar
William Stein committed
4367 4368 4369
    type = PyrexTypes.error_type
    entry = None
    is_called = 0
4370
    needs_none_check = True
4371
    is_memslice_transpose = False
William Stein's avatar
William Stein committed
4372

4373
    def as_cython_attribute(self):
Mark Florisson's avatar
Mark Florisson committed
4374 4375 4376
        if (isinstance(self.obj, NameNode) and
                self.obj.is_cython_module and not
                self.attribute == u"parallel"):
4377
            return self.attribute
Mark Florisson's avatar
Mark Florisson committed
4378

4379 4380 4381
        cy = self.obj.as_cython_attribute()
        if cy:
            return "%s.%s" % (cy, self.attribute)
4382
        return None
4383

4384 4385 4386 4387 4388 4389 4390 4391 4392
    def coerce_to(self, dst_type, env):
        #  If coercing to a generic pyobject and this is a cpdef function
        #  we can create the corresponding attribute
        if dst_type is py_object_type:
            entry = self.entry
            if entry and entry.is_cfunction and entry.as_variable:
                # must be a cpdef function
                self.is_temp = 1
                self.entry = entry.as_variable
4393
                self.analyse_as_python_attribute(env)
4394
                return self
4395
        return ExprNode.coerce_to(self, dst_type, env)
4396 4397 4398

    def calculate_constant_result(self):
        attr = self.attribute
4399
        if attr.startswith("__") and attr.endswith("__"):
4400 4401 4402
            return
        self.constant_result = getattr(self.obj.constant_result, attr)

4403 4404
    def compile_time_value(self, denv):
        attr = self.attribute
4405
        if attr.startswith("__") and attr.endswith("__"):
Stefan Behnel's avatar
Stefan Behnel committed
4406 4407
            error(self.pos,
                  "Invalid attribute name '%s' in compile-time expression" % attr)
4408
            return None
4409
        obj = self.obj.compile_time_value(denv)
4410 4411 4412 4413
        try:
            return getattr(obj, attr)
        except Exception, e:
            self.compile_time_value_error(e)
4414

Robert Bradshaw's avatar
Robert Bradshaw committed
4415 4416
    def type_dependencies(self, env):
        return self.obj.type_dependencies(env)
4417

4418 4419 4420 4421 4422 4423
    def infer_type(self, env):
        if self.analyse_as_cimported_attribute(env, 0):
            return self.entry.type
        elif self.analyse_as_unbound_cmethod(env):
            return self.entry.type
        else:
4424 4425 4426 4427 4428 4429 4430 4431
            obj_type = self.obj.infer_type(env)
            self.analyse_attribute(env, obj_type = obj_type)
            if obj_type.is_builtin_type and self.type.is_cfunction:
                # special case: C-API replacements for C methods of
                # builtin types cannot be inferred as C functions as
                # that would prevent their use as bound methods
                self.type = py_object_type
                return py_object_type
4432
            return self.type
4433

William Stein's avatar
William Stein committed
4434 4435
    def analyse_target_declaration(self, env):
        pass
4436

William Stein's avatar
William Stein committed
4437 4438
    def analyse_target_types(self, env):
        self.analyse_types(env, target = 1)
4439 4440
        if not self.is_lvalue():
            error(self.pos, "Assignment to non-lvalue of type '%s'" % self.type)
4441

William Stein's avatar
William Stein committed
4442
    def analyse_types(self, env, target = 0):
4443
        self.initialized_check = env.directives['initializedcheck']
William Stein's avatar
William Stein committed
4444
        if self.analyse_as_cimported_attribute(env, target):
4445 4446 4447 4448 4449 4450 4451
            self.entry.used = True
        elif not target and self.analyse_as_unbound_cmethod(env):
            self.entry.used = True
        else:
            self.analyse_as_ordinary_attribute(env, target)
            if self.entry:
                self.entry.used = True
4452

4453 4454 4455 4456
        # may be mutated in a namenode now :)
        if self.is_attribute:
            self.wrap_obj_in_nonecheck(env)

William Stein's avatar
William Stein committed
4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
    def analyse_as_cimported_attribute(self, env, target):
        # Try to interpret this as a reference to an imported
        # C const, type, var or function. If successful, mutates
        # this node into a NameNode and returns 1, otherwise
        # returns 0.
        module_scope = self.obj.analyse_as_module(env)
        if module_scope:
            entry = module_scope.lookup_here(self.attribute)
            if entry and (
                entry.is_cglobal or entry.is_cfunction
                or entry.is_type or entry.is_const):
                    self.mutate_into_name_node(env, entry, target)
4469
                    entry.used = 1
William Stein's avatar
William Stein committed
4470 4471
                    return 1
        return 0
4472

William Stein's avatar
William Stein committed
4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488
    def analyse_as_unbound_cmethod(self, env):
        # Try to interpret this as a reference to an unbound
        # C method of an extension type. If successful, mutates
        # this node into a NameNode and returns 1, otherwise
        # returns 0.
        type = self.obj.analyse_as_extension_type(env)
        if type:
            entry = type.scope.lookup_here(self.attribute)
            if entry and entry.is_cmethod:
                # Create a temporary entry describing the C method
                # as an ordinary function.
                ubcm_entry = Symtab.Entry(entry.name,
                    "%s->%s" % (type.vtabptr_cname, entry.cname),
                    entry.type)
                ubcm_entry.is_cfunction = 1
                ubcm_entry.func_cname = entry.func_cname
4489
                ubcm_entry.is_unbound_cmethod = 1
William Stein's avatar
William Stein committed
4490 4491 4492
                self.mutate_into_name_node(env, ubcm_entry, None)
                return 1
        return 0
4493

4494 4495 4496
    def analyse_as_type(self, env):
        module_scope = self.obj.analyse_as_module(env)
        if module_scope:
4497
            return module_scope.lookup_type(self.attribute)
4498
        if not self.obj.is_string_literal:
Robert Bradshaw's avatar
Robert Bradshaw committed
4499
            base_type = self.obj.analyse_as_type(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
4500
            if base_type and hasattr(base_type, 'scope') and base_type.scope is not None:
Robert Bradshaw's avatar
Robert Bradshaw committed
4501
                return base_type.scope.lookup_type(self.attribute)
4502
        return None
4503

William Stein's avatar
William Stein committed
4504 4505 4506 4507 4508 4509 4510 4511 4512
    def analyse_as_extension_type(self, env):
        # Try to interpret this as a reference to an extension type
        # in a cimported module. Returns the extension type, or None.
        module_scope = self.obj.analyse_as_module(env)
        if module_scope:
            entry = module_scope.lookup_here(self.attribute)
            if entry and entry.is_type and entry.type.is_extension_type:
                return entry.type
        return None
4513

William Stein's avatar
William Stein committed
4514 4515 4516 4517 4518 4519 4520 4521 4522
    def analyse_as_module(self, env):
        # Try to interpret this as a reference to a cimported module
        # in another cimported module. Returns the module scope, or None.
        module_scope = self.obj.analyse_as_module(env)
        if module_scope:
            entry = module_scope.lookup_here(self.attribute)
            if entry and entry.as_module:
                return entry.as_module
        return None
4523

William Stein's avatar
William Stein committed
4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534
    def mutate_into_name_node(self, env, entry, target):
        # Mutate this node into a NameNode and complete the
        # analyse_types phase.
        self.__class__ = NameNode
        self.name = self.attribute
        self.entry = entry
        del self.obj
        del self.attribute
        if target:
            NameNode.analyse_target_types(self, env)
        else:
4535
            NameNode.analyse_rvalue_entry(self, env)
4536

William Stein's avatar
William Stein committed
4537 4538 4539 4540
    def analyse_as_ordinary_attribute(self, env, target):
        self.obj.analyse_types(env)
        self.analyse_attribute(env)
        if self.entry and self.entry.is_cmethod and not self.is_called:
4541 4542
#            error(self.pos, "C method can only be called")
            pass
4543 4544
        ## Reference to C array turns into pointer to first element.
        #while self.type.is_array:
Robert Bradshaw's avatar
Robert Bradshaw committed
4545
        #    self.type = self.type.element_ptr_type()
William Stein's avatar
William Stein committed
4546 4547 4548 4549
        if self.is_py_attr:
            if not target:
                self.is_temp = 1
                self.result_ctype = py_object_type
4550 4551
        elif target and self.obj.type.is_builtin_type:
            error(self.pos, "Assignment to an immutable object field")
4552 4553
        #elif self.type.is_memoryviewslice and not target:
        #    self.is_temp = True
4554

Robert Bradshaw's avatar
Robert Bradshaw committed
4555
    def analyse_attribute(self, env, obj_type = None):
William Stein's avatar
William Stein committed
4556 4557 4558
        # Look up attribute and set self.type and self.member.
        self.is_py_attr = 0
        self.member = self.attribute
Robert Bradshaw's avatar
Robert Bradshaw committed
4559 4560 4561 4562 4563 4564 4565
        if obj_type is None:
            if self.obj.type.is_string:
                self.obj = self.obj.coerce_to_pyobject(env)
            obj_type = self.obj.type
        else:
            if obj_type.is_string:
                obj_type = py_object_type
4566
        if obj_type.is_ptr or obj_type.is_array:
William Stein's avatar
William Stein committed
4567 4568
            obj_type = obj_type.base_type
            self.op = "->"
4569
        elif obj_type.is_extension_type or obj_type.is_builtin_type:
William Stein's avatar
William Stein committed
4570 4571 4572 4573 4574 4575
            self.op = "->"
        else:
            self.op = "."
        if obj_type.has_attributes:
            entry = None
            if obj_type.attributes_known():
4576 4577
                if (obj_type.is_memoryviewslice and not
                        obj_type.scope.lookup_here(self.attribute)):
4578 4579 4580 4581 4582 4583 4584
                    if self.attribute == 'T':
                        self.is_memslice_transpose = True
                        self.is_temp = True
                        self.use_managed_ref = True
                        self.type = self.obj.type
                        return
                    else:
4585
                        obj_type.declare_attribute(self.attribute, env, self.pos)
William Stein's avatar
William Stein committed
4586
                entry = obj_type.scope.lookup_here(self.attribute)
Robert Bradshaw's avatar
Robert Bradshaw committed
4587 4588
                if entry and entry.is_member:
                    entry = None
William Stein's avatar
William Stein committed
4589
            else:
4590 4591
                error(self.pos,
                    "Cannot select attribute of incomplete type '%s'"
William Stein's avatar
William Stein committed
4592
                    % obj_type)
Robert Bradshaw's avatar
Robert Bradshaw committed
4593 4594
                self.type = PyrexTypes.error_type
                return
William Stein's avatar
William Stein committed
4595 4596
            self.entry = entry
            if entry:
4597 4598
                if obj_type.is_extension_type and entry.name == "__weakref__":
                    error(self.pos, "Illegal use of special attribute __weakref__")
4599 4600

                # def methods need the normal attribute lookup
4601
                # because they do not have struct entries
4602 4603 4604 4605
                # fused function go through assignment synthesis
                # (foo = pycfunction(foo_func_obj)) and need to go through
                # regular Python lookup as well
                if (entry.is_variable and not entry.fused_cfunction) or entry.is_cmethod:
4606 4607 4608
                    self.type = entry.type
                    self.member = entry.cname
                    return
William Stein's avatar
William Stein committed
4609 4610 4611 4612 4613
                else:
                    # If it's not a variable or C method, it must be a Python
                    # method of an extension type, so we treat it like a Python
                    # attribute.
                    pass
4614
        # If we get here, the base object is not a struct/union/extension
William Stein's avatar
William Stein committed
4615 4616 4617
        # type, or it is an extension type and the attribute is either not
        # declared or is declared as a Python method. Treat it as a Python
        # attribute reference.
Robert Bradshaw's avatar
Robert Bradshaw committed
4618
        self.analyse_as_python_attribute(env, obj_type)
Stefan Behnel's avatar
Stefan Behnel committed
4619

Robert Bradshaw's avatar
Robert Bradshaw committed
4620 4621 4622
    def analyse_as_python_attribute(self, env, obj_type = None):
        if obj_type is None:
            obj_type = self.obj.type
4623 4624
        # mangle private '__*' Python attributes used inside of a class
        self.attribute = env.mangle_class_private_name(self.attribute)
4625
        self.member = self.attribute
4626 4627
        self.type = py_object_type
        self.is_py_attr = 1
4628
        if not obj_type.is_pyobject and not obj_type.is_error:
4629
            if obj_type.can_coerce_to_pyobject(env):
4630 4631 4632 4633 4634
                self.obj = self.obj.coerce_to_pyobject(env)
            else:
                error(self.pos,
                      "Object of type '%s' has no attribute '%s'" %
                      (obj_type, self.attribute))
4635

4636 4637 4638 4639 4640
    def wrap_obj_in_nonecheck(self, env):
        if not env.directives['nonecheck']:
            return

        msg = None
4641
        format_args = ()
4642 4643
        if (self.obj.type.is_extension_type and self.needs_none_check and not
                self.is_py_attr):
4644 4645
            msg = "'NoneType' object has no attribute '%s'"
            format_args = (self.attribute,)
4646 4647 4648 4649 4650 4651 4652
        elif self.obj.type.is_memoryviewslice:
            if self.is_memslice_transpose:
                msg = "Cannot transpose None memoryview slice"
            else:
                entry = self.obj.type.scope.lookup_here(self.attribute)
                if entry:
                    # copy/is_c_contig/shape/strides etc
4653 4654
                    msg = "Cannot access '%s' attribute of None memoryview slice"
                    format_args = (entry.name,)
4655 4656

        if msg:
4657 4658
            self.obj = self.obj.as_none_safe_node(msg, 'PyExc_AttributeError',
                                                  format_args=format_args)
4659 4660


4661
    def nogil_check(self, env):
4662
        if self.is_py_attr:
4663
            self.gil_error()
4664 4665 4666
        elif self.type.is_memoryviewslice:
            import MemoryView
            MemoryView.err_if_nogil_initialized_check(self.pos, env, 'attribute')
4667

4668 4669
    gil_message = "Accessing Python attribute"

William Stein's avatar
William Stein committed
4670 4671 4672 4673 4674 4675 4676 4677
    def is_simple(self):
        if self.obj:
            return self.result_in_temp() or self.obj.is_simple()
        else:
            return NameNode.is_simple(self)

    def is_lvalue(self):
        if self.obj:
4678
            return not self.type.is_array
William Stein's avatar
William Stein committed
4679 4680
        else:
            return NameNode.is_lvalue(self)
4681

William Stein's avatar
William Stein committed
4682 4683 4684 4685 4686
    def is_ephemeral(self):
        if self.obj:
            return self.obj.is_ephemeral()
        else:
            return NameNode.is_ephemeral(self)
4687

William Stein's avatar
William Stein committed
4688 4689
    def calculate_result_code(self):
        #print "AttributeNode.calculate_result_code:", self.member ###
4690
        #print "...obj node =", self.obj, "code", self.obj.result() ###
William Stein's avatar
William Stein committed
4691 4692 4693 4694 4695
        #print "...obj type", self.obj.type, "ctype", self.obj.ctype() ###
        obj = self.obj
        obj_code = obj.result_as(obj.type)
        #print "...obj_code =", obj_code ###
        if self.entry and self.entry.is_cmethod:
Stefan Behnel's avatar
Stefan Behnel committed
4696
            if obj.type.is_extension_type and not self.entry.is_builtin_cmethod:
4697 4698
                if self.entry.final_func_cname:
                    return self.entry.final_func_cname
4699

Mark Florisson's avatar
Mark Florisson committed
4700
                if self.type.from_fused:
4701 4702 4703 4704
                    # If the attribute was specialized through indexing, make
                    # sure to get the right fused name, as our entry was
                    # replaced by our parent index node
                    # (AnalyseExpressionsTransform)
Mark Florisson's avatar
Mark Florisson committed
4705 4706
                    self.member = self.entry.cname

Robert Bradshaw's avatar
Robert Bradshaw committed
4707
                return "((struct %s *)%s%s%s)->%s" % (
4708
                    obj.type.vtabstruct_cname, obj_code, self.op,
Robert Bradshaw's avatar
Robert Bradshaw committed
4709 4710 4711
                    obj.type.vtabslot_cname, self.member)
            else:
                return self.member
4712
        elif obj.type.is_complex:
4713
            return "__Pyx_C%s(%s)" % (self.member.upper(), obj_code)
William Stein's avatar
William Stein committed
4714
        else:
4715 4716 4717
            if obj.type.is_builtin_type and self.entry and self.entry.is_variable:
                # accessing a field of a builtin type, need to cast better than result_as() does
                obj_code = obj.type.cast_code(obj.result(), to_object_struct = True)
William Stein's avatar
William Stein committed
4718
            return "%s%s%s" % (obj_code, self.op, self.member)
4719

William Stein's avatar
William Stein committed
4720 4721
    def generate_result_code(self, code):
        if self.is_py_attr:
4722 4723
            code.putln(
                '%s = PyObject_GetAttr(%s, %s); %s' % (
4724
                    self.result(),
4725
                    self.obj.py_result(),
4726
                    code.intern_identifier(self.attribute),
4727
                    code.error_goto_if_null(self.result(), self.pos)))
4728
            code.put_gotref(self.py_result())
4729
        elif self.type.is_memoryviewslice:
4730 4731 4732 4733 4734 4735 4736 4737 4738
            if self.is_memslice_transpose:
                # transpose the slice
                for access, packing in self.type.axes:
                    if access == 'ptr':
                        error(self.pos, "Transposing not supported for slices "
                                        "with indirect dimensions")
                        return

                code.putln("%s = %s;" % (self.result(), self.obj.result()))
4739 4740
                if self.obj.is_name or (self.obj.is_attribute and
                                        self.obj.is_memslice_transpose):
4741 4742 4743 4744 4745
                    code.put_incref_memoryviewslice(self.result(), have_gil=True)

                T = "__pyx_memslice_transpose(&%s) == 0"
                code.putln(code.error_goto_if(T % self.result(), self.pos))
            elif self.initialized_check:
4746 4747 4748 4749 4750 4751
                code.putln(
                    'if (unlikely(!%s.memview)) {'
                        'PyErr_SetString(PyExc_AttributeError,'
                                        '"Memoryview is not initialized");'
                        '%s'
                    '}' % (self.result(), code.error_goto(self.pos)))
4752 4753 4754
        else:
            # result_code contains what is needed, but we may need to insert
            # a check and raise an exception
4755
            if self.obj.type.is_extension_type:
4756
                pass
4757 4758 4759
            elif self.entry and self.entry.is_cmethod and self.entry.utility_code:
                # C method implemented as function call with utility code
                code.globalstate.use_utility_code(self.entry.utility_code)
4760

William Stein's avatar
William Stein committed
4761 4762 4763
    def generate_assignment_code(self, rhs, code):
        self.obj.generate_evaluation_code(code)
        if self.is_py_attr:
4764
            code.put_error_if_neg(self.pos,
4765 4766
                'PyObject_SetAttr(%s, %s, %s)' % (
                    self.obj.py_result(),
4767
                    code.intern_identifier(self.attribute),
4768
                    rhs.py_result()))
William Stein's avatar
William Stein committed
4769
            rhs.generate_disposal_code(code)
4770
            rhs.free_temps(code)
4771 4772 4773 4774 4775
        elif self.obj.type.is_complex:
            code.putln("__Pyx_SET_C%s(%s, %s);" % (
                self.member.upper(),
                self.obj.result_as(self.obj.type),
                rhs.result_as(self.ctype())))
William Stein's avatar
William Stein committed
4776
        else:
4777
            select_code = self.result()
4778
            if self.type.is_pyobject and self.use_managed_ref:
William Stein's avatar
William Stein committed
4779
                rhs.make_owned_reference(code)
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
4780
                code.put_giveref(rhs.py_result())
4781
                code.put_gotref(select_code)
William Stein's avatar
William Stein committed
4782
                code.put_decref(select_code, self.ctype())
4783
            elif self.type.is_memoryviewslice:
4784
                import MemoryView
4785
                MemoryView.put_assign_to_memviewslice(
4786
                        select_code, rhs, rhs.result(), self.type, code)
4787

4788
            if not self.type.is_memoryviewslice:
4789 4790 4791 4792 4793
                code.putln(
                    "%s = %s;" % (
                        select_code,
                        rhs.result_as(self.ctype())))
                        #rhs.result()))
William Stein's avatar
William Stein committed
4794
            rhs.generate_post_assignment_code(code)
4795
            rhs.free_temps(code)
William Stein's avatar
William Stein committed
4796
        self.obj.generate_disposal_code(code)
4797
        self.obj.free_temps(code)
4798

William Stein's avatar
William Stein committed
4799 4800
    def generate_deletion_code(self, code):
        self.obj.generate_evaluation_code(code)
4801
        if self.is_py_attr or (isinstance(self.entry.scope, Symtab.PropertyScope)
4802
                               and u'__del__' in self.entry.scope.entries):
4803 4804 4805
            code.put_error_if_neg(self.pos,
                'PyObject_DelAttr(%s, %s)' % (
                    self.obj.py_result(),
4806
                    code.intern_identifier(self.attribute)))
William Stein's avatar
William Stein committed
4807 4808 4809
        else:
            error(self.pos, "Cannot delete C attribute of extension type")
        self.obj.generate_disposal_code(code)
4810
        self.obj.free_temps(code)
4811

4812 4813 4814 4815 4816
    def annotate(self, code):
        if self.is_py_attr:
            code.annotate(self.pos, AnnotationItem('py_attr', 'python attribute', size=len(self.attribute)))
        else:
            code.annotate(self.pos, AnnotationItem('c_attr', 'c attribute', size=len(self.attribute)))
William Stein's avatar
William Stein committed
4817

4818

William Stein's avatar
William Stein committed
4819 4820 4821 4822 4823 4824
#-------------------------------------------------------------------
#
#  Constructor nodes
#
#-------------------------------------------------------------------

4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839
class StarredTargetNode(ExprNode):
    #  A starred expression like "*a"
    #
    #  This is only allowed in sequence assignment targets such as
    #
    #      a, *b = (1,2,3,4)    =>     a = 1 ; b = [2,3,4]
    #
    #  and will be removed during type analysis (or generate an error
    #  if it's found at unexpected places).
    #
    #  target          ExprNode

    subexprs = ['target']
    is_starred = 1
    type = py_object_type
Robert Bradshaw's avatar
Robert Bradshaw committed
4840
    is_temp = 1
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868

    def __init__(self, pos, target):
        self.pos = pos
        self.target = target

    def analyse_declarations(self, env):
        error(self.pos, "can use starred expression only as assignment target")
        self.target.analyse_declarations(env)

    def analyse_types(self, env):
        error(self.pos, "can use starred expression only as assignment target")
        self.target.analyse_types(env)
        self.type = self.target.type

    def analyse_target_declaration(self, env):
        self.target.analyse_target_declaration(env)

    def analyse_target_types(self, env):
        self.target.analyse_target_types(env)
        self.type = self.target.type

    def calculate_result_code(self):
        return ""

    def generate_result_code(self, code):
        pass


4869
class SequenceNode(ExprNode):
William Stein's avatar
William Stein committed
4870 4871 4872 4873 4874 4875
    #  Base class for list and tuple constructor nodes.
    #  Contains common code for performing sequence unpacking.
    #
    #  args                    [ExprNode]
    #  unpacked_items          [ExprNode] or None
    #  coerced_unpacked_items  [ExprNode] or None
4876
    # mult_factor              ExprNode     the integer number of content repetitions ([1,2]*3)
4877

4878
    subexprs = ['args', 'mult_factor']
4879

William Stein's avatar
William Stein committed
4880 4881
    is_sequence_constructor = 1
    unpacked_items = None
4882
    mult_factor = None
4883

4884 4885 4886
    def compile_time_value_list(self, denv):
        return [arg.compile_time_value(denv) for arg in self.args]

4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900
    def replace_starred_target_node(self):
        # replace a starred node in the targets by the contained expression
        self.starred_assignment = False
        args = []
        for arg in self.args:
            if arg.is_starred:
                if self.starred_assignment:
                    error(arg.pos, "more than 1 starred expression in assignment")
                self.starred_assignment = True
                arg = arg.target
                arg.is_starred = True
            args.append(arg)
        self.args = args

William Stein's avatar
William Stein committed
4901
    def analyse_target_declaration(self, env):
4902
        self.replace_starred_target_node()
William Stein's avatar
William Stein committed
4903 4904 4905
        for arg in self.args:
            arg.analyse_target_declaration(env)

4906
    def analyse_types(self, env, skip_children=False):
William Stein's avatar
William Stein committed
4907 4908
        for i in range(len(self.args)):
            arg = self.args[i]
4909
            if not skip_children: arg.analyse_types(env)
William Stein's avatar
William Stein committed
4910
            self.args[i] = arg.coerce_to_pyobject(env)
4911 4912 4913
        if self.mult_factor:
            self.mult_factor.analyse_types(env)
            if not self.mult_factor.type.is_int:
4914
                self.mult_factor = self.mult_factor.coerce_to_pyobject(env)
William Stein's avatar
William Stein committed
4915
        self.is_temp = 1
Stefan Behnel's avatar
Stefan Behnel committed
4916
        # not setting self.type here, subtypes do this
4917

4918 4919 4920
    def may_be_none(self):
        return False

William Stein's avatar
William Stein committed
4921
    def analyse_target_types(self, env):
4922
        if self.mult_factor:
Stefan Behnel's avatar
Stefan Behnel committed
4923
            error(self.pos, "can't assign to multiplied sequence")
4924
        self.unpacked_items = []
William Stein's avatar
William Stein committed
4925
        self.coerced_unpacked_items = []
4926
        self.any_coerced_items = False
William Stein's avatar
William Stein committed
4927 4928
        for arg in self.args:
            arg.analyse_target_types(env)
4929 4930 4931 4932 4933 4934
            if arg.is_starred:
                if not arg.type.assignable_from(Builtin.list_type):
                    error(arg.pos,
                          "starred target must have Python object (list) type")
                if arg.type is py_object_type:
                    arg.type = Builtin.list_type
William Stein's avatar
William Stein committed
4935 4936
            unpacked_item = PyTempNode(self.pos, env)
            coerced_unpacked_item = unpacked_item.coerce_to(arg.type, env)
4937 4938
            if unpacked_item is not coerced_unpacked_item:
                self.any_coerced_items = True
William Stein's avatar
William Stein committed
4939 4940 4941
            self.unpacked_items.append(unpacked_item)
            self.coerced_unpacked_items.append(coerced_unpacked_item)
        self.type = py_object_type
4942

William Stein's avatar
William Stein committed
4943 4944
    def generate_result_code(self, code):
        self.generate_operation_code(code)
4945

4946 4947 4948 4949 4950 4951
    def generate_sequence_packing_code(self, code, target=None, plain=False):
        if target is None:
            target = self.result()
        py_multiply = self.mult_factor and not self.mult_factor.type.is_int
        if plain or py_multiply:
            mult_factor = None
4952
        else:
4953 4954 4955 4956 4957 4958
            mult_factor = self.mult_factor
        if mult_factor:
            mult = mult_factor.result()
            if isinstance(mult_factor.constant_result, (int,long)) \
                   and mult_factor.constant_result > 0:
                size_factor = ' * %s' % mult_factor.constant_result
4959 4960 4961 4962 4963
            else:
                size_factor = ' * ((%s<0) ? 0:%s)' % (mult, mult)
        else:
            size_factor = ''
            mult = ''
4964 4965 4966 4967 4968 4969

        if self.type is Builtin.list_type:
            create_func, set_item_func = 'PyList_New', 'PyList_SET_ITEM'
        elif self.type is Builtin.tuple_type:
            create_func, set_item_func = 'PyTuple_New', 'PyTuple_SET_ITEM'
        else:
Stefan Behnel's avatar
Stefan Behnel committed
4970
            raise InternalError("sequence packing for unexpected type %s" % self.type)
4971 4972
        arg_count = len(self.args)
        code.putln("%s = %s(%s%s); %s" % (
4973 4974 4975 4976
            target, create_func, arg_count, size_factor,
            code.error_goto_if_null(target, self.pos)))
        code.put_gotref(target)

4977
        if mult:
4978 4979 4980 4981
            # FIXME: can't use a temp variable here as the code may
            # end up in the constant building function.  Temps
            # currently don't work there.

4982 4983
            #counter = code.funcstate.allocate_temp(mult_factor.type, manage_ref=False)
            counter = Naming.quick_temp_cname
4984 4985
            code.putln('{ Py_ssize_t %s;' % counter)
            if arg_count == 1:
Stefan Behnel's avatar
Stefan Behnel committed
4986
                offset = counter
4987
            else:
Stefan Behnel's avatar
Stefan Behnel committed
4988
                offset = '%s * %s' % (counter, arg_count)
4989 4990 4991 4992 4993 4994 4995 4996 4997
            code.putln('for (%s=0; %s < %s; %s++) {' % (
                counter, counter, mult, counter
                ))
        else:
            offset = ''
        for i in xrange(arg_count):
            arg = self.args[i]
            if mult or not arg.result_in_temp():
                code.put_incref(arg.result(), arg.ctype())
Stefan Behnel's avatar
Stefan Behnel committed
4998
            code.putln("%s(%s, %s, %s);" % (
4999
                set_item_func,
5000
                target,
Stefan Behnel's avatar
Stefan Behnel committed
5001
                (offset and i) and ('%s + %s' % (offset, i)) or (offset or i),
5002 5003 5004 5005
                arg.py_result()))
            code.put_giveref(arg.py_result())
        if mult:
            code.putln('}')
5006 5007
            #code.funcstate.release_temp(counter)
            code.putln('}')
5008
        elif py_multiply and not plain:
5009
            code.putln('{ PyObject* %s = PyNumber_InPlaceMultiply(%s, %s); %s' % (
5010 5011 5012 5013 5014 5015 5016
                Naming.quick_temp_cname, target, self.mult_factor.py_result(),
                code.error_goto_if_null(Naming.quick_temp_cname, self.pos)
                ))
            code.put_gotref(Naming.quick_temp_cname)
            code.put_decref(target, py_object_type)
            code.putln('%s = %s;' % (target, Naming.quick_temp_cname))
            code.putln('}')
5017 5018

    def generate_subexpr_disposal_code(self, code):
5019
        if self.mult_factor and self.mult_factor.type.is_int:
5020 5021 5022 5023 5024 5025 5026 5027 5028
            super(SequenceNode, self).generate_subexpr_disposal_code(code)
        else:
            # We call generate_post_assignment_code here instead
            # of generate_disposal_code, because values were stored
            # in the tuple using a reference-stealing operation.
            for arg in self.args:
                arg.generate_post_assignment_code(code)
                # Should NOT call free_temps -- this is invoked by the default
                # generate_evaluation_code which will do that.
5029 5030
            if self.mult_factor:
                self.mult_factor.generate_disposal_code(code)
5031

William Stein's avatar
William Stein committed
5032
    def generate_assignment_code(self, rhs, code):
5033 5034 5035
        if self.starred_assignment:
            self.generate_starred_assignment_code(rhs, code)
        else:
5036
            self.generate_parallel_assignment_code(rhs, code)
5037 5038 5039 5040 5041

        for item in self.unpacked_items:
            item.release(code)
        rhs.free_temps(code)

5042 5043 5044 5045 5046
    _func_iternext_type = PyrexTypes.CPtrType(PyrexTypes.CFuncType(
        PyrexTypes.py_object_type, [
            PyrexTypes.CFuncTypeArg("it", PyrexTypes.py_object_type, None),
            ]))

5047
    def generate_parallel_assignment_code(self, rhs, code):
5048 5049 5050
        # Need to work around the fact that generate_evaluation_code
        # allocates the temps in a rather hacky way -- the assignment
        # is evaluated twice, within each if-block.
5051 5052
        for item in self.unpacked_items:
            item.allocate(code)
5053 5054 5055
        special_unpack = (rhs.type is py_object_type
                          or rhs.type in (tuple_type, list_type)
                          or not rhs.type.is_builtin_type)
5056
        long_enough_for_a_loop = len(self.unpacked_items) > 3
5057

5058
        if special_unpack:
5059 5060
            self.generate_special_parallel_unpacking_code(
                code, rhs, use_loop=long_enough_for_a_loop)
5061
        code.putln("{")
Stefan Behnel's avatar
Stefan Behnel committed
5062 5063
        self.generate_generic_parallel_unpacking_code(
            code, rhs, self.unpacked_items, use_loop=long_enough_for_a_loop)
5064
        code.putln("}")
5065

5066 5067
        for value_node in self.coerced_unpacked_items:
            value_node.generate_evaluation_code(code)
5068 5069 5070
        for i in range(len(self.args)):
            self.args[i].generate_assignment_code(
                self.coerced_unpacked_items[i], code)
5071

5072
    def generate_special_parallel_unpacking_code(self, code, rhs, use_loop):
5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086
        tuple_check = 'likely(PyTuple_CheckExact(%s))' % rhs.py_result()
        list_check  = 'PyList_CheckExact(%s)' % rhs.py_result()
        sequence_type_test = '1'
        if rhs.type is list_type:
            sequence_types = ['List']
            if rhs.may_be_none():
                sequence_type_test = list_check
        elif rhs.type is tuple_type:
            sequence_types = ['Tuple']
            if rhs.may_be_none():
                sequence_type_test = tuple_check
        else:
            sequence_types = ['Tuple', 'List']
            sequence_type_test = "(%s) || (%s)" % (tuple_check, list_check)
5087

5088 5089
        code.putln("if (%s) {" % sequence_type_test)
        code.putln("PyObject* sequence = %s;" % rhs.py_result())
5090

Stefan Behnel's avatar
Stefan Behnel committed
5091
        # list/tuple => check size
5092
        code.putln("#if CYTHON_COMPILING_IN_CPYTHON")
5093
        code.putln("Py_ssize_t size = Py_SIZE(sequence);")
5094 5095 5096
        code.putln("#else")
        code.putln("Py_ssize_t size = PySequence_Size(sequence);")  # < 0 => exception
        code.putln("#endif")
5097 5098 5099 5100 5101
        code.putln("if (unlikely(size != %d)) {" % len(self.args))
        code.globalstate.use_utility_code(raise_too_many_values_to_unpack)
        code.putln("if (size > %d) __Pyx_RaiseTooManyValuesError(%d);" % (
            len(self.args), len(self.args)))
        code.globalstate.use_utility_code(raise_need_more_values_to_unpack)
5102
        code.putln("else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size);")
5103 5104
        code.putln(code.error_goto(self.pos))
        code.putln("}")
Robert Bradshaw's avatar
Robert Bradshaw committed
5105

5106
        code.putln("#if CYTHON_COMPILING_IN_CPYTHON")
5107 5108 5109 5110 5111 5112 5113 5114
        # unpack items from list/tuple in unrolled loop (can't fail)
        if len(sequence_types) == 2:
            code.putln("if (likely(Py%s_CheckExact(sequence))) {" % sequence_types[0])
        for i, item in enumerate(self.unpacked_items):
            code.putln("%s = Py%s_GET_ITEM(sequence, %d); " % (
                item.result(), sequence_types[0], i))
        if len(sequence_types) == 2:
            code.putln("} else {")
5115
            for i, item in enumerate(self.unpacked_items):
5116 5117 5118 5119 5120
                code.putln("%s = Py%s_GET_ITEM(sequence, %d); " % (
                    item.result(), sequence_types[1], i))
            code.putln("}")
        for item in self.unpacked_items:
            code.put_incref(item.result(), item.ctype())
5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140

        code.putln("#else")
        # in non-CPython, use the PySequence protocol (which can fail)
        if not use_loop:
            for i, item in enumerate(self.unpacked_items):
                code.putln("%s = PySequence_ITEM(sequence, %d); %s" % (
                    item.result(), i,
                    code.error_goto_if_null(item.result(), self.pos)))
        else:
            code.putln("Py_ssize_t i;")
            code.putln("PyObject** temps[%s] = {%s};" % (
                len(self.unpacked_items),
                ','.join(['&%s' % item.result() for item in self.unpacked_items])))
            code.putln("for (i=0; i < %s; i++) {" % len(self.unpacked_items))
            code.putln("PyObject* item = PySequence_ITEM(sequence, i); %s" % (
                code.error_goto_if_null('item', self.pos)))
            code.putln("*(temps[i]) = item;")
            code.putln("}")

        code.putln("#endif")
5141 5142 5143 5144 5145 5146 5147 5148 5149
        rhs.generate_disposal_code(code)

        if rhs.type is tuple_type:
            # if not a tuple: None => save some code by generating the error directly
            code.putln("} else if (1) {")
            code.globalstate.use_utility_code(
                UtilityCode.load_cached("RaiseNoneIterError", "ObjectHandling.c"))
            code.putln("__Pyx_RaiseNoneNotIterableError(); %s" % code.error_goto(self.pos))
        code.putln("} else")
5150

5151
    def generate_generic_parallel_unpacking_code(self, code, rhs, unpacked_items, use_loop, terminate=True):
5152
        code.globalstate.use_utility_code(raise_need_more_values_to_unpack)
5153
        code.globalstate.use_utility_code(UtilityCode.load_cached("IterFinish", "ObjectHandling.c"))
5154
        code.putln("Py_ssize_t index = -1;") # must be at the start of a C block!
5155

5156 5157 5158
        if use_loop:
            code.putln("PyObject** temps[%s] = {%s};" % (
                len(self.unpacked_items),
5159
                ','.join(['&%s' % item.result() for item in unpacked_items])))
5160

5161 5162 5163 5164 5165 5166 5167 5168
        iterator_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
        code.putln(
            "%s = PyObject_GetIter(%s); %s" % (
                iterator_temp,
                rhs.py_result(),
                code.error_goto_if_null(iterator_temp, self.pos)))
        code.put_gotref(iterator_temp)
        rhs.generate_disposal_code(code)
5169

5170 5171 5172
        iternext_func = code.funcstate.allocate_temp(self._func_iternext_type, manage_ref=False)
        code.putln("%s = Py_TYPE(%s)->tp_iternext;" % (
            iternext_func, iterator_temp))
William Stein's avatar
William Stein committed
5173

5174 5175
        unpacking_error_label = code.new_label('unpacking_failed')
        unpack_code = "%s(%s)" % (iternext_func, iterator_temp)
5176
        if use_loop:
5177
            code.putln("for (index=0; index < %s; index++) {" % len(unpacked_items))
5178 5179 5180 5181 5182 5183
            code.put("PyObject* item = %s; if (unlikely(!item)) " % unpack_code)
            code.put_goto(unpacking_error_label)
            code.put_gotref("item")
            code.putln("*(temps[index]) = item;")
            code.putln("}")
        else:
5184
            for i, item in enumerate(unpacked_items):
5185 5186 5187 5188 5189 5190 5191 5192
                code.put(
                    "index = %d; %s = %s; if (unlikely(!%s)) " % (
                        i,
                        item.result(),
                        unpack_code,
                        item.result()))
                code.put_goto(unpacking_error_label)
                code.put_gotref(item.py_result())
5193 5194

        if terminate:
5195 5196
            code.globalstate.use_utility_code(
                UtilityCode.load_cached("UnpackItemEndCheck", "ObjectHandling.c"))
5197 5198 5199 5200 5201 5202
            code.put_error_if_neg(self.pos, "__Pyx_IternextUnpackEndCheck(%s, %d)" % (
                unpack_code,
                len(unpacked_items)))
            code.putln("%s = NULL;" % iternext_func)
            code.put_decref_clear(iterator_temp, py_object_type)

5203 5204 5205 5206 5207
        unpacking_done_label = code.new_label('unpacking_done')
        code.put_goto(unpacking_done_label)

        code.put_label(unpacking_error_label)
        code.put_decref_clear(iterator_temp, py_object_type)
5208
        code.putln("%s = NULL;" % iternext_func)
5209
        code.putln("if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index);")
5210 5211
        code.putln(code.error_goto(self.pos))
        code.put_label(unpacking_done_label)
5212

5213 5214 5215 5216 5217 5218 5219
        code.funcstate.release_temp(iternext_func)
        if terminate:
            code.funcstate.release_temp(iterator_temp)
            iterator_temp = None

        return iterator_temp

5220 5221 5222 5223
    def generate_starred_assignment_code(self, rhs, code):
        for i, arg in enumerate(self.args):
            if arg.is_starred:
                starred_target = self.unpacked_items[i]
5224 5225
                unpacked_fixed_items_left  = self.unpacked_items[:i]
                unpacked_fixed_items_right = self.unpacked_items[i+1:]
5226
                break
5227 5228
        else:
            assert False
5229

5230 5231
        iterator_temp = None
        if unpacked_fixed_items_left:
5232
            for item in unpacked_fixed_items_left:
5233
                item.allocate(code)
5234 5235 5236 5237 5238
            code.putln('{')
            iterator_temp = self.generate_generic_parallel_unpacking_code(
                code, rhs, unpacked_fixed_items_left,
                use_loop=True, terminate=False)
            for i, item in enumerate(unpacked_fixed_items_left):
5239 5240
                value_node = self.coerced_unpacked_items[i]
                value_node.generate_evaluation_code(code)
5241
            code.putln('}')
5242

5243
        starred_target.allocate(code)
5244 5245
        target_list = starred_target.result()
        code.putln("%s = PySequence_List(%s); %s" % (
5246 5247
            target_list,
            iterator_temp or rhs.py_result(),
5248 5249
            code.error_goto_if_null(target_list, self.pos)))
        code.put_gotref(target_list)
5250 5251 5252 5253 5254 5255 5256 5257

        if iterator_temp:
            code.put_decref_clear(iterator_temp, py_object_type)
            code.funcstate.release_temp(iterator_temp)
        else:
            rhs.generate_disposal_code(code)

        if unpacked_fixed_items_right:
5258
            code.globalstate.use_utility_code(raise_need_more_values_to_unpack)
5259 5260 5261 5262 5263 5264
            length_temp = code.funcstate.allocate_temp(PyrexTypes.c_py_ssize_t_type, manage_ref=False)
            code.putln('%s = PyList_GET_SIZE(%s);' % (length_temp, target_list))
            code.putln("if (unlikely(%s < %d)) {" % (length_temp, len(unpacked_fixed_items_right)))
            code.putln("__Pyx_RaiseNeedMoreValuesError(%d+%s); %s" % (
                 len(unpacked_fixed_items_left), length_temp,
                 code.error_goto(self.pos)))
5265
            code.putln('}')
5266 5267 5268 5269 5270

            for item in unpacked_fixed_items_right[::-1]:
                item.allocate(code)
            for i, (item, coerced_arg) in enumerate(zip(unpacked_fixed_items_right[::-1],
                                                        self.coerced_unpacked_items[::-1])):
5271 5272 5273
                code.putln('#if CYTHON_COMPILING_IN_CPYTHON')
                code.putln("%s = PyList_GET_ITEM(%s, %s-%d); " % (
                    item.py_result(), target_list, length_temp, i+1))
5274
                # resize the list the hard way
5275
                code.putln("((PyVarObject*)%s)->ob_size--;" % target_list)
5276
                code.putln('#else')
5277
                code.putln("%s = PySequence_ITEM(%s, %s-%d); " % (
5278 5279
                    item.py_result(), target_list, length_temp, i+1))
                code.putln('#endif')
5280
                code.put_gotref(item.py_result())
5281 5282
                coerced_arg.generate_evaluation_code(code)

5283
            code.putln('#if !CYTHON_COMPILING_IN_CPYTHON')
5284
            sublist_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
Stefan Behnel's avatar
Stefan Behnel committed
5285
            code.putln('%s = PySequence_GetSlice(%s, 0, %s-%d); %s' % (
5286 5287 5288 5289 5290 5291
                sublist_temp, target_list, length_temp, len(unpacked_fixed_items_right),
                code.error_goto_if_null(sublist_temp, self.pos)))
            code.put_gotref(sublist_temp)
            code.funcstate.release_temp(length_temp)
            code.put_decref(target_list, py_object_type)
            code.putln('%s = %s; %s = NULL;' % (target_list, sublist_temp, sublist_temp))
5292 5293
            code.putln('#else')
            code.putln('%s = %s;' % (sublist_temp, sublist_temp)) # avoid warning about unused variable
5294 5295 5296 5297 5298
            code.funcstate.release_temp(sublist_temp)
            code.putln('#endif')

        for i, arg in enumerate(self.args):
            arg.generate_assignment_code(self.coerced_unpacked_items[i], code)
5299

5300 5301 5302 5303 5304 5305 5306 5307
    def annotate(self, code):
        for arg in self.args:
            arg.annotate(code)
        if self.unpacked_items:
            for arg in self.unpacked_items:
                arg.annotate(code)
            for arg in self.coerced_unpacked_items:
                arg.annotate(code)
William Stein's avatar
William Stein committed
5308 5309 5310 5311


class TupleNode(SequenceNode):
    #  Tuple constructor.
5312

5313
    type = tuple_type
5314
    is_partly_literal = False
5315 5316 5317

    gil_message = "Constructing Python tuple"

5318
    def analyse_types(self, env, skip_children=False):
Robert Bradshaw's avatar
Robert Bradshaw committed
5319
        if len(self.args) == 0:
5320 5321
            self.is_temp = False
            self.is_literal = True
Robert Bradshaw's avatar
Robert Bradshaw committed
5322
        else:
5323
            SequenceNode.analyse_types(self, env, skip_children)
5324 5325 5326 5327
            for child in self.args:
                if not child.is_literal:
                    break
            else:
5328 5329 5330 5331 5332
                if not self.mult_factor or self.mult_factor.is_literal and \
                       isinstance(self.mult_factor.constant_result, (int, long)):
                    self.is_temp = False
                    self.is_literal = True
                else:
5333 5334
                    if not self.mult_factor.type.is_pyobject:
                        self.mult_factor = self.mult_factor.coerce_to_pyobject(env)
5335 5336
                    self.is_temp = True
                    self.is_partly_literal = True
5337

Stefan Behnel's avatar
Stefan Behnel committed
5338 5339 5340 5341
    def is_simple(self):
        # either temp or constant => always simple
        return True

5342 5343 5344 5345
    def nonlocally_immutable(self):
        # either temp or constant => always safe
        return True

Robert Bradshaw's avatar
Robert Bradshaw committed
5346 5347
    def calculate_result_code(self):
        if len(self.args) > 0:
5348
            return self.result_code
Robert Bradshaw's avatar
Robert Bradshaw committed
5349 5350
        else:
            return Naming.empty_tuple
William Stein's avatar
William Stein committed
5351

5352 5353 5354 5355
    def calculate_constant_result(self):
        self.constant_result = tuple([
                arg.constant_result for arg in self.args])

5356 5357 5358 5359 5360 5361
    def compile_time_value(self, denv):
        values = self.compile_time_value_list(denv)
        try:
            return tuple(values)
        except Exception, e:
            self.compile_time_value_error(e)
5362

William Stein's avatar
William Stein committed
5363
    def generate_operation_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
5364 5365 5366
        if len(self.args) == 0:
            # result_code is Naming.empty_tuple
            return
5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379
        if self.is_partly_literal:
            # underlying tuple is const, but factor is not
            tuple_target = code.get_py_const(py_object_type, 'tuple_', cleanup_level=2)
            const_code = code.get_cached_constants_writer()
            const_code.mark_pos(self.pos)
            self.generate_sequence_packing_code(const_code, tuple_target, plain=True)
            const_code.put_giveref(tuple_target)
            code.putln('%s = PyNumber_Multiply(%s, %s); %s' % (
                self.result(), tuple_target, self.mult_factor.py_result(),
                code.error_goto_if_null(self.result(), self.pos)
                ))
            code.put_gotref(self.py_result())
        elif self.is_literal:
5380 5381
            # non-empty cached tuple => result is global constant,
            # creation code goes into separate code writer
5382
            self.result_code = code.get_py_const(py_object_type, 'tuple_', cleanup_level=2)
5383 5384
            code = code.get_cached_constants_writer()
            code.mark_pos(self.pos)
5385
            self.generate_sequence_packing_code(code)
5386
            code.put_giveref(self.py_result())
5387 5388
        else:
            self.generate_sequence_packing_code(code)
William Stein's avatar
William Stein committed
5389 5390 5391 5392


class ListNode(SequenceNode):
    #  List constructor.
5393

5394 5395
    # obj_conversion_errors    [PyrexError]   used internally
    # orignial_args            [ExprNode]     used internally
5396

5397
    obj_conversion_errors = []
Stefan Behnel's avatar
Stefan Behnel committed
5398
    type = list_type
5399

5400
    gil_message = "Constructing Python list"
5401

Robert Bradshaw's avatar
Robert Bradshaw committed
5402
    def type_dependencies(self, env):
5403
        return ()
5404

5405 5406 5407
    def infer_type(self, env):
        # TOOD: Infer non-object list arrays.
        return list_type
5408

5409
    def analyse_expressions(self, env):
5410
        SequenceNode.analyse_expressions(self, env)
5411 5412
        self.coerce_to_pyobject(env)

Robert Bradshaw's avatar
Robert Bradshaw committed
5413
    def analyse_types(self, env):
5414 5415 5416 5417 5418
        hold_errors()
        self.original_args = list(self.args)
        SequenceNode.analyse_types(self, env)
        self.obj_conversion_errors = held_errors()
        release_errors(ignore=True)
5419

Robert Bradshaw's avatar
Robert Bradshaw committed
5420 5421
    def coerce_to(self, dst_type, env):
        if dst_type.is_pyobject:
5422 5423 5424
            for err in self.obj_conversion_errors:
                report_error(err)
            self.obj_conversion_errors = []
Robert Bradshaw's avatar
Robert Bradshaw committed
5425 5426
            if not self.type.subtype_of(dst_type):
                error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
5427 5428
        elif self.mult_factor:
            error(self.pos, "Cannot coerce multiplied list to '%s'" % dst_type)
5429
        elif dst_type.is_ptr and dst_type.base_type is not PyrexTypes.c_void_type:
Robert Bradshaw's avatar
Robert Bradshaw committed
5430
            base_type = dst_type.base_type
Robert Bradshaw's avatar
Robert Bradshaw committed
5431
            self.type = PyrexTypes.CArrayType(base_type, len(self.args))
5432
            for i in range(len(self.original_args)):
Robert Bradshaw's avatar
Robert Bradshaw committed
5433
                arg = self.args[i]
5434 5435
                if isinstance(arg, CoerceToPyTypeNode):
                    arg = arg.arg
Robert Bradshaw's avatar
Robert Bradshaw committed
5436
                self.args[i] = arg.coerce_to(base_type, env)
Robert Bradshaw's avatar
Robert Bradshaw committed
5437 5438 5439 5440 5441 5442
        elif dst_type.is_struct:
            if len(self.args) > len(dst_type.scope.var_entries):
                error(self.pos, "Too may members for '%s'" % dst_type)
            else:
                if len(self.args) < len(dst_type.scope.var_entries):
                    warning(self.pos, "Too few members for '%s'" % dst_type, 1)
5443 5444 5445
                for i, (arg, member) in enumerate(zip(self.original_args, dst_type.scope.var_entries)):
                    if isinstance(arg, CoerceToPyTypeNode):
                        arg = arg.arg
Robert Bradshaw's avatar
Robert Bradshaw committed
5446 5447
                    self.args[i] = arg.coerce_to(member.type, env)
            self.type = dst_type
Robert Bradshaw's avatar
Robert Bradshaw committed
5448 5449 5450 5451
        else:
            self.type = error_type
            error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
        return self
5452

Robert Bradshaw's avatar
Robert Bradshaw committed
5453 5454
    def release_temp(self, env):
        if self.type.is_array:
5455 5456
            # To be valid C++, we must allocate the memory on the stack
            # manually and be sure not to reuse it for something else.
Robert Bradshaw's avatar
Robert Bradshaw committed
5457 5458 5459
            pass
        else:
            SequenceNode.release_temp(self, env)
Robert Bradshaw's avatar
Robert Bradshaw committed
5460

5461
    def calculate_constant_result(self):
5462 5463
        if self.mult_factor:
            raise ValueError() # may exceed the compile time memory
5464 5465 5466
        self.constant_result = [
            arg.constant_result for arg in self.args]

5467
    def compile_time_value(self, denv):
5468 5469 5470 5471
        l = self.compile_time_value_list(denv)
        if self.mult_factor:
            l *= self.mult_factor.compile_time_value(denv)
        return l
5472

William Stein's avatar
William Stein committed
5473
    def generate_operation_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
5474
        if self.type.is_pyobject:
5475 5476
            for err in self.obj_conversion_errors:
                report_error(err)
5477
            self.generate_sequence_packing_code(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
5478 5479 5480 5481 5482 5483
        elif self.type.is_array:
            for i, arg in enumerate(self.args):
                code.putln("%s[%s] = %s;" % (
                                self.result(),
                                i,
                                arg.result()))
Robert Bradshaw's avatar
Robert Bradshaw committed
5484
        elif self.type.is_struct:
Robert Bradshaw's avatar
Robert Bradshaw committed
5485 5486 5487 5488 5489
            for arg, member in zip(self.args, self.type.scope.var_entries):
                code.putln("%s.%s = %s;" % (
                        self.result(),
                        member.cname,
                        arg.result()))
5490 5491
        else:
            raise InternalError("List type never specified")
5492

Robert Bradshaw's avatar
Robert Bradshaw committed
5493

5494 5495 5496 5497 5498 5499 5500 5501 5502
class ScopedExprNode(ExprNode):
    # Abstract base class for ExprNodes that have their own local
    # scope, such as generator expressions.
    #
    # expr_scope    Scope  the inner scope of the expression

    subexprs = []
    expr_scope = None

5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521
    # does this node really have a local scope, e.g. does it leak loop
    # variables or not?  non-leaking Py3 behaviour is default, except
    # for list comprehensions where the behaviour differs in Py2 and
    # Py3 (set in Parsing.py based on parser context)
    has_local_scope = True

    def init_scope(self, outer_scope, expr_scope=None):
        if expr_scope is not None:
            self.expr_scope = expr_scope
        elif self.has_local_scope:
            self.expr_scope = Symtab.GeneratorExpressionScope(outer_scope)
        else:
            self.expr_scope = None

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

    def analyse_scoped_declarations(self, env):
        # this is called with the expr_scope as env
5522 5523
        pass

5524 5525
    def analyse_types(self, env):
        # no recursion here, the children will be analysed separately below
5526 5527 5528 5529 5530 5531
        pass

    def analyse_scoped_expressions(self, env):
        # this is called with the expr_scope as env
        pass

5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578
    def generate_evaluation_code(self, code):
        # set up local variables and free their references on exit
        generate_inner_evaluation_code = super(ScopedExprNode, self).generate_evaluation_code
        if not self.has_local_scope or not self.expr_scope.var_entries:
            # no local variables => delegate, done
            generate_inner_evaluation_code(code)
            return

        code.putln('{ /* enter inner scope */')
        py_entries = []
        for entry in self.expr_scope.var_entries:
            if not entry.in_closure:
                code.put_var_declaration(entry)
                if entry.type.is_pyobject and entry.used:
                    py_entries.append(entry)
        if not py_entries:
            # no local Python references => no cleanup required
            generate_inner_evaluation_code(code)
            code.putln('} /* exit inner scope */')
            return

        # must free all local Python references at each exit point
        old_loop_labels = tuple(code.new_loop_labels())
        old_error_label = code.new_error_label()

        generate_inner_evaluation_code(code)

        # normal (non-error) exit
        for entry in py_entries:
            code.put_var_decref(entry)

        # error/loop body exit points
        exit_scope = code.new_label('exit_scope')
        code.put_goto(exit_scope)
        for label, old_label in ([(code.error_label, old_error_label)] +
                                 list(zip(code.get_loop_labels(), old_loop_labels))):
            if code.label_used(label):
                code.put_label(label)
                for entry in py_entries:
                    code.put_var_decref(entry)
                code.put_goto(old_label)
        code.put_label(exit_scope)
        code.putln('} /* exit inner scope */')

        code.set_loop_labels(old_loop_labels)
        code.error_label = old_error_label

5579 5580

class ComprehensionNode(ScopedExprNode):
5581
    subexprs = ["target"]
5582
    child_attrs = ["loop"]
5583

5584 5585
    def infer_type(self, env):
        return self.target.infer_type(env)
5586 5587 5588

    def analyse_declarations(self, env):
        self.append.target = self # this is used in the PyList_Append of the inner loop
5589 5590
        self.init_scope(env)

5591 5592
    def analyse_scoped_declarations(self, env):
        self.loop.analyse_declarations(env)
5593

5594 5595 5596
    def analyse_types(self, env):
        self.target.analyse_expressions(env)
        self.type = self.target.type
5597 5598
        if not self.has_local_scope:
            self.loop.analyse_expressions(env)
5599

5600 5601 5602
    def analyse_scoped_expressions(self, env):
        if self.has_local_scope:
            self.loop.analyse_expressions(env)
5603

5604 5605 5606
    def may_be_none(self):
        return False

5607 5608
    def calculate_result_code(self):
        return self.target.result()
5609

5610 5611
    def generate_result_code(self, code):
        self.generate_operation_code(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
5612

5613 5614 5615
    def generate_operation_code(self, code):
        self.loop.generate_execution_code(code)

5616 5617
    def annotate(self, code):
        self.loop.annotate(code)
5618 5619


5620
class ComprehensionAppendNode(Node):
5621 5622
    # Need to be careful to avoid infinite recursion:
    # target must not be in child_attrs/subexprs
5623 5624

    child_attrs = ['expr']
5625 5626

    type = PyrexTypes.c_int_type
5627

5628 5629
    def analyse_expressions(self, env):
        self.expr.analyse_expressions(env)
5630
        if not self.expr.type.is_pyobject:
Robert Bradshaw's avatar
Robert Bradshaw committed
5631
            self.expr = self.expr.coerce_to_pyobject(env)
5632

5633
    def generate_execution_code(self, code):
5634
        if self.target.type is list_type:
5635 5636
            code.globalstate.use_utility_code(UtilityCode.load_cached("InternalListAppend", "Optimize.c"))
            function = "__Pyx_PyList_Append"
5637 5638 5639 5640 5641
        elif self.target.type is set_type:
            function = "PySet_Add"
        else:
            raise InternalError(
                "Invalid type for comprehension node: %s" % self.target.type)
5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656

        self.expr.generate_evaluation_code(code)
        code.putln(code.error_goto_if("%s(%s, (PyObject*)%s)" % (
            function,
            self.target.result(),
            self.expr.result()
            ), self.pos))
        self.expr.generate_disposal_code(code)
        self.expr.free_temps(code)

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

    def annotate(self, code):
        self.expr.annotate(code)
5657 5658

class DictComprehensionAppendNode(ComprehensionAppendNode):
5659
    child_attrs = ['key_expr', 'value_expr']
5660

5661 5662
    def analyse_expressions(self, env):
        self.key_expr.analyse_expressions(env)
5663 5664
        if not self.key_expr.type.is_pyobject:
            self.key_expr = self.key_expr.coerce_to_pyobject(env)
5665
        self.value_expr.analyse_expressions(env)
5666 5667 5668
        if not self.value_expr.type.is_pyobject:
            self.value_expr = self.value_expr.coerce_to_pyobject(env)

5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688
    def generate_execution_code(self, code):
        self.key_expr.generate_evaluation_code(code)
        self.value_expr.generate_evaluation_code(code)
        code.putln(code.error_goto_if("PyDict_SetItem(%s, (PyObject*)%s, (PyObject*)%s)" % (
            self.target.result(),
            self.key_expr.result(),
            self.value_expr.result()
            ), self.pos))
        self.key_expr.generate_disposal_code(code)
        self.key_expr.free_temps(code)
        self.value_expr.generate_disposal_code(code)
        self.value_expr.free_temps(code)

    def generate_function_definitions(self, env, code):
        self.key_expr.generate_function_definitions(env, code)
        self.value_expr.generate_function_definitions(env, code)

    def annotate(self, code):
        self.key_expr.annotate(code)
        self.value_expr.annotate(code)
5689 5690


5691 5692 5693 5694 5695
class InlinedGeneratorExpressionNode(ScopedExprNode):
    # An inlined generator expression for which the result is
    # calculated inside of the loop.  This will only be created by
    # transforms when replacing builtin calls on generator
    # expressions.
5696
    #
5697 5698 5699
    # loop           ForStatNode      the for-loop, not containing any YieldExprNodes
    # result_node    ResultRefNode    the reference to the result value temp
    # orig_func      String           the name of the builtin function this node replaces
5700

5701
    child_attrs = ["loop"]
5702
    loop_analysed = False
5703 5704
    type = py_object_type

5705 5706
    def analyse_scoped_declarations(self, env):
        self.loop.analyse_declarations(env)
5707

5708 5709 5710 5711 5712 5713
    def may_be_none(self):
        return False

    def annotate(self, code):
        self.loop.annotate(code)

5714 5715
    def infer_type(self, env):
        return self.result_node.infer_type(env)
5716 5717

    def analyse_types(self, env):
5718 5719 5720
        if not self.has_local_scope:
            self.loop_analysed = True
            self.loop.analyse_expressions(env)
5721 5722 5723
        self.type = self.result_node.type
        self.is_temp = True

5724 5725
    def analyse_scoped_expressions(self, env):
        self.loop_analysed = True
5726 5727
        if self.has_local_scope:
            self.loop.analyse_expressions(env)
5728

5729
    def coerce_to(self, dst_type, env):
5730 5731 5732 5733 5734 5735
        if self.orig_func == 'sum' and dst_type.is_numeric and not self.loop_analysed:
            # We can optimise by dropping the aggregation variable and
            # the add operations into C.  This can only be done safely
            # before analysing the loop body, after that, the result
            # reference type will have infected expressions and
            # assignments.
5736 5737
            self.result_node.type = self.type = dst_type
            return self
5738
        return super(InlinedGeneratorExpressionNode, self).coerce_to(dst_type, env)
5739

5740 5741 5742 5743 5744
    def generate_result_code(self, code):
        self.result_node.result_code = self.result()
        self.loop.generate_execution_code(code)


5745
class SetNode(ExprNode):
5746 5747
    #  Set constructor.

5748 5749
    type = set_type

5750 5751 5752
    subexprs = ['args']

    gil_message = "Constructing Python set"
5753

5754 5755 5756 5757 5758 5759 5760 5761
    def analyse_types(self, env):
        for i in range(len(self.args)):
            arg = self.args[i]
            arg.analyse_types(env)
            self.args[i] = arg.coerce_to_pyobject(env)
        self.type = set_type
        self.is_temp = 1

5762 5763 5764
    def may_be_none(self):
        return False

5765 5766 5767 5768
    def calculate_constant_result(self):
        self.constant_result = set([
                arg.constant_result for arg in self.args])

5769 5770 5771 5772 5773 5774 5775 5776
    def compile_time_value(self, denv):
        values = [arg.compile_time_value(denv) for arg in self.args]
        try:
            return set(values)
        except Exception, e:
            self.compile_time_value_error(e)

    def generate_evaluation_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
5777
        code.globalstate.use_utility_code(Builtin.py_set_utility_code)
5778 5779 5780 5781 5782
        self.allocate_temp_result(code)
        code.putln(
            "%s = PySet_New(0); %s" % (
                self.result(),
                code.error_goto_if_null(self.result(), self.pos)))
5783
        code.put_gotref(self.py_result())
5784 5785 5786 5787 5788 5789 5790 5791
        for arg in self.args:
            arg.generate_evaluation_code(code)
            code.putln(
                code.error_goto_if_neg(
                    "PySet_Add(%s, %s)" % (self.result(), arg.py_result()),
                    self.pos))
            arg.generate_disposal_code(code)
            arg.free_temps(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
5792

William Stein's avatar
William Stein committed
5793

5794
class DictNode(ExprNode):
William Stein's avatar
William Stein committed
5795 5796
    #  Dictionary constructor.
    #
Vitja Makarov's avatar
Vitja Makarov committed
5797 5798
    #  key_value_pairs     [DictItemNode]
    #  exclude_null_values [boolean]          Do not add NULL values to dict
5799 5800
    #
    # obj_conversion_errors    [PyrexError]   used internally
5801

5802
    subexprs = ['key_value_pairs']
5803
    is_temp = 1
Vitja Makarov's avatar
Vitja Makarov committed
5804
    exclude_null_values = False
5805
    type = dict_type
5806

5807
    obj_conversion_errors = []
5808

5809 5810 5811 5812 5813
    @classmethod
    def from_pairs(cls, pos, pairs):
        return cls(pos, key_value_pairs=[
                DictItemNode(pos, key=k, value=v) for k, v in pairs])

5814 5815 5816
    def calculate_constant_result(self):
        self.constant_result = dict([
                item.constant_result for item in self.key_value_pairs])
5817

5818
    def compile_time_value(self, denv):
Robert Bradshaw's avatar
Robert Bradshaw committed
5819 5820
        pairs = [(item.key.compile_time_value(denv), item.value.compile_time_value(denv))
            for item in self.key_value_pairs]
5821 5822 5823 5824
        try:
            return dict(pairs)
        except Exception, e:
            self.compile_time_value_error(e)
5825

Robert Bradshaw's avatar
Robert Bradshaw committed
5826
    def type_dependencies(self, env):
5827
        return ()
5828

5829 5830 5831 5832
    def infer_type(self, env):
        # TOOD: Infer struct constructors.
        return dict_type

William Stein's avatar
William Stein committed
5833
    def analyse_types(self, env):
5834
        hold_errors()
Robert Bradshaw's avatar
Robert Bradshaw committed
5835 5836
        for item in self.key_value_pairs:
            item.analyse_types(env)
5837 5838
        self.obj_conversion_errors = held_errors()
        release_errors(ignore=True)
5839 5840 5841

    def may_be_none(self):
        return False
5842

5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856
    def coerce_to(self, dst_type, env):
        if dst_type.is_pyobject:
            self.release_errors()
            if not self.type.subtype_of(dst_type):
                error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
        elif dst_type.is_struct_or_union:
            self.type = dst_type
            if not dst_type.is_struct and len(self.key_value_pairs) != 1:
                error(self.pos, "Exactly one field must be specified to convert to union '%s'" % dst_type)
            elif dst_type.is_struct and len(self.key_value_pairs) < len(dst_type.scope.var_entries):
                warning(self.pos, "Not all members given for struct '%s'" % dst_type, 1)
            for item in self.key_value_pairs:
                if isinstance(item.key, CoerceToPyTypeNode):
                    item.key = item.key.arg
5857
                if not item.key.is_string_literal:
5858
                    error(item.key.pos, "Invalid struct field identifier")
5859
                    item.key = StringNode(item.key.pos, value="<error>")
5860
                else:
Stefan Behnel's avatar
Stefan Behnel committed
5861 5862
                    key = str(item.key.value) # converts string literals to unicode in Py3
                    member = dst_type.scope.lookup_here(key)
5863
                    if not member:
Stefan Behnel's avatar
Stefan Behnel committed
5864
                        error(item.key.pos, "struct '%s' has no field '%s'" % (dst_type, key))
5865 5866 5867 5868 5869 5870 5871 5872 5873
                    else:
                        value = item.value
                        if isinstance(value, CoerceToPyTypeNode):
                            value = value.arg
                        item.value = value.coerce_to(member.type, env)
        else:
            self.type = error_type
            error(self.pos, "Cannot interpret dict as type '%s'" % dst_type)
        return self
5874

5875 5876 5877 5878
    def release_errors(self):
        for err in self.obj_conversion_errors:
            report_error(err)
        self.obj_conversion_errors = []
5879 5880 5881

    gil_message = "Constructing Python dict"

William Stein's avatar
William Stein committed
5882 5883 5884
    def generate_evaluation_code(self, code):
        #  Custom method used here because key-value
        #  pairs are evaluated and used one at a time.
5885 5886
        code.mark_pos(self.pos)
        self.allocate_temp_result(code)
5887 5888 5889 5890 5891 5892
        if self.type.is_pyobject:
            self.release_errors()
            code.putln(
                "%s = PyDict_New(); %s" % (
                    self.result(),
                    code.error_goto_if_null(self.result(), self.pos)))
5893
            code.put_gotref(self.py_result())
Robert Bradshaw's avatar
Robert Bradshaw committed
5894 5895
        for item in self.key_value_pairs:
            item.generate_evaluation_code(code)
5896
            if self.type.is_pyobject:
Vitja Makarov's avatar
Vitja Makarov committed
5897 5898
                if self.exclude_null_values:
                    code.putln('if (%s) {' % item.value.py_result())
5899
                code.put_error_if_neg(self.pos,
5900 5901 5902 5903
                    "PyDict_SetItem(%s, %s, %s)" % (
                        self.result(),
                        item.key.py_result(),
                        item.value.py_result()))
Vitja Makarov's avatar
Vitja Makarov committed
5904 5905
                if self.exclude_null_values:
                    code.putln('}')
5906 5907 5908
            else:
                code.putln("%s.%s = %s;" % (
                        self.result(),
5909
                        item.key.value,
5910
                        item.value.result()))
Robert Bradshaw's avatar
Robert Bradshaw committed
5911
            item.generate_disposal_code(code)
5912
            item.free_temps(code)
5913

5914
    def annotate(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
5915 5916
        for item in self.key_value_pairs:
            item.annotate(code)
5917

5918
class DictItemNode(ExprNode):
Robert Bradshaw's avatar
Robert Bradshaw committed
5919 5920 5921 5922 5923
    # Represents a single item in a DictNode
    #
    # key          ExprNode
    # value        ExprNode
    subexprs = ['key', 'value']
5924

5925
    nogil_check = None # Parent DictNode takes care of it
5926

5927 5928 5929
    def calculate_constant_result(self):
        self.constant_result = (
            self.key.constant_result, self.value.constant_result)
5930

Robert Bradshaw's avatar
Robert Bradshaw committed
5931 5932 5933 5934 5935
    def analyse_types(self, env):
        self.key.analyse_types(env)
        self.value.analyse_types(env)
        self.key = self.key.coerce_to_pyobject(env)
        self.value = self.value.coerce_to_pyobject(env)
5936

Robert Bradshaw's avatar
Robert Bradshaw committed
5937 5938 5939
    def generate_evaluation_code(self, code):
        self.key.generate_evaluation_code(code)
        self.value.generate_evaluation_code(code)
Stefan Behnel's avatar
Stefan Behnel committed
5940

5941 5942 5943
    def generate_disposal_code(self, code):
        self.key.generate_disposal_code(code)
        self.value.generate_disposal_code(code)
5944 5945 5946 5947

    def free_temps(self, code):
        self.key.free_temps(code)
        self.value.free_temps(code)
5948

5949 5950
    def __iter__(self):
        return iter([self.key, self.value])
William Stein's avatar
William Stein committed
5951

5952

5953 5954 5955 5956 5957 5958 5959
class ModuleNameMixin(object):
    def set_mod_name(self, env):
        self.module_name = env.global_scope().qualified_name

    def get_py_mod_name(self, code):
        return code.get_py_string_const(
                 self.module_name, identifier=True)
Stefan Behnel's avatar
Stefan Behnel committed
5960

5961
class ClassNode(ExprNode, ModuleNameMixin):
William Stein's avatar
William Stein committed
5962 5963 5964 5965
    #  Helper class used in the implementation of Python
    #  class definitions. Constructs a class object given
    #  a name, tuple of bases and class dictionary.
    #
Stefan Behnel's avatar
Stefan Behnel committed
5966
    #  name         EncodedString      Name of the class
William Stein's avatar
William Stein committed
5967 5968 5969
    #  bases        ExprNode           Base class tuple
    #  dict         ExprNode           Class dict (not owned by this node)
    #  doc          ExprNode or None   Doc string
5970
    #  module_name  EncodedString      Name of defining module
5971

5972
    subexprs = ['bases', 'doc']
5973

William Stein's avatar
William Stein committed
5974 5975 5976 5977 5978 5979 5980
    def analyse_types(self, env):
        self.bases.analyse_types(env)
        if self.doc:
            self.doc.analyse_types(env)
            self.doc = self.doc.coerce_to_pyobject(env)
        self.type = py_object_type
        self.is_temp = 1
5981
        env.use_utility_code(UtilityCode.load_cached("CreateClass", "ObjectHandling.c"))
5982 5983
        #TODO(craig,haoyu) This should be moved to a better place
        self.set_mod_name(env)
5984

5985
    def may_be_none(self):
Stefan Behnel's avatar
Stefan Behnel committed
5986
        return True
5987

5988 5989
    gil_message = "Constructing Python class"

William Stein's avatar
William Stein committed
5990
    def generate_result_code(self, code):
5991
        cname = code.intern_identifier(self.name)
5992

William Stein's avatar
William Stein committed
5993
        if self.doc:
5994
            code.put_error_if_neg(self.pos,
Robert Bradshaw's avatar
Robert Bradshaw committed
5995
                'PyDict_SetItemString(%s, "__doc__", %s)' % (
William Stein's avatar
William Stein committed
5996
                    self.dict.py_result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
5997
                    self.doc.py_result()))
5998
        py_mod_name = self.get_py_mod_name(code)
William Stein's avatar
William Stein committed
5999
        code.putln(
6000
            '%s = __Pyx_CreateClass(%s, %s, %s, %s); %s' % (
6001
                self.result(),
William Stein's avatar
William Stein committed
6002 6003
                self.bases.py_result(),
                self.dict.py_result(),
6004
                cname,
6005
                py_mod_name,
6006
                code.error_goto_if_null(self.result(), self.pos)))
6007
        code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
6008

Stefan Behnel's avatar
Stefan Behnel committed
6009

6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027
class Py3ClassNode(ExprNode):
    #  Helper class used in the implementation of Python3+
    #  class definitions. Constructs a class object given
    #  a name, tuple of bases and class dictionary.
    #
    #  name         EncodedString      Name of the class
    #  dict         ExprNode           Class dict (not owned by this node)
    #  module_name  EncodedString      Name of defining module

    subexprs = []

    def analyse_types(self, env):
        self.type = py_object_type
        self.is_temp = 1

    def may_be_none(self):
        return True

6028
    gil_message = "Constructing Python class"
6029 6030

    def generate_result_code(self, code):
6031
        code.globalstate.use_utility_code(UtilityCode.load_cached("Py3ClassCreate", "ObjectHandling.c"))
6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044
        cname = code.intern_identifier(self.name)
        code.putln(
            '%s = __Pyx_Py3ClassCreate(%s, %s, %s, %s, %s); %s' % (
                self.result(),
                self.metaclass.result(),
                cname,
                self.bases.py_result(),
                self.dict.py_result(),
                self.mkw.py_result(),
                code.error_goto_if_null(self.result(), self.pos)))
        code.put_gotref(self.py_result())

class KeywordArgsNode(ExprNode):
6045
    #  Helper class for keyword arguments.
6046
    #
6047 6048
    #  starstar_arg      DictNode
    #  keyword_args      [DictItemNode]
6049

6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075
    subexprs = ['starstar_arg', 'keyword_args']
    is_temp = 1
    type = dict_type

    def calculate_constant_result(self):
        result = dict(self.starstar_arg.constant_result)
        for item in self.keyword_args:
            key, value = item.constant_result
            if key in result:
                raise ValueError("duplicate keyword argument found: %s" % key)
            result[key] = value
        self.constant_result = result

    def compile_time_value(self, denv):
        result = self.starstar_arg.compile_time_value(denv)
        pairs = [ (item.key.compile_time_value(denv), item.value.compile_time_value(denv))
                  for item in self.keyword_args ]
        try:
            result = dict(result)
            for key, value in pairs:
                if key in result:
                    raise ValueError("duplicate keyword argument found: %s" % key)
                result[key] = value
        except Exception, e:
            self.compile_time_value_error(e)
        return result
6076

6077 6078 6079 6080 6081
    def type_dependencies(self, env):
        return ()

    def infer_type(self, env):
        return dict_type
6082 6083

    def analyse_types(self, env):
6084 6085 6086 6087 6088 6089
        self.starstar_arg.analyse_types(env)
        self.starstar_arg = self.starstar_arg.coerce_to_pyobject(env).as_none_safe_node(
            # FIXME: CPython's error message starts with the runtime function name
            'argument after ** must be a mapping, not NoneType')
        for item in self.keyword_args:
            item.analyse_types(env)
6090

6091 6092
    def may_be_none(self):
        return False
6093

6094 6095 6096 6097 6098 6099 6100 6101 6102 6103
    gil_message = "Constructing Python dict"

    def generate_evaluation_code(self, code):
        code.mark_pos(self.pos)
        self.allocate_temp_result(code)
        self.starstar_arg.generate_evaluation_code(code)
        if self.starstar_arg.type is not Builtin.dict_type:
            # CPython supports calling functions with non-dicts, so do we
            code.putln('if (likely(PyDict_Check(%s))) {' %
                       self.starstar_arg.py_result())
6104 6105 6106 6107 6108 6109
        if self.keyword_args:
            code.putln(
                "%s = PyDict_Copy(%s); %s" % (
                    self.result(),
                    self.starstar_arg.py_result(),
                    code.error_goto_if_null(self.result(), self.pos)))
6110
            code.put_gotref(self.py_result())
6111
        else:
6112 6113 6114 6115 6116 6117
            code.putln("%s = %s;" % (
                self.result(),
                self.starstar_arg.py_result()))
            code.put_incref(self.result(), py_object_type)
        if self.starstar_arg.type is not Builtin.dict_type:
            code.putln('} else {')
6118
            code.putln(
6119 6120
                "%s = PyObject_CallFunctionObjArgs("
                "(PyObject*)&PyDict_Type, %s, NULL); %s" % (
6121
                    self.result(),
6122
                    self.starstar_arg.py_result(),
6123
                    code.error_goto_if_null(self.result(), self.pos)))
6124
            code.put_gotref(self.py_result())
6125 6126 6127 6128 6129 6130 6131
            code.putln('}')
        self.starstar_arg.generate_disposal_code(code)
        self.starstar_arg.free_temps(code)

        if not self.keyword_args:
            return

6132 6133
        code.globalstate.use_utility_code(
            UtilityCode.load_cached("RaiseDoubleKeywords", "FunctionArguments.c"))
6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155
        for item in self.keyword_args:
            item.generate_evaluation_code(code)
            code.putln("if (unlikely(PyDict_GetItem(%s, %s))) {" % (
                    self.result(),
                    item.key.py_result()))
            # FIXME: find out function name at runtime!
            code.putln('__Pyx_RaiseDoubleKeywordsError("function", %s); %s' % (
                item.key.py_result(),
                code.error_goto(self.pos)))
            code.putln("}")
            code.put_error_if_neg(self.pos,
                "PyDict_SetItem(%s, %s, %s)" % (
                    self.result(),
                    item.key.py_result(),
                    item.value.py_result()))
            item.generate_disposal_code(code)
            item.free_temps(code)

    def annotate(self, code):
        self.starstar_arg.annotate(code)
        for item in self.keyword_args:
            item.annotate(code)
6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172

class PyClassMetaclassNode(ExprNode):
    # Helper class holds Python3 metaclass object
    #
    #  bases        ExprNode           Base class tuple (not owned by this node)
    #  mkw          ExprNode           Class keyword arguments (not owned by this node)

    subexprs = []

    def analyse_types(self, env):
        self.type = py_object_type
        self.is_temp = True

    def may_be_none(self):
        return True

    def generate_result_code(self, code):
6173
        code.globalstate.use_utility_code(UtilityCode.load_cached("Py3MetaclassGet", "ObjectHandling.c"))
6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224
        code.putln(
            "%s = __Pyx_Py3MetaclassGet(%s, %s); %s" % (
                self.result(),
                self.bases.result(),
                self.mkw.result(),
                code.error_goto_if_null(self.result(), self.pos)))
        code.put_gotref(self.py_result())

class PyClassNamespaceNode(ExprNode, ModuleNameMixin):
    # Helper class holds Python3 namespace object
    #
    # All this are not owned by this node
    #  metaclass    ExprNode           Metaclass object
    #  bases        ExprNode           Base class tuple
    #  mkw          ExprNode           Class keyword arguments
    #  doc          ExprNode or None   Doc string (owned)

    subexprs = ['doc']

    def analyse_types(self, env):
        self.bases.analyse_types(env)
        if self.doc:
            self.doc.analyse_types(env)
            self.doc = self.doc.coerce_to_pyobject(env)
        self.type = py_object_type
        self.is_temp = 1
        #TODO(craig,haoyu) This should be moved to a better place
        self.set_mod_name(env)

    def may_be_none(self):
        return True

    def generate_result_code(self, code):
        cname = code.intern_identifier(self.name)
        py_mod_name = self.get_py_mod_name(code)
        if self.doc:
            doc_code = self.doc.result()
        else:
            doc_code = '(PyObject *) NULL'
        code.putln(
            "%s = __Pyx_Py3MetaclassPrepare(%s, %s, %s, %s, %s, %s); %s" % (
                self.result(),
                self.metaclass.result(),
                self.bases.result(),
                cname,
                self.mkw.result(),
                py_mod_name,
                doc_code,
                code.error_goto_if_null(self.result(), self.pos)))
        code.put_gotref(self.py_result())

6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268

class ClassCellInjectorNode(ExprNode):
    # Initialize CyFunction.func_classobj
    is_temp = True
    type = py_object_type
    subexprs = []
    is_active = False

    def analyse_expressions(self, env):
        if self.is_active:
            env.use_utility_code(cyfunction_class_cell_utility_code)

    def generate_evaluation_code(self, code):
        if self.is_active:
            self.allocate_temp_result(code)
            code.putln(
                '%s = PyList_New(0); %s' % (
                    self.result(),
                    code.error_goto_if_null(self.result(), self.pos)))
            code.put_gotref(self.result())

    def generate_injection_code(self, code, classobj_cname):
        if self.is_active:
            code.putln('__Pyx_CyFunction_InitClassCell(%s, %s);' % (
                self.result(), classobj_cname))


class ClassCellNode(ExprNode):
    # Class Cell for noargs super()
    subexprs = []
    is_temp = True
    is_generator = False
    type = py_object_type

    def analyse_types(self, env):
        pass

    def generate_result_code(self, code):
        if not self.is_generator:
            code.putln('%s = __Pyx_CyFunction_GetClassObj(%s);' % (
                self.result(),
                Naming.self_cname))
        else:
            code.putln('%s =  %s->classobj;' % (
6269
                self.result(), Naming.generator_cname))
6270 6271 6272 6273 6274 6275 6276 6277
        code.putln(
            'if (!%s) { PyErr_SetString(PyExc_SystemError, '
            '"super(): empty __class__ cell"); %s }' % (
                self.result(),
                code.error_goto(self.pos)));
        code.put_incref(self.result(), py_object_type)


Robert Bradshaw's avatar
Robert Bradshaw committed
6278 6279 6280 6281 6282 6283 6284
class BoundMethodNode(ExprNode):
    #  Helper class used in the implementation of Python
    #  class definitions. Constructs an bound method
    #  object from a class and a function.
    #
    #  function      ExprNode   Function object
    #  self_object   ExprNode   self object
6285

Robert Bradshaw's avatar
Robert Bradshaw committed
6286
    subexprs = ['function']
6287

Robert Bradshaw's avatar
Robert Bradshaw committed
6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303
    def analyse_types(self, env):
        self.function.analyse_types(env)
        self.type = py_object_type
        self.is_temp = 1

    gil_message = "Constructing an bound method"

    def generate_result_code(self, code):
        code.putln(
            "%s = PyMethod_New(%s, %s, (PyObject*)%s->ob_type); %s" % (
                self.result(),
                self.function.py_result(),
                self.self_object.py_result(),
                self.self_object.py_result(),
                code.error_goto_if_null(self.result(), self.pos)))
        code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
6304

6305
class UnboundMethodNode(ExprNode):
William Stein's avatar
William Stein committed
6306 6307 6308 6309 6310
    #  Helper class used in the implementation of Python
    #  class definitions. Constructs an unbound method
    #  object from a class and a function.
    #
    #  function      ExprNode   Function object
6311

6312 6313
    type = py_object_type
    is_temp = 1
6314

William Stein's avatar
William Stein committed
6315
    subexprs = ['function']
6316

William Stein's avatar
William Stein committed
6317 6318
    def analyse_types(self, env):
        self.function.analyse_types(env)
6319

6320 6321 6322
    def may_be_none(self):
        return False

6323 6324
    gil_message = "Constructing an unbound method"

William Stein's avatar
William Stein committed
6325
    def generate_result_code(self, code):
6326
        class_cname = code.pyclass_stack[-1].classobj.result()
William Stein's avatar
William Stein committed
6327
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
6328
            "%s = PyMethod_New(%s, 0, %s); %s" % (
6329
                self.result(),
William Stein's avatar
William Stein committed
6330
                self.function.py_result(),
6331
                class_cname,
6332
                code.error_goto_if_null(self.result(), self.pos)))
6333
        code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
6334

Robert Bradshaw's avatar
Robert Bradshaw committed
6335

6336
class PyCFunctionNode(ExprNode, ModuleNameMixin):
William Stein's avatar
William Stein committed
6337 6338 6339 6340
    #  Helper class used in the implementation of Python
    #  class definitions. Constructs a PyCFunction object
    #  from a PyMethodDef struct.
    #
6341
    #  pymethdef_cname   string             PyMethodDef structure
Robert Bradshaw's avatar
Robert Bradshaw committed
6342
    #  self_object       ExprNode or None
Robert Bradshaw's avatar
Robert Bradshaw committed
6343
    #  binding           bool
6344
    #  def_node          DefNode            the Python function node
6345
    #  module_name       EncodedString      Name of defining module
6346 6347
    #  code_object       CodeObjectNode     the PyCodeObject creator node

6348
    subexprs = ['code_object', 'defaults_tuple']
Stefan Behnel's avatar
Stefan Behnel committed
6349

Robert Bradshaw's avatar
Robert Bradshaw committed
6350
    self_object = None
6351
    code_object = None
Robert Bradshaw's avatar
Robert Bradshaw committed
6352
    binding = False
6353
    def_node = None
6354 6355 6356
    defaults = None
    defaults_struct = None
    defaults_pyobjects = 0
6357
    defaults_tuple = None
6358

6359 6360
    type = py_object_type
    is_temp = 1
6361

6362
    specialized_cpdefs = None
6363
    is_specialization = False
6364

6365 6366 6367 6368 6369 6370 6371 6372
    @classmethod
    def from_defnode(cls, node, binding):
        return cls(node.pos,
                   def_node=node,
                   pymethdef_cname=node.entry.pymethdef_cname,
                   binding=binding or node.specialized_cpdefs,
                   specialized_cpdefs=node.specialized_cpdefs,
                   code_object=CodeObjectNode(node))
6373

6374
    def analyse_types(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
6375
        if self.binding:
6376
            if self.specialized_cpdefs or self.is_specialization:
6377 6378 6379
                env.use_utility_code(fused_function_utility_code)
            else:
                env.use_utility_code(binding_cfunc_utility_code)
Mark Florisson's avatar
Mark Florisson committed
6380
            self.analyse_default_args(env)
6381

6382 6383 6384
        #TODO(craig,haoyu) This should be moved to a better place
        self.set_mod_name(env)

6385 6386 6387 6388 6389 6390
    def analyse_default_args(self, env):
        """
        Handle non-literal function's default arguments.
        """
        nonliteral_objects = []
        nonliteral_other = []
6391
        default_args = []
6392
        for arg in self.def_node.args:
6393 6394 6395 6396 6397 6398 6399
            if arg.default:
                if not arg.default.is_literal:
                    arg.is_dynamic = True
                    if arg.type.is_pyobject:
                        nonliteral_objects.append(arg)
                    else:
                        nonliteral_other.append(arg)
6400 6401
                else:
                    arg.default = DefaultLiteralArgNode(arg.pos, arg.default)
6402
                default_args.append(arg)
Mark Florisson's avatar
Mark Florisson committed
6403
        if nonliteral_objects or nonliteral_other:
6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426
            module_scope = env.global_scope()
            cname = module_scope.next_id(Naming.defaults_struct_prefix)
            scope = Symtab.StructOrUnionScope(cname)
            self.defaults = []
            for arg in nonliteral_objects:
                entry = scope.declare_var(arg.name, arg.type, None,
                                          Naming.arg_prefix + arg.name,
                                          allow_pyobject=True)
                self.defaults.append((arg, entry))
            for arg in nonliteral_other:
                entry = scope.declare_var(arg.name, arg.type, None,
                                          Naming.arg_prefix + arg.name,
                                          allow_pyobject=False)
                self.defaults.append((arg, entry))
            entry = module_scope.declare_struct_or_union(
                None, 'struct', scope, 1, None, cname=cname)
            self.defaults_struct = scope
            self.defaults_pyobjects = len(nonliteral_objects)
            for arg, entry in self.defaults:
                arg.default_value = '%s->%s' % (
                    Naming.dynamic_args_cname, entry.cname)
            self.def_node.defaults_struct = self.defaults_struct.name

6427 6428 6429 6430 6431
        if default_args:
            if self.defaults_struct is None:
                self.defaults_tuple = TupleNode(self.pos, args=[
                    arg.default for arg in default_args])
                self.defaults_tuple.analyse_types(env)
6432 6433 6434 6435 6436 6437 6438 6439
            else:
                defaults_getter = Nodes.DefNode(
                    self.pos, args=[], star_arg=None, starstar_arg=None,
                    body=Nodes.ReturnStatNode(
                        self.pos, return_type=py_object_type,
                        value=DefaultsTupleNode(
                            self.pos, default_args,
                            self.defaults_struct)),
6440
                    decorators=None, name=StringEncoding.EncodedString("__defaults__"))
6441 6442 6443 6444 6445 6446 6447
                defaults_getter.analyse_declarations(env)
                defaults_getter.analyse_expressions(env)
                defaults_getter.body.analyse_expressions(
                    defaults_getter.local_scope)
                defaults_getter.py_wrapper_required = False
                defaults_getter.pymethdef_required = False
                self.def_node.defaults_getter = defaults_getter
6448

6449 6450
    def may_be_none(self):
        return False
6451

6452 6453
    gil_message = "Constructing Python function"

Stefan Behnel's avatar
Stefan Behnel committed
6454
    def self_result_code(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
6455 6456 6457 6458
        if self.self_object is None:
            self_result = "NULL"
        else:
            self_result = self.self_object.py_result()
Stefan Behnel's avatar
Stefan Behnel committed
6459 6460 6461
        return self_result

    def generate_result_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
6462
        if self.binding:
6463 6464 6465
            self.generate_cyfunction_code(code)
        else:
            self.generate_pycfunction_code(code)
6466

6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479
    def generate_pycfunction_code(self, code):
        py_mod_name = self.get_py_mod_name(code)
        code.putln(
            '%s = PyCFunction_NewEx(&%s, %s, %s); %s' % (
                self.result(),
                self.pymethdef_cname,
                self.self_result_code(),
                py_mod_name,
                code.error_goto_if_null(self.result(), self.pos)))

        code.put_gotref(self.py_result())

    def generate_cyfunction_code(self, code):
6480 6481
        def_node = self.def_node

6482 6483
        if self.specialized_cpdefs:
            constructor = "__pyx_FusedFunction_NewEx"
6484
            def_node = self.specialized_cpdefs[0]
6485 6486
        elif self.is_specialization:
            constructor = "__pyx_FusedFunction_NewEx"
Robert Bradshaw's avatar
Robert Bradshaw committed
6487
        else:
6488 6489 6490 6491 6492 6493 6494 6495
            constructor = "__Pyx_CyFunction_NewEx"

        if self.code_object:
            code_object_result = self.code_object.py_result()
        else:
            code_object_result = 'NULL'

        flags = []
6496
        if def_node.is_staticmethod:
6497
            flags.append('__Pyx_CYFUNCTION_STATICMETHOD')
6498
        elif def_node.is_classmethod:
6499
            flags.append('__Pyx_CYFUNCTION_CLASSMETHOD')
6500 6501 6502 6503

        if def_node.local_scope.parent_scope.is_c_class_scope:
            flags.append('__Pyx_CYFUNCTION_CCLASS')

6504 6505 6506 6507
        if flags:
            flags = ' | '.join(flags)
        else:
            flags = '0'
6508

6509
        py_mod_name = self.get_py_mod_name(code)
William Stein's avatar
William Stein committed
6510
        code.putln(
6511
            '%s = %s(&%s, %s, %s, %s, %s); %s' % (
6512
                self.result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
6513
                constructor,
William Stein's avatar
William Stein committed
6514
                self.pymethdef_cname,
6515
                flags,
Stefan Behnel's avatar
Stefan Behnel committed
6516
                self.self_result_code(),
6517
                py_mod_name,
6518
                code_object_result,
6519
                code.error_goto_if_null(self.result(), self.pos)))
6520

6521
        code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
6522

6523
        if def_node.requires_classobj:
6524 6525 6526 6527 6528 6529 6530 6531 6532
            assert code.pyclass_stack, "pyclass_stack is empty"
            class_node = code.pyclass_stack[-1]
            code.put_incref(self.py_result(), py_object_type)
            code.putln(
                'PyList_Append(%s, %s);' % (
                    class_node.class_cell.result(),
                    self.result()))
            code.put_giveref(self.py_result())

6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543
        if self.defaults:
            code.putln(
                'if (!__Pyx_CyFunction_InitDefaults(%s, sizeof(%s), %d)) %s' % (
                    self.result(), self.defaults_struct.name,
                    self.defaults_pyobjects, code.error_goto(self.pos)))
            defaults = '__Pyx_CyFunction_Defaults(%s, %s)' % (
                self.defaults_struct.name, self.result())
            for arg, entry in self.defaults:
                arg.generate_assignment_code(code, target='%s->%s' % (
                    defaults, entry.cname))

6544 6545 6546
        if self.defaults_tuple:
            code.putln('__Pyx_CyFunction_SetDefaultsTuple(%s, %s);' % (
                self.result(), self.defaults_tuple.py_result()))
6547 6548 6549
        if def_node.defaults_getter:
            code.putln('__Pyx_CyFunction_SetDefaultsGetter(%s, %s);' % (
                self.result(), def_node.defaults_getter.entry.pyfunc_cname))
6550

6551

Stefan Behnel's avatar
Stefan Behnel committed
6552 6553 6554
class InnerFunctionNode(PyCFunctionNode):
    # Special PyCFunctionNode that depends on a closure class
    #
Vitja Makarov's avatar
Vitja Makarov committed
6555

Robert Bradshaw's avatar
Robert Bradshaw committed
6556
    binding = True
Vitja Makarov's avatar
Vitja Makarov committed
6557 6558
    needs_self_code = True

Stefan Behnel's avatar
Stefan Behnel committed
6559
    def self_result_code(self):
Vitja Makarov's avatar
Vitja Makarov committed
6560 6561 6562
        if self.needs_self_code:
            return "((PyObject*)%s)" % (Naming.cur_scope_cname)
        return "NULL"
Stefan Behnel's avatar
Stefan Behnel committed
6563

6564 6565 6566 6567
class CodeObjectNode(ExprNode):
    # Create a PyCodeObject for a CyFunction instance.
    #
    # def_node   DefNode    the Python function node
6568
    # varnames   TupleNode  a tuple with all local variable names
6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579

    subexprs = ['varnames']
    is_temp = False

    def __init__(self, def_node):
        ExprNode.__init__(self, def_node.pos, def_node=def_node)
        args = list(def_node.args)
        if def_node.star_arg:
            args.append(def_node.star_arg)
        if def_node.starstar_arg:
            args.append(def_node.starstar_arg)
6580
        local_vars = [ arg for arg in def_node.local_scope.var_entries
6581
                       if arg.name ]
6582 6583
        self.varnames = TupleNode(
            def_node.pos,
6584
            args = [ IdentifierStringNode(arg.pos, value=arg.name)
6585
                     for arg in args + local_vars ],
6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610
            is_temp = 0,
            is_literal = 1)

    def calculate_result_code(self):
        return self.result_code

    def generate_result_code(self, code):
        self.result_code = code.get_py_const(py_object_type, 'codeobj_', cleanup_level=2)

        code = code.get_cached_constants_writer()
        code.mark_pos(self.pos)
        func = self.def_node
        func_name = code.get_py_string_const(
            func.name, identifier=True, is_str=False, unicode_value=func.name)
        # FIXME: better way to get the module file path at module init time? Encoding to use?
        file_path = StringEncoding.BytesLiteral(func.pos[0].get_filenametable_entry().encode('utf8'))
        file_path_const = code.get_py_string_const(file_path, identifier=False, is_str=True)

        code.putln("%s = (PyObject*)__Pyx_PyCode_New(%d, %d, %d, 0, 0, %s, %s, %s, %s, %s, %s, %s, %s, %d, %s); %s" % (
            self.result_code,
            len(func.args),            # argcount
            func.num_kwonly_args,      # kwonlyargcount (Py3 only)
            len(self.varnames.args),   # nlocals
            Naming.empty_bytes,        # code
            Naming.empty_tuple,        # consts
6611 6612
            Naming.empty_tuple,        # names (FIXME)
            self.varnames.result(),    # varnames
6613 6614 6615 6616 6617 6618 6619 6620 6621 6622
            Naming.empty_tuple,        # freevars (FIXME)
            Naming.empty_tuple,        # cellvars (FIXME)
            file_path_const,           # filename
            func_name,                 # name
            self.pos[1],               # firstlineno
            Naming.empty_bytes,        # lnotab
            code.error_goto_if_null(self.result_code, self.pos),
            ))


6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653
class DefaultLiteralArgNode(ExprNode):
    # CyFunction's literal argument default value
    #
    # Evaluate literal only once.

    subexprs = []
    is_literal = True
    is_temp = False

    def __init__(self, pos, arg):
        super(DefaultLiteralArgNode, self).__init__(pos)
        self.arg = arg
        self.type = self.arg.type
        self.evaluated = False

    def analyse_types(self, env):
        pass

    def generate_result_code(self, code):
        pass

    def generate_evaluation_code(self, code):
        if not self.evaluated:
            self.arg.generate_evaluation_code(code)
            self.evaluated = True

    def result(self):
        return self.type.cast_code(self.arg.result())


class DefaultNonLiteralArgNode(ExprNode):
6654 6655 6656 6657 6658
    # CyFunction's non-literal argument default value

    subexprs = []

    def __init__(self, pos, arg, defaults_struct):
6659
        super(DefaultNonLiteralArgNode, self).__init__(pos)
6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682
        self.arg = arg
        self.defaults_struct = defaults_struct

    def analyse_types(self, env):
        self.type = self.arg.type
        self.is_temp = False

    def generate_result_code(self, code):
        pass

    def result(self):
        return '__Pyx_CyFunction_Defaults(%s, %s)->%s' % (
            self.defaults_struct.name, Naming.self_cname,
            self.defaults_struct.lookup(self.arg.name).cname)


class DefaultsTupleNode(TupleNode):
    # CyFunction's __defaults__ tuple

    def __init__(self, pos, defaults, defaults_struct):
        args = []
        for arg in defaults:
            if not arg.default.is_literal:
6683
                arg = DefaultNonLiteralArgNode(pos, arg, defaults_struct)
6684 6685 6686 6687 6688 6689
            else:
                arg = arg.default
            args.append(arg)
        super(DefaultsTupleNode, self).__init__(pos, args=args)


Stefan Behnel's avatar
Stefan Behnel committed
6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704
class LambdaNode(InnerFunctionNode):
    # Lambda expression node (only used as a function reference)
    #
    # args          [CArgDeclNode]         formal arguments
    # star_arg      PyArgDeclNode or None  * argument
    # starstar_arg  PyArgDeclNode or None  ** argument
    # lambda_name   string                 a module-globally unique lambda name
    # result_expr   ExprNode
    # def_node      DefNode                the underlying function 'def' node

    child_attrs = ['def_node']

    name = StringEncoding.EncodedString('<lambda>')

    def analyse_declarations(self, env):
6705 6706
        self.def_node.no_assignment_synthesis = True
        self.def_node.pymethdef_required = True
Stefan Behnel's avatar
Stefan Behnel committed
6707
        self.def_node.analyse_declarations(env)
6708
        self.def_node.is_cyfunction = True
Stefan Behnel's avatar
Stefan Behnel committed
6709 6710 6711
        self.pymethdef_cname = self.def_node.entry.pymethdef_cname
        env.add_lambda_def(self.def_node)

6712 6713 6714 6715 6716 6717 6718 6719
    def analyse_types(self, env):
        self.def_node.analyse_expressions(env)
        super(LambdaNode, self).analyse_types(env)

    def generate_result_code(self, code):
        self.def_node.generate_execution_code(code)
        super(LambdaNode, self).generate_result_code(code)

6720

6721 6722 6723 6724 6725 6726 6727 6728
class GeneratorExpressionNode(LambdaNode):
    # A generator expression, e.g.  (i for i in range(10))
    #
    # Result is a generator.
    #
    # loop      ForStatNode   the for-loop, containing a YieldExprNode
    # def_node  DefNode       the underlying generator 'def' node

6729
    name = StringEncoding.EncodedString('genexpr')
6730 6731 6732
    binding = False

    def analyse_declarations(self, env):
6733 6734 6735
        super(GeneratorExpressionNode, self).analyse_declarations(env)
        # No pymethdef required
        self.def_node.pymethdef_required = False
6736
        self.def_node.py_wrapper_required = False
6737
        self.def_node.is_cyfunction = False
6738 6739
        # Force genexpr signature
        self.def_node.entry.signature = TypeSlots.pyfunction_noargs
6740 6741 6742

    def generate_result_code(self, code):
        code.putln(
6743
            '%s = %s(%s); %s' % (
6744
                self.result(),
6745
                self.def_node.entry.pyfunc_cname,
6746 6747 6748 6749 6750
                self.self_result_code(),
                code.error_goto_if_null(self.result(), self.pos)))
        code.put_gotref(self.py_result())


6751 6752 6753 6754 6755
class YieldExprNode(ExprNode):
    # Yield expression node
    #
    # arg         ExprNode   the value to return from the generator
    # label_name  string     name of the C label used for this yield
6756
    # label_num   integer    yield label number
6757
    # is_yield_from  boolean is a YieldFromExprNode to delegate to another generator
6758 6759 6760

    subexprs = ['arg']
    type = py_object_type
6761
    label_num = 0
6762
    is_yield_from = False
6763 6764

    def analyse_types(self, env):
6765 6766
        if not self.label_num:
            error(self.pos, "'yield' not supported here")
6767 6768 6769 6770
        self.is_temp = 1
        if self.arg is not None:
            self.arg.analyse_types(env)
            if not self.arg.type.is_pyobject:
6771 6772 6773 6774
                self.coerce_yield_argument(env)

    def coerce_yield_argument(self, env):
        self.arg = self.arg.coerce_to_pyobject(env)
6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787

    def generate_evaluation_code(self, code):
        if self.arg:
            self.arg.generate_evaluation_code(code)
            self.arg.make_owned_reference(code)
            code.putln(
                "%s = %s;" % (
                    Naming.retval_cname,
                    self.arg.result_as(py_object_type)))
            self.arg.generate_post_assignment_code(code)
            self.arg.free_temps(code)
        else:
            code.put_init_to_py_none(Naming.retval_cname, py_object_type)
6788 6789 6790 6791 6792 6793 6794 6795 6796 6797
        self.generate_yield_code(code)

    def generate_yield_code(self, code):
        """
        Generate the code to return the argument in 'Naming.retval_cname'
        and to continue at the yield label.
        """
        self.label_name = code.new_label('resume_from_yield')
        code.use_label(self.label_name)

6798
        saved = []
6799
        code.funcstate.closure_temps.reset()
6800
        for cname, type, manage_ref in code.funcstate.temps_in_use():
6801
            save_cname = code.funcstate.closure_temps.allocate_temp(type)
6802 6803 6804 6805
            saved.append((cname, save_cname, type))
            if type.is_pyobject:
                code.put_xgiveref(cname)
            code.putln('%s->%s = %s;' % (Naming.cur_scope_cname, save_cname, cname))
6806

6807
        code.put_xgiveref(Naming.retval_cname)
6808
        code.put_finish_refcount_context()
Stefan Behnel's avatar
Stefan Behnel committed
6809
        code.putln("/* return from generator, yielding value */")
6810 6811
        code.putln("%s->resume_label = %d;" % (
            Naming.generator_cname, self.label_num))
6812
        code.putln("return %s;" % Naming.retval_cname);
6813

6814
        code.put_label(self.label_name)
6815 6816 6817 6818 6819 6820
        for cname, save_cname, type in saved:
            code.putln('%s = %s->%s;' % (cname, Naming.cur_scope_cname, save_cname))
            if type.is_pyobject:
                code.putln('%s->%s = 0;' % (Naming.cur_scope_cname, save_cname))
            if type.is_pyobject:
                code.put_xgotref(cname)
6821 6822 6823 6824 6825 6826 6827 6828
        if self.result_is_used:
            self.allocate_temp_result(code)
            code.putln('%s = %s; %s' %
                       (self.result(), Naming.sent_value_cname,
                        code.error_goto_if_null(self.result(), self.pos)))
            code.put_incref(self.result(), py_object_type)
        else:
            code.putln(code.error_goto_if_null(Naming.sent_value_cname, self.pos))
6829

Vitja Makarov's avatar
Vitja Makarov committed
6830

6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848
class YieldFromExprNode(YieldExprNode):
    # "yield from GEN" expression
    is_yield_from = True

    def coerce_yield_argument(self, env):
        if not self.arg.type.is_string:
            # FIXME: support C arrays and C++ iterators?
            error(self.pos, "yielding from non-Python object not supported")
        self.arg = self.arg.coerce_to_pyobject(env)

    def generate_evaluation_code(self, code):
        code.globalstate.use_utility_code(UtilityCode.load_cached("YieldFrom", "Generator.c"))

        self.arg.generate_evaluation_code(code)
        code.putln("%s = __Pyx_Generator_Yield_From(%s, %s);" % (
            Naming.retval_cname,
            Naming.generator_cname,
            self.arg.result_as(py_object_type)))
6849
        self.arg.generate_disposal_code(code)
6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870
        self.arg.free_temps(code)
        code.put_xgotref(Naming.retval_cname)

        code.putln("if (likely(%s)) {" % Naming.retval_cname)
        self.generate_yield_code(code)
        code.putln("} else {")
        # either error or sub-generator has normally terminated: return value => node result
        if self.result_is_used:
            # YieldExprNode has allocated the result temp for us
            code.putln("if (__Pyx_PyGen_FetchStopIterationValue(&%s) < 0) %s" % (
                self.result(),
                code.error_goto(self.pos)))
        else:
            code.putln("PyObject* exc_type = PyErr_Occurred();")
            code.putln("if (exc_type) {")
            code.putln("if (!PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) %s" %
                code.error_goto(self.pos))
            code.putln("PyErr_Clear();")
            code.putln("}")
        code.putln("}")

Vitja Makarov's avatar
Vitja Makarov committed
6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885
class GlobalsExprNode(AtomicExprNode):
    type = dict_type
    is_temp = 1

    def analyse_types(self, env):
        env.use_utility_code(Builtin.globals_utility_code)

    gil_message = "Constructing globals dict"

    def generate_result_code(self, code):
        code.putln('%s = __Pyx_Globals(); %s' % (
            self.result(),
            code.error_goto_if_null(self.result(), self.pos)))
        code.put_gotref(self.result())

Vitja Makarov's avatar
Vitja Makarov committed
6886

6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897
class LocalsDictItemNode(DictItemNode):
    def analyse_types(self, env):
        self.key.analyse_types(env)
        self.value.analyse_types(env)
        self.key = self.key.coerce_to_pyobject(env)
        if self.value.type.can_coerce_to_pyobject(env):
            self.value = self.value.coerce_to_pyobject(env)
        else:
            self.value = None


6898
class FuncLocalsExprNode(DictNode):
Vitja Makarov's avatar
Vitja Makarov committed
6899
    def __init__(self, pos, env):
6900
        local_vars = [entry.name for entry in env.entries.values()
6901 6902 6903 6904
                      if entry.name]
        items = [LocalsDictItemNode(
            pos, key=IdentifierStringNode(pos, value=var),
            value=NameNode(pos, name=var, allow_null=True))
Vitja Makarov's avatar
Vitja Makarov committed
6905 6906 6907 6908
                 for var in local_vars]
        DictNode.__init__(self, pos, key_value_pairs=items,
                          exclude_null_values=True)

6909 6910 6911 6912 6913
    def analyse_types(self, env):
        super(FuncLocalsExprNode, self).analyse_types(env)
        self.key_value_pairs = [i for i in self.key_value_pairs
                                if i.value is not None]

6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938

class PyClassLocalsExprNode(AtomicExprNode):
    def __init__(self, pos, pyclass_dict):
        AtomicExprNode.__init__(self, pos)
        self.pyclass_dict = pyclass_dict

    def analyse_types(self, env):
        self.type = self.pyclass_dict.type
        self.is_tmep = 0

    def result(self):
        return self.pyclass_dict.result()

    def generate_result_code(self, code):
        pass


def LocalsExprNode(pos, scope_node, env):
    if env.is_module_scope:
        return GlobalsExprNode(pos)
    if env.is_py_class_scope:
        return PyClassLocalsExprNode(pos, scope_node.dict)
    return FuncLocalsExprNode(pos, env)


William Stein's avatar
William Stein committed
6939 6940 6941 6942 6943 6944
#-------------------------------------------------------------------
#
#  Unary operator nodes
#
#-------------------------------------------------------------------

6945 6946 6947 6948 6949 6950 6951
compile_time_unary_operators = {
    'not': operator.not_,
    '~': operator.inv,
    '-': operator.neg,
    '+': operator.pos,
}

6952
class UnopNode(ExprNode):
William Stein's avatar
William Stein committed
6953 6954 6955 6956 6957 6958 6959 6960 6961 6962
    #  operator     string
    #  operand      ExprNode
    #
    #  Processing during analyse_expressions phase:
    #
    #    analyse_c_operation
    #      Called when the operand is not a pyobject.
    #      - Check operand type and coerce if needed.
    #      - Determine result type and result code fragment.
    #      - Allocate temporary for result if needed.
6963

William Stein's avatar
William Stein committed
6964
    subexprs = ['operand']
Robert Bradshaw's avatar
Robert Bradshaw committed
6965
    infix = True
6966 6967 6968 6969

    def calculate_constant_result(self):
        func = compile_time_unary_operators[self.operator]
        self.constant_result = func(self.operand.constant_result)
6970

6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981
    def compile_time_value(self, denv):
        func = compile_time_unary_operators.get(self.operator)
        if not func:
            error(self.pos,
                "Unary '%s' not supported in compile-time expression"
                    % self.operator)
        operand = self.operand.compile_time_value(denv)
        try:
            return func(operand)
        except Exception, e:
            self.compile_time_value_error(e)
6982

6983
    def infer_type(self, env):
6984 6985 6986 6987 6988
        operand_type = self.operand.infer_type(env)
        if operand_type.is_pyobject:
            return py_object_type
        else:
            return operand_type
6989

William Stein's avatar
William Stein committed
6990 6991 6992 6993 6994 6995
    def analyse_types(self, env):
        self.operand.analyse_types(env)
        if self.is_py_operation():
            self.coerce_operand_to_pyobject(env)
            self.type = py_object_type
            self.is_temp = 1
6996 6997
        elif self.is_cpp_operation():
            self.analyse_cpp_operation(env)
William Stein's avatar
William Stein committed
6998 6999
        else:
            self.analyse_c_operation(env)
7000

William Stein's avatar
William Stein committed
7001
    def check_const(self):
7002
        return self.operand.check_const()
7003

William Stein's avatar
William Stein committed
7004 7005
    def is_py_operation(self):
        return self.operand.type.is_pyobject
7006

7007
    def nogil_check(self, env):
7008
        if self.is_py_operation():
7009
            self.gil_error()
7010

Danilo Freitas's avatar
Danilo Freitas committed
7011
    def is_cpp_operation(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
7012
        type = self.operand.type
Robert Bradshaw's avatar
Robert Bradshaw committed
7013
        return type.is_cpp_class
7014

William Stein's avatar
William Stein committed
7015 7016
    def coerce_operand_to_pyobject(self, env):
        self.operand = self.operand.coerce_to_pyobject(env)
7017

William Stein's avatar
William Stein committed
7018 7019 7020
    def generate_result_code(self, code):
        if self.operand.type.is_pyobject:
            self.generate_py_operation_code(code)
7021

William Stein's avatar
William Stein committed
7022 7023 7024
    def generate_py_operation_code(self, code):
        function = self.py_operation_function()
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
7025
            "%s = %s(%s); %s" % (
7026 7027
                self.result(),
                function,
William Stein's avatar
William Stein committed
7028
                self.operand.py_result(),
7029
                code.error_goto_if_null(self.result(), self.pos)))
7030
        code.put_gotref(self.py_result())
7031

William Stein's avatar
William Stein committed
7032 7033 7034 7035 7036 7037
    def type_error(self):
        if not self.operand.type.is_error:
            error(self.pos, "Invalid operand type for '%s' (%s)" %
                (self.operator, self.operand.type))
        self.type = PyrexTypes.error_type

Danilo Freitas's avatar
Danilo Freitas committed
7038
    def analyse_cpp_operation(self, env):
7039
        type = self.operand.type
Robert Bradshaw's avatar
Robert Bradshaw committed
7040
        if type.is_ptr:
Danilo Freitas's avatar
Danilo Freitas committed
7041
            type = type.base_type
Robert Bradshaw's avatar
Robert Bradshaw committed
7042
        function = type.scope.lookup("operator%s" % self.operator)
Danilo Freitas's avatar
Danilo Freitas committed
7043 7044
        if not function:
            error(self.pos, "'%s' operator not defined for %s"
7045
                % (self.operator, type))
Danilo Freitas's avatar
Danilo Freitas committed
7046 7047
            self.type_error()
            return
7048 7049 7050 7051
        func_type = function.type
        if func_type.is_ptr:
            func_type = func_type.base_type
        self.type = func_type.return_type
Danilo Freitas's avatar
Danilo Freitas committed
7052

William Stein's avatar
William Stein committed
7053

7054
class NotNode(ExprNode):
William Stein's avatar
William Stein committed
7055 7056 7057
    #  'not' operator
    #
    #  operand   ExprNode
7058

7059
    type = PyrexTypes.c_bint_type
7060

7061
    subexprs = ['operand']
7062

7063 7064 7065
    def calculate_constant_result(self):
        self.constant_result = not self.operand.constant_result

7066 7067 7068 7069 7070 7071 7072
    def compile_time_value(self, denv):
        operand = self.operand.compile_time_value(denv)
        try:
            return not operand
        except Exception, e:
            self.compile_time_value_error(e)

7073 7074
    def infer_type(self, env):
        return PyrexTypes.c_bint_type
7075

William Stein's avatar
William Stein committed
7076 7077
    def analyse_types(self, env):
        self.operand.analyse_types(env)
7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091
        if self.operand.type.is_cpp_class:
            type = self.operand.type
            function = type.scope.lookup("operator!")
            if not function:
                error(self.pos, "'!' operator not defined for %s"
                    % (type))
                self.type = PyrexTypes.error_type
                return
            func_type = function.type
            if func_type.is_ptr:
                func_type = func_type.base_type
            self.type = func_type.return_type
        else:
            self.operand = self.operand.coerce_to_boolean(env)
7092

William Stein's avatar
William Stein committed
7093
    def calculate_result_code(self):
7094
        return "(!%s)" % self.operand.result()
7095

William Stein's avatar
William Stein committed
7096 7097 7098 7099 7100 7101
    def generate_result_code(self, code):
        pass


class UnaryPlusNode(UnopNode):
    #  unary '+' operator
7102

William Stein's avatar
William Stein committed
7103
    operator = '+'
7104

William Stein's avatar
William Stein committed
7105
    def analyse_c_operation(self, env):
Lisandro Dalcin's avatar
Lisandro Dalcin committed
7106
        self.type = PyrexTypes.widest_numeric_type(
Robert Bradshaw's avatar
Robert Bradshaw committed
7107
            self.operand.type, PyrexTypes.c_int_type)
7108

William Stein's avatar
William Stein committed
7109 7110
    def py_operation_function(self):
        return "PyNumber_Positive"
7111

William Stein's avatar
William Stein committed
7112
    def calculate_result_code(self):
7113 7114 7115 7116
        if self.is_cpp_operation():
            return "(+%s)" % self.operand.result()
        else:
            return self.operand.result()
William Stein's avatar
William Stein committed
7117 7118 7119 7120


class UnaryMinusNode(UnopNode):
    #  unary '-' operator
7121

William Stein's avatar
William Stein committed
7122
    operator = '-'
7123

William Stein's avatar
William Stein committed
7124 7125
    def analyse_c_operation(self, env):
        if self.operand.type.is_numeric:
7126 7127
            self.type = PyrexTypes.widest_numeric_type(
                self.operand.type, PyrexTypes.c_int_type)
7128 7129
        elif self.operand.type.is_enum:
            self.type = PyrexTypes.c_int_type
William Stein's avatar
William Stein committed
7130 7131
        else:
            self.type_error()
Robert Bradshaw's avatar
Robert Bradshaw committed
7132
        if self.type.is_complex:
7133
            self.infix = False
7134

William Stein's avatar
William Stein committed
7135 7136
    def py_operation_function(self):
        return "PyNumber_Negative"
7137

William Stein's avatar
William Stein committed
7138
    def calculate_result_code(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
7139 7140 7141 7142
        if self.infix:
            return "(-%s)" % self.operand.result()
        else:
            return "%s(%s)" % (self.operand.type.unary_op('-'), self.operand.result())
William Stein's avatar
William Stein committed
7143

7144 7145 7146 7147 7148
    def get_constant_c_result_code(self):
        value = self.operand.get_constant_c_result_code()
        if value:
            return "(-%s)" % (value)

William Stein's avatar
William Stein committed
7149 7150 7151 7152 7153
class TildeNode(UnopNode):
    #  unary '~' operator

    def analyse_c_operation(self, env):
        if self.operand.type.is_int:
7154 7155
            self.type = PyrexTypes.widest_numeric_type(
                self.operand.type, PyrexTypes.c_int_type)
7156 7157
        elif self.operand.type.is_enum:
            self.type = PyrexTypes.c_int_type
William Stein's avatar
William Stein committed
7158 7159 7160 7161 7162
        else:
            self.type_error()

    def py_operation_function(self):
        return "PyNumber_Invert"
7163

William Stein's avatar
William Stein committed
7164
    def calculate_result_code(self):
7165
        return "(~%s)" % self.operand.result()
William Stein's avatar
William Stein committed
7166 7167


7168 7169
class CUnopNode(UnopNode):

Robert Bradshaw's avatar
Robert Bradshaw committed
7170 7171 7172
    def is_py_operation(self):
        return False

7173 7174
class DereferenceNode(CUnopNode):
    #  unary * operator
7175 7176

    operator = '*'
7177

Robert Bradshaw's avatar
Robert Bradshaw committed
7178 7179 7180 7181 7182 7183 7184 7185
    def analyse_c_operation(self, env):
        if self.operand.type.is_ptr:
            self.type = self.operand.type.base_type
        else:
            self.type_error()

    def calculate_result_code(self):
        return "(*%s)" % self.operand.result()
William Stein's avatar
William Stein committed
7186 7187


7188 7189
class DecrementIncrementNode(CUnopNode):
    #  unary ++/-- operator
7190

7191
    def analyse_c_operation(self, env):
7192 7193 7194 7195
        if self.operand.type.is_numeric:
            self.type = PyrexTypes.widest_numeric_type(
                self.operand.type, PyrexTypes.c_int_type)
        elif self.operand.type.is_ptr:
7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209
            self.type = self.operand.type
        else:
            self.type_error()

    def calculate_result_code(self):
        if self.is_prefix:
            return "(%s%s)" % (self.operator, self.operand.result())
        else:
            return "(%s%s)" % (self.operand.result(), self.operator)

def inc_dec_constructor(is_prefix, operator):
    return lambda pos, **kwds: DecrementIncrementNode(pos, is_prefix=is_prefix, operator=operator, **kwds)


7210
class AmpersandNode(ExprNode):
William Stein's avatar
William Stein committed
7211 7212 7213
    #  The C address-of operator.
    #
    #  operand  ExprNode
7214

William Stein's avatar
William Stein committed
7215
    subexprs = ['operand']
7216

7217 7218
    def infer_type(self, env):
        return PyrexTypes.c_ptr_type(self.operand.infer_type(env))
William Stein's avatar
William Stein committed
7219 7220 7221 7222

    def analyse_types(self, env):
        self.operand.analyse_types(env)
        argtype = self.operand.type
7223
        if not (argtype.is_cfunction or argtype.is_reference or self.operand.is_addressable()):
7224 7225 7226 7227
            if argtype.is_memoryviewslice:
                self.error("Cannot take address of memoryview slice")
            else:
                self.error("Taking address of non-lvalue")
William Stein's avatar
William Stein committed
7228 7229 7230 7231 7232
            return
        if argtype.is_pyobject:
            self.error("Cannot take address of Python variable")
            return
        self.type = PyrexTypes.c_ptr_type(argtype)
7233

William Stein's avatar
William Stein committed
7234
    def check_const(self):
7235
        return self.operand.check_const_addr()
7236

William Stein's avatar
William Stein committed
7237 7238 7239 7240
    def error(self, mess):
        error(self.pos, mess)
        self.type = PyrexTypes.error_type
        self.result_code = "<error>"
7241

William Stein's avatar
William Stein committed
7242
    def calculate_result_code(self):
7243
        return "(&%s)" % self.operand.result()
William Stein's avatar
William Stein committed
7244 7245 7246

    def generate_result_code(self, code):
        pass
7247

William Stein's avatar
William Stein committed
7248 7249 7250 7251 7252 7253 7254 7255

unop_node_classes = {
    "+":  UnaryPlusNode,
    "-":  UnaryMinusNode,
    "~":  TildeNode,
}

def unop_node(pos, operator, operand):
7256
    # Construct unnop node of appropriate class for
William Stein's avatar
William Stein committed
7257
    # given operator.
7258
    if isinstance(operand, IntNode) and operator == '-':
7259
        return IntNode(pos = operand.pos, value = str(-Utils.str_to_number(operand.value)))
Robert Bradshaw's avatar
Robert Bradshaw committed
7260 7261
    elif isinstance(operand, UnopNode) and operand.operator == operator:
        warning(pos, "Python has no increment/decrement operator: %s%sx = %s(%sx) = x" % ((operator,)*4), 5)
7262 7263
    return unop_node_classes[operator](pos,
        operator = operator,
William Stein's avatar
William Stein committed
7264 7265 7266
        operand = operand)


7267
class TypecastNode(ExprNode):
William Stein's avatar
William Stein committed
7268 7269
    #  C type cast
    #
7270
    #  operand      ExprNode
William Stein's avatar
William Stein committed
7271 7272
    #  base_type    CBaseTypeNode
    #  declarator   CDeclaratorNode
7273 7274 7275
    #
    #  If used from a transform, one can if wanted specify the attribute
    #  "type" directly and leave base_type and declarator to None
7276

William Stein's avatar
William Stein committed
7277
    subexprs = ['operand']
7278
    base_type = declarator = type = None
7279

Robert Bradshaw's avatar
Robert Bradshaw committed
7280
    def type_dependencies(self, env):
7281
        return ()
7282

Robert Bradshaw's avatar
Robert Bradshaw committed
7283
    def infer_type(self, env):
7284 7285 7286 7287
        if self.type is None:
            base_type = self.base_type.analyse(env)
            _, self.type = self.declarator.analyse(base_type, env)
        return self.type
7288

William Stein's avatar
William Stein committed
7289
    def analyse_types(self, env):
7290 7291 7292
        if self.type is None:
            base_type = self.base_type.analyse(env)
            _, self.type = self.declarator.analyse(base_type, env)
7293 7294 7295 7296
        if self.type.is_cfunction:
            error(self.pos,
                "Cannot cast to a function type")
            self.type = PyrexTypes.error_type
William Stein's avatar
William Stein committed
7297 7298 7299
        self.operand.analyse_types(env)
        to_py = self.type.is_pyobject
        from_py = self.operand.type.is_pyobject
7300 7301 7302
        if from_py and not to_py and self.operand.is_ephemeral():
            if not self.type.is_numeric and not self.type.is_cpp_class:
                error(self.pos, "Casting temporary Python object to non-numeric non-Python type")
William Stein's avatar
William Stein committed
7303
        if to_py and not from_py:
7304 7305 7306 7307 7308 7309
            if self.type is bytes_type and self.operand.type.is_int:
                # FIXME: the type cast node isn't needed in this case
                # and can be dropped once analyse_types() can return a
                # different node
                self.operand = CoerceIntToBytesNode(self.operand, env)
            elif self.operand.type.can_coerce_to_pyobject(env):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
7310
                self.result_ctype = py_object_type
7311
                self.operand = self.operand.coerce_to_pyobject(env)
7312
            else:
7313 7314 7315 7316
                if self.operand.type.is_ptr:
                    if not (self.operand.type.base_type.is_void or self.operand.type.base_type.is_struct):
                        error(self.pos, "Python objects cannot be cast from pointers of primitive types")
                else:
7317
                    # Should this be an error?
7318
                    warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.operand.type, self.type))
7319
                self.operand = self.operand.coerce_to_simple(env)
7320
        elif from_py and not to_py:
7321
            if self.type.create_from_py_utility_code(env):
7322
                self.operand = self.operand.coerce_to(self.type, env)
7323 7324 7325
            elif self.type.is_ptr:
                if not (self.type.base_type.is_void or self.type.base_type.is_struct):
                    error(self.pos, "Python objects cannot be cast to pointers of primitive types")
7326 7327
            else:
                warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.type, self.operand.type))
7328 7329
        elif from_py and to_py:
            if self.typecheck and self.type.is_extension_type:
7330
                self.operand = PyTypeTestNode(self.operand, self.type, env, notnone=True)
7331 7332
        elif self.type.is_complex and self.operand.type.is_complex:
            self.operand = self.operand.coerce_to_simple(env)
7333 7334
        elif self.operand.type.is_fused:
            self.operand = self.operand.coerce_to(self.type, env)
7335
            #self.type = self.operand.type
7336

Stefan Behnel's avatar
Stefan Behnel committed
7337
    def is_simple(self):
7338 7339
        # either temp or a C cast => no side effects other than the operand's
        return self.operand.is_simple()
Stefan Behnel's avatar
Stefan Behnel committed
7340

7341 7342 7343
    def nonlocally_immutable(self):
        return self.operand.nonlocally_immutable()

7344 7345 7346
    def nogil_check(self, env):
        if self.type and self.type.is_pyobject and self.is_temp:
            self.gil_error()
7347

William Stein's avatar
William Stein committed
7348
    def check_const(self):
7349
        return self.operand.check_const()
Stefan Behnel's avatar
Stefan Behnel committed
7350 7351

    def calculate_constant_result(self):
7352 7353 7354
        # we usually do not know the result of a type cast at code
        # generation time
        pass
7355

William Stein's avatar
William Stein committed
7356
    def calculate_result_code(self):
7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367
        if self.type.is_complex:
            operand_result = self.operand.result()
            if self.operand.type.is_complex:
                real_part = self.type.real_type.cast_code("__Pyx_CREAL(%s)" % operand_result)
                imag_part = self.type.real_type.cast_code("__Pyx_CIMAG(%s)" % operand_result)
            else:
                real_part = self.type.real_type.cast_code(operand_result)
                imag_part = "0"
            return "%s(%s, %s)" % (
                    self.type.from_parts,
                    real_part,
7368
                    imag_part)
7369 7370
        else:
            return self.type.cast_code(self.operand.result())
7371

7372 7373 7374 7375
    def get_constant_c_result_code(self):
        operand_result = self.operand.get_constant_c_result_code()
        if operand_result:
            return self.type.cast_code(operand_result)
7376

William Stein's avatar
William Stein committed
7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387
    def result_as(self, type):
        if self.type.is_pyobject and not self.is_temp:
            #  Optimise away some unnecessary casting
            return self.operand.result_as(type)
        else:
            return ExprNode.result_as(self, type)

    def generate_result_code(self, code):
        if self.is_temp:
            code.putln(
                "%s = (PyObject *)%s;" % (
7388 7389 7390
                    self.result(),
                    self.operand.result()))
            code.put_incref(self.result(), self.ctype())
William Stein's avatar
William Stein committed
7391 7392


7393 7394 7395 7396
ERR_START = "Start may not be given"
ERR_NOT_STOP = "Stop must be provided to indicate shape"
ERR_STEPS = ("Strides may only be given to indicate contiguity. "
             "Consider slicing it after conversion")
7397
ERR_NOT_POINTER = "Can only create cython.array from pointer or array"
7398 7399 7400 7401 7402 7403 7404
ERR_BASE_TYPE = "Pointer base type does not match cython.array base type"

class CythonArrayNode(ExprNode):
    """
    Used when a pointer of base_type is cast to a memoryviewslice with that
    base type. i.e.

7405
        <int[:M:1, :N]> p
7406 7407 7408 7409 7410 7411 7412

    creates a fortran-contiguous cython.array.

    We leave the type set to object so coercions to object are more efficient
    and less work. Acquiring a memoryviewslice from this will be just as
    efficient. ExprNode.coerce_to() will do the additional typecheck on
    self.compile_time_type
7413 7414 7415 7416 7417 7418

    This also handles <int[:, :]> my_c_array


    operand             ExprNode                 the thing we're casting
    base_type_node      MemoryViewSliceTypeNode  the cast expression node
7419 7420 7421 7422 7423 7424 7425
    """

    subexprs = ['operand', 'shapes']

    shapes = None
    is_temp = True
    mode = "c"
7426
    array_dtype = None
7427 7428 7429 7430 7431 7432

    shape_type = PyrexTypes.c_py_ssize_t_type

    def analyse_types(self, env):
        import MemoryView

7433 7434 7435 7436 7437 7438 7439 7440 7441
        self.operand.analyse_types(env)
        if self.array_dtype:
            array_dtype = self.array_dtype
        else:
            array_dtype = self.base_type_node.base_type_node.analyse(env)
        axes = self.base_type_node.axes

        MemoryView.validate_memslice_dtype(self.pos, array_dtype)

7442 7443
        self.type = error_type
        self.shapes = []
7444
        ndim = len(axes)
7445

7446 7447 7448
        # Base type of the pointer or C array we are converting
        base_type = self.operand.type

7449 7450 7451
        if not self.operand.type.is_ptr and not self.operand.type.is_array:
            return error(self.operand.pos, ERR_NOT_POINTER)

7452 7453 7454 7455 7456 7457
        # Dimension sizes of C array
        array_dimension_sizes = []
        if base_type.is_array:
            while base_type.is_array:
                array_dimension_sizes.append(base_type.size)
                base_type = base_type.base_type
7458
        elif base_type.is_ptr:
7459
            base_type = base_type.base_type
7460 7461
        else:
            return error()
7462

7463
        if not (base_type.same_as(array_dtype) or base_type.is_void):
7464 7465 7466 7467 7468 7469 7470 7471 7472 7473
            return error(self.operand.pos, ERR_BASE_TYPE)
        elif self.operand.type.is_array and len(array_dimension_sizes) != ndim:
            return error(self.operand.pos,
                         "Expected %d dimensions, array has %d dimensions" %
                                            (ndim, len(array_dimension_sizes)))

        # Verify the start, stop and step values
        # In case of a C array, use the size of C array in each dimension to
        # get an automatic cast
        for axis_no, axis in enumerate(axes):
7474 7475 7476 7477
            if not axis.start.is_none:
                return error(axis.start.pos, ERR_START)

            if axis.stop.is_none:
7478 7479 7480 7481 7482 7483 7484
                if array_dimension_sizes:
                    dimsize = array_dimension_sizes[axis_no]
                    axis.stop = IntNode(self.pos, value=dimsize,
                                        constant_result=dimsize,
                                        type=PyrexTypes.c_int_type)
                else:
                    return error(axis.pos, ERR_NOT_STOP)
7485 7486 7487 7488 7489 7490 7491 7492

            axis.stop.analyse_types(env)
            shape = axis.stop.coerce_to(self.shape_type, env)
            if not shape.is_literal:
                shape.coerce_to_temp(env)

            self.shapes.append(shape)

7493
            first_or_last = axis_no in (0, ndim - 1)
7494
            if not axis.step.is_none and first_or_last:
7495
                # '1' in the first or last dimension denotes F or C contiguity
7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506
                axis.step.analyse_types(env)
                if (not axis.step.type.is_int and axis.step.is_literal and not
                        axis.step.type.is_error):
                    return error(axis.step.pos, "Expected an integer literal")

                if axis.step.compile_time_value(env) != 1:
                    return error(axis.step.pos, ERR_STEPS)

                if axis_no == 0:
                    self.mode = "fortran"

7507 7508
            elif not axis.step.is_none and not first_or_last:
                # step provided in some other dimension
7509 7510 7511 7512 7513
                return error(axis.step.pos, ERR_STEPS)

        if not self.operand.is_name:
            self.operand = self.operand.coerce_to_temp(env)

7514
        axes = [('direct', 'follow')] * len(axes)
7515 7516 7517 7518 7519 7520
        if self.mode == "fortran":
            axes[0] = ('direct', 'contig')
        else:
            axes[-1] = ('direct', 'contig')

        self.coercion_type = PyrexTypes.MemoryViewSliceType(array_dtype, axes)
7521
        self.type = self.get_cython_array_type(env)
7522
        MemoryView.use_cython_array_utility_code(env)
7523 7524 7525 7526 7527 7528 7529 7530
        env.use_utility_code(MemoryView.typeinfo_to_format_code)

    def allocate_temp_result(self, code):
        if self.temp_code:
            raise RuntimeError("temp allocated mulitple times")

        self.temp_code = code.funcstate.allocate_temp(self.type, True)

7531 7532 7533 7534
    def infer_type(self, env):
        return self.get_cython_array_type(env)

    def get_cython_array_type(self, env):
7535
        return env.global_scope().context.cython_scope.viewscope.lookup("array").type
7536

7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549
    def generate_result_code(self, code):
        import Buffer

        shapes = [self.shape_type.cast_code(shape.result())
                      for shape in self.shapes]
        dtype = self.coercion_type.dtype

        shapes_temp = code.funcstate.allocate_temp(py_object_type, True)
        format_temp = code.funcstate.allocate_temp(py_object_type, True)

        itemsize = "sizeof(%s)" % dtype.declaration_code("")
        type_info = Buffer.get_type_information_cname(code, dtype)

7550 7551 7552 7553 7554 7555
        if self.operand.type.is_ptr:
            code.putln("if (!%s) {" % self.operand.result())
            code.putln(    'PyErr_SetString(PyExc_ValueError,'
                                '"Cannot create cython.array from NULL pointer");')
            code.putln(code.error_goto(self.operand.pos))
            code.putln("}")
7556 7557 7558

        code.putln("%s = __pyx_format_from_typeinfo(&%s);" %
                                                (format_temp, type_info))
7559 7560 7561 7562
        buildvalue_fmt = " __PYX_BUILD_PY_SSIZE_T " * len(shapes)
        code.putln('%s = Py_BuildValue("(" %s ")", %s);' % (shapes_temp,
                                                            buildvalue_fmt,
                                                            ", ".join(shapes)))
7563

7564 7565 7566
        err = "!%s || !%s || !PyBytes_AsString(%s)" % (format_temp,
                                                       shapes_temp,
                                                       format_temp)
7567 7568 7569 7570 7571 7572 7573 7574
        code.putln(code.error_goto_if(err, self.pos))
        code.put_gotref(format_temp)
        code.put_gotref(shapes_temp)

        tup = (self.result(), shapes_temp, itemsize, format_temp,
               self.mode, self.operand.result())
        code.putln('%s = __pyx_array_new('
                            '%s, %s, PyBytes_AS_STRING(%s), '
7575
                            '(char *) "%s", (char *) %s);' % tup)
7576 7577 7578 7579 7580 7581 7582 7583 7584 7585
        code.putln(code.error_goto_if_null(self.result(), self.pos))
        code.put_gotref(self.result())

        def dispose(temp):
            code.put_decref_clear(temp, py_object_type)
            code.funcstate.release_temp(temp)

        dispose(shapes_temp)
        dispose(format_temp)

7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608
    @classmethod
    def from_carray(cls, src_node, env):
        """
        Given a C array type, return a CythonArrayNode
        """
        pos = src_node.pos
        base_type = src_node.type

        none_node = NoneNode(pos)
        axes = []

        while base_type.is_array:
            axes.append(SliceNode(pos, start=none_node, stop=none_node,
                                       step=none_node))
            base_type = base_type.base_type
        axes[-1].step = IntNode(pos, value="1", is_c_literal=True)

        memslicenode = Nodes.MemoryViewSliceTypeNode(pos, axes=axes,
                                                     base_type_node=base_type)
        result = CythonArrayNode(pos, base_type_node=memslicenode,
                                 operand=src_node, array_dtype=base_type)
        result.analyse_types(env)
        return result
7609

7610
class SizeofNode(ExprNode):
William Stein's avatar
William Stein committed
7611
    #  Abstract base class for sizeof(x) expression nodes.
7612

7613
    type = PyrexTypes.c_size_t_type
William Stein's avatar
William Stein committed
7614 7615

    def check_const(self):
7616
        return True
William Stein's avatar
William Stein committed
7617 7618 7619 7620 7621 7622 7623 7624 7625 7626

    def generate_result_code(self, code):
        pass


class SizeofTypeNode(SizeofNode):
    #  C sizeof function applied to a type
    #
    #  base_type   CBaseTypeNode
    #  declarator  CDeclaratorNode
7627

William Stein's avatar
William Stein committed
7628
    subexprs = []
7629
    arg_type = None
7630

William Stein's avatar
William Stein committed
7631
    def analyse_types(self, env):
7632 7633
        # we may have incorrectly interpreted a dotted name as a type rather than an attribute
        # this could be better handled by more uniformly treating types as runtime-available objects
7634
        if 0 and self.base_type.module_path:
7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645
            path = self.base_type.module_path
            obj = env.lookup(path[0])
            if obj.as_module is None:
                operand = NameNode(pos=self.pos, name=path[0])
                for attr in path[1:]:
                    operand = AttributeNode(pos=self.pos, obj=operand, attribute=attr)
                operand = AttributeNode(pos=self.pos, obj=operand, attribute=self.base_type.name)
                self.operand = operand
                self.__class__ = SizeofVarNode
                self.analyse_types(env)
                return
7646 7647 7648 7649
        if self.arg_type is None:
            base_type = self.base_type.analyse(env)
            _, arg_type = self.declarator.analyse(base_type, env)
            self.arg_type = arg_type
7650
        self.check_type()
7651

7652 7653
    def check_type(self):
        arg_type = self.arg_type
7654
        if arg_type.is_pyobject and not arg_type.is_extension_type:
William Stein's avatar
William Stein committed
7655 7656 7657 7658 7659
            error(self.pos, "Cannot take sizeof Python object")
        elif arg_type.is_void:
            error(self.pos, "Cannot take sizeof void")
        elif not arg_type.is_complete():
            error(self.pos, "Cannot take sizeof incomplete type '%s'" % arg_type)
7660

William Stein's avatar
William Stein committed
7661
    def calculate_result_code(self):
7662 7663 7664 7665 7666 7667
        if self.arg_type.is_extension_type:
            # the size of the pointer is boring
            # we want the size of the actual struct
            arg_code = self.arg_type.declaration_code("", deref=1)
        else:
            arg_code = self.arg_type.declaration_code("")
William Stein's avatar
William Stein committed
7668
        return "(sizeof(%s))" % arg_code
7669

William Stein's avatar
William Stein committed
7670 7671 7672 7673 7674

class SizeofVarNode(SizeofNode):
    #  C sizeof function applied to a variable
    #
    #  operand   ExprNode
7675

William Stein's avatar
William Stein committed
7676
    subexprs = ['operand']
7677

William Stein's avatar
William Stein committed
7678
    def analyse_types(self, env):
7679 7680 7681 7682 7683
        # We may actually be looking at a type rather than a variable...
        # If we are, traditional analysis would fail...
        operand_as_type = self.operand.analyse_as_type(env)
        if operand_as_type:
            self.arg_type = operand_as_type
Mark Florisson's avatar
Mark Florisson committed
7684 7685
            if self.arg_type.is_fused:
                self.arg_type = self.arg_type.specialize(env.fused_to_specific)
7686 7687 7688 7689
            self.__class__ = SizeofTypeNode
            self.check_type()
        else:
            self.operand.analyse_types(env)
7690

William Stein's avatar
William Stein committed
7691
    def calculate_result_code(self):
7692
        return "(sizeof(%s))" % self.operand.result()
7693

William Stein's avatar
William Stein committed
7694 7695 7696
    def generate_result_code(self, code):
        pass

Robert Bradshaw's avatar
Robert Bradshaw committed
7697
class TypeofNode(ExprNode):
7698 7699 7700
    #  Compile-time type of an expression, as a string.
    #
    #  operand   ExprNode
Robert Bradshaw's avatar
Robert Bradshaw committed
7701
    #  literal   StringNode # internal
7702

Robert Bradshaw's avatar
Robert Bradshaw committed
7703 7704
    literal = None
    type = py_object_type
7705

Stefan Behnel's avatar
Stefan Behnel committed
7706
    subexprs = ['literal'] # 'operand' will be ignored after type analysis!
7707

7708 7709
    def analyse_types(self, env):
        self.operand.analyse_types(env)
7710
        value = StringEncoding.EncodedString(str(self.operand.type)) #self.operand.type.typeof_name())
7711
        self.literal = StringNode(self.pos, value=value)
Robert Bradshaw's avatar
Robert Bradshaw committed
7712 7713
        self.literal.analyse_types(env)
        self.literal = self.literal.coerce_to_pyobject(env)
7714 7715 7716 7717

    def may_be_none(self):
        return False

7718
    def generate_evaluation_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
7719
        self.literal.generate_evaluation_code(code)
7720

Robert Bradshaw's avatar
Robert Bradshaw committed
7721 7722
    def calculate_result_code(self):
        return self.literal.calculate_result_code()
William Stein's avatar
William Stein committed
7723 7724 7725 7726 7727 7728 7729

#-------------------------------------------------------------------
#
#  Binary operator nodes
#
#-------------------------------------------------------------------

Stefan Behnel's avatar
Stefan Behnel committed
7730 7731 7732
def _not_in(x, seq):
    return x not in seq

7733 7734 7735
compile_time_binary_operators = {
    '<': operator.lt,
    '<=': operator.le,
7736
    '==': operator.eq,
7737 7738 7739 7740 7741 7742 7743
    '!=': operator.ne,
    '>=': operator.ge,
    '>': operator.gt,
    'is': operator.is_,
    'is_not': operator.is_not,
    '+': operator.add,
    '&': operator.and_,
7744
    '/': operator.truediv,
7745 7746 7747 7748 7749 7750 7751 7752 7753
    '//': operator.floordiv,
    '<<': operator.lshift,
    '%': operator.mod,
    '*': operator.mul,
    '|': operator.or_,
    '**': operator.pow,
    '>>': operator.rshift,
    '-': operator.sub,
    '^': operator.xor,
Stefan Behnel's avatar
Stefan Behnel committed
7754 7755
    'in': operator.contains,
    'not_in': _not_in,
7756 7757 7758 7759 7760 7761 7762
}

def get_compile_time_binop(node):
    func = compile_time_binary_operators.get(node.operator)
    if not func:
        error(node.pos,
            "Binary '%s' not supported in compile-time expression"
7763
                % node.operator)
7764 7765
    return func

7766
class BinopNode(ExprNode):
William Stein's avatar
William Stein committed
7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777
    #  operator     string
    #  operand1     ExprNode
    #  operand2     ExprNode
    #
    #  Processing during analyse_expressions phase:
    #
    #    analyse_c_operation
    #      Called when neither operand is a pyobject.
    #      - Check operand types and coerce if needed.
    #      - Determine result type and result code fragment.
    #      - Allocate temporary for result if needed.
7778

William Stein's avatar
William Stein committed
7779
    subexprs = ['operand1', 'operand2']
7780
    inplace = False
7781 7782 7783 7784 7785 7786 7787

    def calculate_constant_result(self):
        func = compile_time_binary_operators[self.operator]
        self.constant_result = func(
            self.operand1.constant_result,
            self.operand2.constant_result)

7788 7789 7790 7791 7792 7793 7794 7795
    def compile_time_value(self, denv):
        func = get_compile_time_binop(self)
        operand1 = self.operand1.compile_time_value(denv)
        operand2 = self.operand2.compile_time_value(denv)
        try:
            return func(operand1, operand2)
        except Exception, e:
            self.compile_time_value_error(e)
7796

7797 7798
    def infer_type(self, env):
        return self.result_type(self.operand1.infer_type(env),
Robert Bradshaw's avatar
Robert Bradshaw committed
7799
                                self.operand2.infer_type(env))
7800

William Stein's avatar
William Stein committed
7801 7802 7803
    def analyse_types(self, env):
        self.operand1.analyse_types(env)
        self.operand2.analyse_types(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
7804
        self.analyse_operation(env)
7805

Robert Bradshaw's avatar
Robert Bradshaw committed
7806
    def analyse_operation(self, env):
William Stein's avatar
William Stein committed
7807 7808
        if self.is_py_operation():
            self.coerce_operands_to_pyobjects(env)
7809 7810 7811
            self.type = self.result_type(self.operand1.type,
                                         self.operand2.type)
            assert self.type.is_pyobject
William Stein's avatar
William Stein committed
7812
            self.is_temp = 1
DaniloFreitas's avatar
DaniloFreitas committed
7813 7814
        elif self.is_cpp_operation():
            self.analyse_cpp_operation(env)
William Stein's avatar
William Stein committed
7815 7816
        else:
            self.analyse_c_operation(env)
7817

William Stein's avatar
William Stein committed
7818
    def is_py_operation(self):
7819
        return self.is_py_operation_types(self.operand1.type, self.operand2.type)
7820

7821 7822 7823
    def is_py_operation_types(self, type1, type2):
        return type1.is_pyobject or type2.is_pyobject

DaniloFreitas's avatar
DaniloFreitas committed
7824
    def is_cpp_operation(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
7825 7826
        return (self.operand1.type.is_cpp_class
            or self.operand2.type.is_cpp_class)
7827

7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843
    def analyse_cpp_operation(self, env):
        type1 = self.operand1.type
        type2 = self.operand2.type
        entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
        if not entry:
            self.type_error()
            return
        func_type = entry.type
        if func_type.is_ptr:
            func_type = func_type.base_type
        if len(func_type.args) == 1:
            self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
        else:
            self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
            self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
        self.type = func_type.return_type
7844

7845 7846
    def result_type(self, type1, type2):
        if self.is_py_operation_types(type1, type2):
7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864
            if type2.is_string:
                type2 = Builtin.bytes_type
            if type1.is_string:
                type1 = Builtin.bytes_type
            elif self.operator == '%' \
                     and type1 in (Builtin.str_type, Builtin.unicode_type):
                # note that  b'%s' % b'abc'  doesn't work in Py3
                return type1
            if type1.is_builtin_type:
                if type1 is type2:
                    if self.operator in '**%+|&^':
                        # FIXME: at least these operators should be safe - others?
                        return type1
                elif self.operator == '*':
                    if type1 in (Builtin.bytes_type, Builtin.str_type, Builtin.unicode_type):
                        return type1
                    # multiplication of containers/numbers with an
                    # integer value always (?) returns the same type
7865
                    if type2.is_int:
7866
                        return type1
7867 7868 7869 7870
            elif type2.is_builtin_type and type1.is_int and self.operator == '*':
                # multiplication of containers/numbers with an
                # integer value always (?) returns the same type
                return type2
7871 7872 7873
            return py_object_type
        else:
            return self.compute_c_result_type(type1, type2)
7874

7875
    def nogil_check(self, env):
7876
        if self.is_py_operation():
7877
            self.gil_error()
7878

William Stein's avatar
William Stein committed
7879 7880 7881
    def coerce_operands_to_pyobjects(self, env):
        self.operand1 = self.operand1.coerce_to_pyobject(env)
        self.operand2 = self.operand2.coerce_to_pyobject(env)
7882

William Stein's avatar
William Stein committed
7883
    def check_const(self):
7884
        return self.operand1.check_const() and self.operand2.check_const()
7885

William Stein's avatar
William Stein committed
7886 7887 7888 7889
    def generate_result_code(self, code):
        #print "BinopNode.generate_result_code:", self.operand1, self.operand2 ###
        if self.operand1.type.is_pyobject:
            function = self.py_operation_function()
7890
            if self.operator == '**':
William Stein's avatar
William Stein committed
7891 7892 7893 7894
                extra_args = ", Py_None"
            else:
                extra_args = ""
            code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
7895
                "%s = %s(%s, %s%s); %s" % (
7896 7897
                    self.result(),
                    function,
William Stein's avatar
William Stein committed
7898 7899 7900
                    self.operand1.py_result(),
                    self.operand2.py_result(),
                    extra_args,
7901
                    code.error_goto_if_null(self.result(), self.pos)))
7902
            code.put_gotref(self.py_result())
7903

William Stein's avatar
William Stein committed
7904 7905 7906 7907
    def type_error(self):
        if not (self.operand1.type.is_error
                or self.operand2.type.is_error):
            error(self.pos, "Invalid operand types for '%s' (%s; %s)" %
7908
                (self.operator, self.operand1.type,
William Stein's avatar
William Stein committed
7909 7910 7911 7912
                    self.operand2.type))
        self.type = PyrexTypes.error_type


Robert Bradshaw's avatar
Robert Bradshaw committed
7913
class CBinopNode(BinopNode):
7914

Robert Bradshaw's avatar
Robert Bradshaw committed
7915 7916 7917 7918
    def analyse_types(self, env):
        BinopNode.analyse_types(self, env)
        if self.is_py_operation():
            self.type = PyrexTypes.error_type
7919

Stefan Behnel's avatar
Stefan Behnel committed
7920
    def py_operation_function(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
7921
        return ""
7922

Robert Bradshaw's avatar
Robert Bradshaw committed
7923 7924
    def calculate_result_code(self):
        return "(%s %s %s)" % (
7925 7926
            self.operand1.result(),
            self.operator,
Robert Bradshaw's avatar
Robert Bradshaw committed
7927 7928 7929 7930 7931 7932 7933 7934
            self.operand2.result())


def c_binop_constructor(operator):
    def make_binop_node(pos, **operands):
        return CBinopNode(pos, operator=operator, **operands)
    return make_binop_node

William Stein's avatar
William Stein committed
7935 7936
class NumBinopNode(BinopNode):
    #  Binary operation taking numeric arguments.
7937

Robert Bradshaw's avatar
Robert Bradshaw committed
7938
    infix = True
7939

William Stein's avatar
William Stein committed
7940 7941 7942 7943 7944 7945
    def analyse_c_operation(self, env):
        type1 = self.operand1.type
        type2 = self.operand2.type
        self.type = self.compute_c_result_type(type1, type2)
        if not self.type:
            self.type_error()
7946
            return
7947
        if self.type.is_complex:
Robert Bradshaw's avatar
Robert Bradshaw committed
7948
            self.infix = False
7949
        if not self.infix or (type1.is_numeric and type2.is_numeric):
7950 7951
            self.operand1 = self.operand1.coerce_to(self.type, env)
            self.operand2 = self.operand2.coerce_to(self.type, env)
7952

William Stein's avatar
William Stein committed
7953 7954
    def compute_c_result_type(self, type1, type2):
        if self.c_types_okay(type1, type2):
7955 7956 7957 7958 7959
            widest_type = PyrexTypes.widest_numeric_type(type1, type2)
            if widest_type is PyrexTypes.c_bint_type:
                if self.operator not in '|^&':
                    # False + False == 0 # not False!
                    widest_type = PyrexTypes.c_int_type
7960 7961 7962
            else:
                widest_type = PyrexTypes.widest_numeric_type(
                    widest_type, PyrexTypes.c_int_type)
7963
            return widest_type
William Stein's avatar
William Stein committed
7964 7965
        else:
            return None
7966

7967 7968 7969 7970 7971 7972 7973 7974 7975 7976
    def may_be_none(self):
        type1 = self.operand1.type
        type2 = self.operand2.type
        if type1 and type1.is_builtin_type and type2 and type2.is_builtin_type:
            # XXX: I can't think of any case where a binary operation
            # on builtin types evaluates to None - add a special case
            # here if there is one.
            return False
        return super(NumBinopNode, self).may_be_none()

7977 7978 7979 7980 7981 7982 7983
    def get_constant_c_result_code(self):
        value1 = self.operand1.get_constant_c_result_code()
        value2 = self.operand2.get_constant_c_result_code()
        if value1 and value2:
            return "(%s %s %s)" % (value1, self.operator, value2)
        else:
            return None
7984

William Stein's avatar
William Stein committed
7985
    def c_types_okay(self, type1, type2):
7986 7987 7988
        #print "NumBinopNode.c_types_okay:", type1, type2 ###
        return (type1.is_numeric  or type1.is_enum) \
            and (type2.is_numeric  or type2.is_enum)
William Stein's avatar
William Stein committed
7989 7990

    def calculate_result_code(self):
7991 7992
        if self.infix:
            return "(%s %s %s)" % (
7993 7994
                self.operand1.result(),
                self.operator,
7995 7996
                self.operand2.result())
        else:
7997 7998 7999
            func = self.type.binary_op(self.operator)
            if func is None:
                error(self.pos, "binary operator %s not supported for %s" % (self.operator, self.type))
8000
            return "%s(%s, %s)" % (
8001
                func,
8002 8003
                self.operand1.result(),
                self.operand2.result())
8004

8005
    def is_py_operation_types(self, type1, type2):
Stefan Behnel's avatar
Stefan Behnel committed
8006 8007
        return (type1.is_unicode_char or
                type2.is_unicode_char or
8008
                BinopNode.is_py_operation_types(self, type1, type2))
8009

William Stein's avatar
William Stein committed
8010
    def py_operation_function(self):
8011 8012 8013 8014
        fuction = self.py_functions[self.operator]
        if self.inplace:
            fuction = fuction.replace('PyNumber_', 'PyNumber_InPlace')
        return fuction
William Stein's avatar
William Stein committed
8015 8016

    py_functions = {
Robert Bradshaw's avatar
Robert Bradshaw committed
8017 8018 8019
        "|":        "PyNumber_Or",
        "^":        "PyNumber_Xor",
        "&":        "PyNumber_And",
8020 8021
        "<<":       "PyNumber_Lshift",
        ">>":       "PyNumber_Rshift",
Robert Bradshaw's avatar
Robert Bradshaw committed
8022 8023 8024 8025
        "+":        "PyNumber_Add",
        "-":        "PyNumber_Subtract",
        "*":        "PyNumber_Multiply",
        "/":        "__Pyx_PyNumber_Divide",
8026
        "//":       "PyNumber_FloorDivide",
Robert Bradshaw's avatar
Robert Bradshaw committed
8027
        "%":        "PyNumber_Remainder",
8028
        "**":       "PyNumber_Power"
William Stein's avatar
William Stein committed
8029 8030 8031 8032
    }

class IntBinopNode(NumBinopNode):
    #  Binary operation taking integer arguments.
8033

William Stein's avatar
William Stein committed
8034
    def c_types_okay(self, type1, type2):
8035 8036 8037
        #print "IntBinopNode.c_types_okay:", type1, type2 ###
        return (type1.is_int or type1.is_enum) \
            and (type2.is_int or type2.is_enum)
William Stein's avatar
William Stein committed
8038

8039

William Stein's avatar
William Stein committed
8040 8041
class AddNode(NumBinopNode):
    #  '+' operator.
8042

8043 8044 8045
    def is_py_operation_types(self, type1, type2):
        if type1.is_string and type2.is_string:
            return 1
William Stein's avatar
William Stein committed
8046
        else:
8047
            return NumBinopNode.is_py_operation_types(self, type1, type2)
William Stein's avatar
William Stein committed
8048 8049

    def compute_c_result_type(self, type1, type2):
8050 8051
        #print "AddNode.compute_c_result_type:", type1, self.operator, type2 ###
        if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
William Stein's avatar
William Stein committed
8052
            return type1
8053
        elif (type2.is_ptr or type2.is_array) and (type1.is_int or type1.is_enum):
William Stein's avatar
William Stein committed
8054 8055 8056 8057 8058 8059 8060 8061
            return type2
        else:
            return NumBinopNode.compute_c_result_type(
                self, type1, type2)


class SubNode(NumBinopNode):
    #  '-' operator.
8062

William Stein's avatar
William Stein committed
8063
    def compute_c_result_type(self, type1, type2):
8064
        if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
William Stein's avatar
William Stein committed
8065
            return type1
8066
        elif (type1.is_ptr or type1.is_array) and (type2.is_ptr or type2.is_array):
William Stein's avatar
William Stein committed
8067 8068 8069 8070 8071 8072 8073 8074
            return PyrexTypes.c_int_type
        else:
            return NumBinopNode.compute_c_result_type(
                self, type1, type2)


class MulNode(NumBinopNode):
    #  '*' operator.
8075

8076
    def is_py_operation_types(self, type1, type2):
William Stein's avatar
William Stein committed
8077 8078 8079 8080
        if (type1.is_string and type2.is_int) \
            or (type2.is_string and type1.is_int):
                return 1
        else:
8081
            return NumBinopNode.is_py_operation_types(self, type1, type2)
William Stein's avatar
William Stein committed
8082 8083


8084 8085
class DivNode(NumBinopNode):
    #  '/' or '//' operator.
8086

8087
    cdivision = None
8088 8089
    truedivision = None   # == "unknown" if operator == '/'
    ctruedivision = False
Robert Bradshaw's avatar
Robert Bradshaw committed
8090
    cdivision_warnings = False
8091
    zerodivision_check = None
8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113

    def find_compile_time_binary_operator(self, op1, op2):
        func = compile_time_binary_operators[self.operator]
        if self.operator == '/' and self.truedivision is None:
            # => true div for floats, floor div for integers
            if isinstance(op1, (int,long)) and isinstance(op2, (int,long)):
                func = compile_time_binary_operators['//']
        return func

    def calculate_constant_result(self):
        op1 = self.operand1.constant_result
        op2 = self.operand2.constant_result
        func = self.find_compile_time_binary_operator(op1, op2)
        self.constant_result = func(
            self.operand1.constant_result,
            self.operand2.constant_result)

    def compile_time_value(self, denv):
        operand1 = self.operand1.compile_time_value(denv)
        operand2 = self.operand2.compile_time_value(denv)
        try:
            func = self.find_compile_time_binary_operator(
Robert Bradshaw's avatar
Robert Bradshaw committed
8114
                operand1, operand2)
8115 8116 8117 8118
            return func(operand1, operand2)
        except Exception, e:
            self.compile_time_value_error(e)

Robert Bradshaw's avatar
Robert Bradshaw committed
8119
    def analyse_operation(self, env):
8120 8121 8122 8123
        if self.cdivision or env.directives['cdivision']:
            self.ctruedivision = False
        else:
            self.ctruedivision = self.truedivision
Robert Bradshaw's avatar
Robert Bradshaw committed
8124
        NumBinopNode.analyse_operation(self, env)
8125 8126
        if self.is_cpp_operation():
            self.cdivision = True
8127
        if not self.type.is_pyobject:
8128 8129
            self.zerodivision_check = (
                self.cdivision is None and not env.directives['cdivision']
8130
                and (not self.operand2.has_constant_result() or
8131
                     self.operand2.constant_result == 0))
8132 8133 8134 8135
            if self.zerodivision_check or env.directives['cdivision_warnings']:
                # Need to check ahead of time to warn or raise zero division error
                self.operand1 = self.operand1.coerce_to_simple(env)
                self.operand2 = self.operand2.coerce_to_simple(env)
8136 8137
                if env.nogil:
                    error(self.pos, "Pythonic division not allowed without gil, consider using cython.cdivision(True)")
8138 8139 8140 8141 8142 8143 8144 8145 8146

    def compute_c_result_type(self, type1, type2):
        if self.operator == '/' and self.ctruedivision:
            if not type1.is_float and not type2.is_float:
                widest_type = PyrexTypes.widest_numeric_type(type1, PyrexTypes.c_double_type)
                widest_type = PyrexTypes.widest_numeric_type(type2, widest_type)
                return widest_type
        return NumBinopNode.compute_c_result_type(self, type1, type2)

8147 8148 8149 8150 8151
    def zero_division_message(self):
        if self.type.is_int:
            return "integer division or modulo by zero"
        else:
            return "float division"
Robert Bradshaw's avatar
Robert Bradshaw committed
8152

8153
    def generate_evaluation_code(self, code):
8154
        if not self.type.is_pyobject and not self.type.is_complex:
8155
            if self.cdivision is None:
8156
                self.cdivision = (code.globalstate.directives['cdivision']
8157 8158 8159
                                    or not self.type.signed
                                    or self.type.is_float)
            if not self.cdivision:
8160
                code.globalstate.use_utility_code(div_int_utility_code.specialize(self.type))
8161
        NumBinopNode.generate_evaluation_code(self, code)
8162
        self.generate_div_warning_code(code)
8163

8164
    def generate_div_warning_code(self, code):
8165 8166
        if not self.type.is_pyobject:
            if self.zerodivision_check:
8167 8168 8169 8170 8171
                if not self.infix:
                    zero_test = "%s(%s)" % (self.type.unary_op('zero'), self.operand2.result())
                else:
                    zero_test = "%s == 0" % self.operand2.result()
                code.putln("if (unlikely(%s)) {" % zero_test)
8172 8173 8174
                code.putln('PyErr_Format(PyExc_ZeroDivisionError, "%s");' % self.zero_division_message())
                code.putln(code.error_goto(self.pos))
                code.putln("}")
8175 8176 8177
                if self.type.is_int and self.type.signed and self.operator != '%':
                    code.globalstate.use_utility_code(division_overflow_test_code)
                    code.putln("else if (sizeof(%s) == sizeof(long) && unlikely(%s == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(%s))) {" % (
8178
                                    self.type.declaration_code(''),
8179 8180 8181 8182 8183
                                    self.operand2.result(),
                                    self.operand1.result()))
                    code.putln('PyErr_Format(PyExc_OverflowError, "value too large to perform division");')
                    code.putln(code.error_goto(self.pos))
                    code.putln("}")
Robert Bradshaw's avatar
Robert Bradshaw committed
8184
            if code.globalstate.directives['cdivision_warnings'] and self.operator != '/':
8185 8186 8187 8188 8189
                code.globalstate.use_utility_code(cdivision_warning_utility_code)
                code.putln("if ((%s < 0) ^ (%s < 0)) {" % (
                                self.operand1.result(),
                                self.operand2.result()))
                code.putln(code.set_error_info(self.pos));
8190 8191 8192 8193 8194 8195
                code.put("if (__Pyx_cdivision_warning(%(FILENAME)s, "
                                                     "%(LINENO)s)) " % {
                    'FILENAME': Naming.filename_cname,
                    'LINENO':  Naming.lineno_cname,
                    })

8196 8197
                code.put_goto(code.error_label)
                code.putln("}")
8198

Robert Bradshaw's avatar
Robert Bradshaw committed
8199
    def calculate_result_code(self):
8200 8201 8202
        if self.type.is_complex:
            return NumBinopNode.calculate_result_code(self)
        elif self.type.is_float and self.operator == '//':
8203
            return "floor(%s / %s)" % (
8204
                self.operand1.result(),
8205
                self.operand2.result())
8206 8207 8208 8209 8210 8211 8212 8213 8214
        elif self.truedivision or self.cdivision:
            op1 = self.operand1.result()
            op2 = self.operand2.result()
            if self.truedivision:
                if self.type != self.operand1.type:
                    op1 = self.type.cast_code(op1)
                if self.type != self.operand2.type:
                    op2 = self.type.cast_code(op2)
            return "(%s / %s)" % (op1, op2)
8215 8216
        else:
            return "__Pyx_div_%s(%s, %s)" % (
Craig Citro's avatar
Craig Citro committed
8217
                    self.type.specialization_name(),
8218
                    self.operand1.result(),
8219
                    self.operand2.result())
Robert Bradshaw's avatar
Robert Bradshaw committed
8220 8221


Robert Bradshaw's avatar
Robert Bradshaw committed
8222
class ModNode(DivNode):
William Stein's avatar
William Stein committed
8223
    #  '%' operator.
8224

8225 8226 8227 8228
    def is_py_operation_types(self, type1, type2):
        return (type1.is_string
            or type2.is_string
            or NumBinopNode.is_py_operation_types(self, type1, type2))
William Stein's avatar
William Stein committed
8229

8230 8231 8232 8233 8234
    def zero_division_message(self):
        if self.type.is_int:
            return "integer division or modulo by zero"
        else:
            return "float divmod()"
8235

8236
    def generate_evaluation_code(self, code):
8237 8238 8239 8240 8241
        if not self.type.is_pyobject:
            if self.cdivision is None:
                self.cdivision = code.globalstate.directives['cdivision'] or not self.type.signed
            if not self.cdivision:
                if self.type.is_int:
8242
                    code.globalstate.use_utility_code(mod_int_utility_code.specialize(self.type))
8243
                else:
8244 8245
                    code.globalstate.use_utility_code(
                        mod_float_utility_code.specialize(self.type, math_h_modifier=self.type.math_h_modifier))
8246
        NumBinopNode.generate_evaluation_code(self, code)
8247
        self.generate_div_warning_code(code)
8248

Robert Bradshaw's avatar
Robert Bradshaw committed
8249
    def calculate_result_code(self):
8250 8251 8252 8253
        if self.cdivision:
            if self.type.is_float:
                return "fmod%s(%s, %s)" % (
                    self.type.math_h_modifier,
8254
                    self.operand1.result(),
8255 8256 8257
                    self.operand2.result())
            else:
                return "(%s %% %s)" % (
8258
                    self.operand1.result(),
8259
                    self.operand2.result())
Robert Bradshaw's avatar
Robert Bradshaw committed
8260
        else:
8261
            return "__Pyx_mod_%s(%s, %s)" % (
Craig Citro's avatar
Craig Citro committed
8262
                    self.type.specialization_name(),
8263
                    self.operand1.result(),
8264
                    self.operand2.result())
William Stein's avatar
William Stein committed
8265 8266 8267

class PowNode(NumBinopNode):
    #  '**' operator.
8268

Robert Bradshaw's avatar
Robert Bradshaw committed
8269 8270
    def analyse_c_operation(self, env):
        NumBinopNode.analyse_c_operation(self, env)
8271
        if self.type.is_complex:
Robert Bradshaw's avatar
Robert Bradshaw committed
8272 8273 8274 8275 8276 8277 8278
            if self.type.real_type.is_float:
                self.operand1 = self.operand1.coerce_to(self.type, env)
                self.operand2 = self.operand2.coerce_to(self.type, env)
                self.pow_func = "__Pyx_c_pow" + self.type.real_type.math_h_modifier
            else:
                error(self.pos, "complex int powers not supported")
                self.pow_func = "<error>"
8279
        elif self.type.is_float:
8280
            self.pow_func = "pow" + self.type.math_h_modifier
William Stein's avatar
William Stein committed
8281
        else:
Robert Bradshaw's avatar
Robert Bradshaw committed
8282 8283
            self.pow_func = "__Pyx_pow_%s" % self.type.declaration_code('').replace(' ', '_')
            env.use_utility_code(
8284
                    int_pow_utility_code.specialize(func_name=self.pow_func,
Robert Bradshaw's avatar
Robert Bradshaw committed
8285
                                                type=self.type.declaration_code('')))
8286

William Stein's avatar
William Stein committed
8287
    def calculate_result_code(self):
8288 8289 8290 8291 8292 8293
        # Work around MSVC overloading ambiguity.
        def typecast(operand):
            if self.type == operand.type:
                return operand.result()
            else:
                return self.type.cast_code(operand.result())
Robert Bradshaw's avatar
Robert Bradshaw committed
8294
        return "%s(%s, %s)" % (
8295 8296
            self.pow_func,
            typecast(self.operand1),
8297
            typecast(self.operand2))
8298

William Stein's avatar
William Stein committed
8299

Craig Citro's avatar
Craig Citro committed
8300
# Note: This class is temporarily "shut down" into an ineffective temp
8301 8302
# allocation mode.
#
Craig Citro's avatar
Craig Citro committed
8303 8304 8305
# More sophisticated temp reuse was going on before, one could have a
# look at adding this again after /all/ classes are converted to the
# new temp scheme. (The temp juggling cannot work otherwise).
8306
class BoolBinopNode(ExprNode):
William Stein's avatar
William Stein committed
8307 8308 8309 8310 8311
    #  Short-circuiting boolean operation.
    #
    #  operator     string
    #  operand1     ExprNode
    #  operand2     ExprNode
8312

8313
    subexprs = ['operand1', 'operand2']
8314

8315
    def infer_type(self, env):
8316 8317
        type1 = self.operand1.infer_type(env)
        type2 = self.operand2.infer_type(env)
8318
        return PyrexTypes.independent_spanning_type(type1, type2)
8319

Stefan Behnel's avatar
Stefan Behnel committed
8320 8321 8322 8323 8324 8325
    def may_be_none(self):
        if self.operator == 'or':
            return self.operand2.may_be_none()
        else:
            return self.operand1.may_be_none() or self.operand2.may_be_none()

8326 8327 8328 8329 8330 8331 8332 8333 8334
    def calculate_constant_result(self):
        if self.operator == 'and':
            self.constant_result = \
                self.operand1.constant_result and \
                self.operand2.constant_result
        else:
            self.constant_result = \
                self.operand1.constant_result or \
                self.operand2.constant_result
8335

8336 8337 8338 8339 8340 8341 8342
    def compile_time_value(self, denv):
        if self.operator == 'and':
            return self.operand1.compile_time_value(denv) \
                and self.operand2.compile_time_value(denv)
        else:
            return self.operand1.compile_time_value(denv) \
                or self.operand2.compile_time_value(denv)
8343

8344
    def coerce_to_boolean(self, env):
8345 8346 8347 8348 8349 8350 8351
        return BoolBinopNode(
            self.pos,
            operator = self.operator,
            operand1 = self.operand1.coerce_to_boolean(env),
            operand2 = self.operand2.coerce_to_boolean(env),
            type = PyrexTypes.c_bint_type,
            is_temp = self.is_temp)
8352

William Stein's avatar
William Stein committed
8353 8354 8355
    def analyse_types(self, env):
        self.operand1.analyse_types(env)
        self.operand2.analyse_types(env)
8356
        self.type = PyrexTypes.independent_spanning_type(self.operand1.type, self.operand2.type)
8357 8358
        self.operand1 = self.operand1.coerce_to(self.type, env)
        self.operand2 = self.operand2.coerce_to(self.type, env)
8359

William Stein's avatar
William Stein committed
8360 8361
        # For what we're about to do, it's vital that
        # both operands be temp nodes.
8362 8363
        self.operand1 = self.operand1.coerce_to_simple(env)
        self.operand2 = self.operand2.coerce_to_simple(env)
William Stein's avatar
William Stein committed
8364
        self.is_temp = 1
8365 8366 8367

    gil_message = "Truth-testing Python object"

William Stein's avatar
William Stein committed
8368
    def check_const(self):
8369
        return self.operand1.check_const() and self.operand2.check_const()
8370

William Stein's avatar
William Stein committed
8371
    def generate_evaluation_code(self, code):
8372
        code.mark_pos(self.pos)
William Stein's avatar
William Stein committed
8373
        self.operand1.generate_evaluation_code(code)
8374
        test_result, uses_temp = self.generate_operand1_test(code)
William Stein's avatar
William Stein committed
8375 8376 8377 8378 8379 8380 8381 8382
        if self.operator == 'and':
            sense = ""
        else:
            sense = "!"
        code.putln(
            "if (%s%s) {" % (
                sense,
                test_result))
8383 8384
        if uses_temp:
            code.funcstate.release_temp(test_result)
8385
        self.operand1.generate_disposal_code(code)
William Stein's avatar
William Stein committed
8386
        self.operand2.generate_evaluation_code(code)
8387
        self.allocate_temp_result(code)
8388
        self.operand2.make_owned_reference(code)
8389
        code.putln("%s = %s;" % (self.result(), self.operand2.result()))
8390 8391
        self.operand2.generate_post_assignment_code(code)
        self.operand2.free_temps(code)
8392
        code.putln("} else {")
8393
        self.operand1.make_owned_reference(code)
8394
        code.putln("%s = %s;" % (self.result(), self.operand1.result()))
8395 8396
        self.operand1.generate_post_assignment_code(code)
        self.operand1.free_temps(code)
8397
        code.putln("}")
8398

William Stein's avatar
William Stein committed
8399 8400 8401
    def generate_operand1_test(self, code):
        #  Generate code to test the truth of the first operand.
        if self.type.is_pyobject:
8402 8403
            test_result = code.funcstate.allocate_temp(PyrexTypes.c_bint_type,
                                                       manage_ref=False)
William Stein's avatar
William Stein committed
8404
            code.putln(
8405
                "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
William Stein's avatar
William Stein committed
8406 8407
                    test_result,
                    self.operand1.py_result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
8408
                    code.error_goto_if_neg(test_result, self.pos)))
William Stein's avatar
William Stein committed
8409
        else:
8410
            test_result = self.operand1.result()
8411
        return (test_result, self.type.is_pyobject)
William Stein's avatar
William Stein committed
8412 8413


8414
class CondExprNode(ExprNode):
Robert Bradshaw's avatar
Robert Bradshaw committed
8415 8416 8417 8418 8419
    #  Short-circuiting conditional expression.
    #
    #  test        ExprNode
    #  true_val    ExprNode
    #  false_val   ExprNode
8420

8421 8422
    true_val = None
    false_val = None
8423

Robert Bradshaw's avatar
Robert Bradshaw committed
8424
    subexprs = ['test', 'true_val', 'false_val']
8425

Robert Bradshaw's avatar
Robert Bradshaw committed
8426 8427
    def type_dependencies(self, env):
        return self.true_val.type_dependencies(env) + self.false_val.type_dependencies(env)
8428

Robert Bradshaw's avatar
Robert Bradshaw committed
8429
    def infer_type(self, env):
8430 8431
        return PyrexTypes.independent_spanning_type(self.true_val.infer_type(env),
                                                    self.false_val.infer_type(env))
8432 8433 8434 8435 8436 8437 8438

    def calculate_constant_result(self):
        if self.test.constant_result:
            self.constant_result = self.true_val.constant_result
        else:
            self.constant_result = self.false_val.constant_result

Robert Bradshaw's avatar
Robert Bradshaw committed
8439 8440 8441 8442 8443
    def analyse_types(self, env):
        self.test.analyse_types(env)
        self.test = self.test.coerce_to_boolean(env)
        self.true_val.analyse_types(env)
        self.false_val.analyse_types(env)
8444
        self.type = PyrexTypes.independent_spanning_type(self.true_val.type, self.false_val.type)
8445 8446 8447 8448 8449
        if self.true_val.type.is_pyobject or self.false_val.type.is_pyobject:
            self.true_val = self.true_val.coerce_to(self.type, env)
            self.false_val = self.false_val.coerce_to(self.type, env)
        self.is_temp = 1
        if self.type == PyrexTypes.error_type:
Robert Bradshaw's avatar
Robert Bradshaw committed
8450
            self.type_error()
8451

Robert Bradshaw's avatar
Robert Bradshaw committed
8452 8453 8454 8455 8456
    def type_error(self):
        if not (self.true_val.type.is_error or self.false_val.type.is_error):
            error(self.pos, "Incompatable types in conditional expression (%s; %s)" %
                (self.true_val.type, self.false_val.type))
        self.type = PyrexTypes.error_type
8457

Robert Bradshaw's avatar
Robert Bradshaw committed
8458
    def check_const(self):
8459
        return (self.test.check_const()
8460 8461
            and self.true_val.check_const()
            and self.false_val.check_const())
8462

Robert Bradshaw's avatar
Robert Bradshaw committed
8463
    def generate_evaluation_code(self, code):
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
8464 8465
        # Because subexprs may not be evaluated we can use a more optimal
        # subexpr allocation strategy than the default, so override evaluation_code.
8466

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
8467
        code.mark_pos(self.pos)
8468
        self.allocate_temp_result(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
8469
        self.test.generate_evaluation_code(code)
8470
        code.putln("if (%s) {" % self.test.result() )
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
8471
        self.eval_and_get(code, self.true_val)
Robert Bradshaw's avatar
Robert Bradshaw committed
8472
        code.putln("} else {")
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
8473
        self.eval_and_get(code, self.false_val)
Robert Bradshaw's avatar
Robert Bradshaw committed
8474 8475
        code.putln("}")
        self.test.generate_disposal_code(code)
8476
        self.test.free_temps(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
8477

Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
8478 8479 8480
    def eval_and_get(self, code, expr):
        expr.generate_evaluation_code(code)
        expr.make_owned_reference(code)
8481
        code.putln('%s = %s;' % (self.result(), expr.result_as(self.ctype())))
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
8482 8483 8484
        expr.generate_post_assignment_code(code)
        expr.free_temps(code)

8485 8486 8487 8488 8489 8490 8491 8492 8493 8494
richcmp_constants = {
    "<" : "Py_LT",
    "<=": "Py_LE",
    "==": "Py_EQ",
    "!=": "Py_NE",
    "<>": "Py_NE",
    ">" : "Py_GT",
    ">=": "Py_GE",
}

8495
class CmpNode(object):
William Stein's avatar
William Stein committed
8496 8497
    #  Mixin class containing code common to PrimaryCmpNodes
    #  and CascadedCmpNodes.
8498 8499 8500

    special_bool_cmp_function = None

Stefan Behnel's avatar
typo  
Stefan Behnel committed
8501
    def infer_type(self, env):
8502 8503
        # TODO: Actually implement this (after merging with -unstable).
        return py_object_type
8504 8505 8506 8507 8508

    def calculate_cascaded_constant_result(self, operand1_result):
        func = compile_time_binary_operators[self.operator]
        operand2_result = self.operand2.constant_result
        result = func(operand1_result, operand2_result)
8509 8510 8511 8512 8513 8514 8515
        if self.cascade:
            self.cascade.calculate_cascaded_constant_result(operand2_result)
            if self.cascade.constant_result:
                self.constant_result = result and self.cascade.constant_result
        else:
            self.constant_result = result

8516 8517
    def cascaded_compile_time_value(self, operand1, denv):
        func = get_compile_time_binop(self)
8518
        operand2 = self.operand2.compile_time_value(denv)
8519 8520 8521 8522
        try:
            result = func(operand1, operand2)
        except Exception, e:
            self.compile_time_value_error(e)
8523
            result = None
8524 8525 8526
        if result:
            cascade = self.cascade
            if cascade:
8527
                # FIXME: I bet this must call cascaded_compile_time_value()
8528
                result = result and cascade.cascaded_compile_time_value(operand2, denv)
8529 8530
        return result

8531
    def is_cpp_comparison(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
8532
        return self.operand1.type.is_cpp_class or self.operand2.type.is_cpp_class
8533

8534
    def find_common_int_type(self, env, op, operand1, operand2):
8535 8536 8537 8538 8539 8540
        # type1 != type2 and at least one of the types is not a C int
        type1 = operand1.type
        type2 = operand2.type
        type1_can_be_int = False
        type2_can_be_int = False

8541
        if operand1.is_string_literal and operand1.can_coerce_to_char_literal():
8542
            type1_can_be_int = True
8543
        if operand2.is_string_literal and operand2.can_coerce_to_char_literal():
8544 8545 8546 8547
            type2_can_be_int = True

        if type1.is_int:
            if type2_can_be_int:
8548
                return type1
8549 8550
        elif type2.is_int:
            if type1_can_be_int:
8551
                return type2
8552 8553
        elif type1_can_be_int:
            if type2_can_be_int:
8554
                return PyrexTypes.c_uchar_type
William Stein's avatar
William Stein committed
8555

8556
        return None
8557

8558
    def find_common_type(self, env, op, operand1, common_type=None):
8559
        operand2 = self.operand2
William Stein's avatar
William Stein committed
8560 8561
        type1 = operand1.type
        type2 = operand2.type
8562

8563 8564
        new_common_type = None

Stefan Behnel's avatar
Stefan Behnel committed
8565
        # catch general errors
8566 8567 8568
        if type1 == str_type and (type2.is_string or type2 in (bytes_type, unicode_type)) or \
               type2 == str_type and (type1.is_string or type1 in (bytes_type, unicode_type)):
            error(self.pos, "Comparisons between bytes/unicode and str are not portable to Python 3")
8569
            new_common_type = error_type
Stefan Behnel's avatar
Stefan Behnel committed
8570 8571

        # try to use numeric comparisons where possible
8572
        elif type1.is_complex or type2.is_complex:
8573 8574 8575
            if op not in ('==', '!=') \
               and (type1.is_complex or type1.is_numeric) \
               and (type2.is_complex or type2.is_numeric):
8576 8577
                error(self.pos, "complex types are unordered")
                new_common_type = error_type
8578
            elif type1.is_pyobject:
8579 8580 8581
                new_common_type = type1
            elif type2.is_pyobject:
                new_common_type = type2
8582
            else:
8583
                new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
8584 8585
        elif type1.is_numeric and type2.is_numeric:
            new_common_type = PyrexTypes.widest_numeric_type(type1, type2)
8586
        elif common_type is None or not common_type.is_pyobject:
8587
            new_common_type = self.find_common_int_type(env, op, operand1, operand2)
8588 8589

        if new_common_type is None:
Stefan Behnel's avatar
Stefan Behnel committed
8590
            # fall back to generic type compatibility tests
8591
            if type1 == type2:
8592 8593 8594 8595 8596 8597
                new_common_type = type1
            elif type1.is_pyobject or type2.is_pyobject:
                if type2.is_numeric or type2.is_string:
                    if operand2.check_for_coercion_error(type1):
                        new_common_type = error_type
                    else:
Robert Bradshaw's avatar
Robert Bradshaw committed
8598
                        new_common_type = py_object_type
8599 8600 8601 8602
                elif type1.is_numeric or type1.is_string:
                    if operand1.check_for_coercion_error(type2):
                        new_common_type = error_type
                    else:
Robert Bradshaw's avatar
Robert Bradshaw committed
8603 8604 8605
                        new_common_type = py_object_type
                elif py_object_type.assignable_from(type1) and py_object_type.assignable_from(type2):
                    new_common_type = py_object_type
8606 8607 8608 8609
                else:
                    # one Python type and one non-Python type, not assignable
                    self.invalid_types_error(operand1, op, operand2)
                    new_common_type = error_type
8610 8611 8612 8613
            elif type1.assignable_from(type2):
                new_common_type = type1
            elif type2.assignable_from(type1):
                new_common_type = type2
8614 8615 8616 8617
            else:
                # C types that we couldn't handle up to here are an error
                self.invalid_types_error(operand1, op, operand2)
                new_common_type = error_type
8618

8619 8620 8621 8622 8623 8624
        if new_common_type.is_string and (isinstance(operand1, BytesNode) or
                                          isinstance(operand2, BytesNode)):
            # special case when comparing char* to bytes literal: must
            # compare string values!
            new_common_type = bytes_type

Stefan Behnel's avatar
Stefan Behnel committed
8625
        # recursively merge types
8626
        if common_type is None or new_common_type.is_error:
8627
            common_type = new_common_type
William Stein's avatar
William Stein committed
8628
        else:
8629 8630 8631
            # we could do a lot better by splitting the comparison
            # into a non-Python part and a Python part, but this is
            # safer for now
8632
            common_type = PyrexTypes.spanning_type(common_type, new_common_type)
8633 8634

        if self.cascade:
8635
            common_type = self.cascade.find_common_type(env, self.operator, operand2, common_type)
8636

8637 8638
        return common_type

8639 8640 8641 8642
    def invalid_types_error(self, operand1, op, operand2):
        error(self.pos, "Invalid types for '%s' (%s, %s)" %
              (op, operand1.type, operand2.type))

Stefan Behnel's avatar
Stefan Behnel committed
8643
    def is_python_comparison(self):
8644 8645 8646 8647 8648
        return (not self.is_ptr_contains()
            and not self.is_c_string_contains()
            and (self.has_python_operands()
                 or (self.cascade and self.cascade.is_python_comparison())
                 or self.operator in ('in', 'not_in')))
Stefan Behnel's avatar
Stefan Behnel committed
8649

8650 8651 8652 8653 8654 8655
    def coerce_operands_to(self, dst_type, env):
        operand2 = self.operand2
        if operand2.type != dst_type:
            self.operand2 = operand2.coerce_to(dst_type, env)
        if self.cascade:
            self.cascade.coerce_operands_to(dst_type, env)
8656

8657
    def is_python_result(self):
8658
        return ((self.has_python_operands() and
8659
                 self.special_bool_cmp_function is None and
8660
                 self.operator not in ('is', 'is_not', 'in', 'not_in') and
8661 8662
                 not self.is_c_string_contains() and
                 not self.is_ptr_contains())
8663
            or (self.cascade and self.cascade.is_python_result()))
William Stein's avatar
William Stein committed
8664

8665 8666
    def is_c_string_contains(self):
        return self.operator in ('in', 'not_in') and \
8667 8668
               ((self.operand1.type.is_int
                 and (self.operand2.type.is_string or self.operand2.type is bytes_type)) or
Stefan Behnel's avatar
Stefan Behnel committed
8669
                (self.operand1.type.is_unicode_char
8670
                 and self.operand2.type is unicode_type))
8671

8672 8673
    def is_ptr_contains(self):
        if self.operator in ('in', 'not_in'):
8674 8675 8676
            container_type = self.operand2.type
            return (container_type.is_ptr or container_type.is_array) \
                and not container_type.is_string
8677

8678 8679 8680 8681 8682
    def find_special_bool_compare_function(self, env):
        if self.operator in ('==', '!='):
            type1, type2 = self.operand1.type, self.operand2.type
            if type1.is_pyobject and type2.is_pyobject:
                if type1 is Builtin.unicode_type or type2 is Builtin.unicode_type:
8683
                    env.use_utility_code(UtilityCode.load_cached("UnicodeEquals", "StringTools.c"))
8684 8685
                    self.special_bool_cmp_function = "__Pyx_PyUnicode_Equals"
                    return True
8686
                elif type1 is Builtin.bytes_type or type2 is Builtin.bytes_type:
8687
                    env.use_utility_code(UtilityCode.load_cached("BytesEquals", "StringTools.c"))
8688 8689 8690
                    self.special_bool_cmp_function = "__Pyx_PyBytes_Equals"
                    return True
                elif type1 is Builtin.str_type or type2 is Builtin.str_type:
8691
                    env.use_utility_code(UtilityCode.load_cached("StrEquals", "StringTools.c"))
8692 8693
                    self.special_bool_cmp_function = "__Pyx_PyString_Equals"
                    return True
8694 8695
        return False

8696
    def generate_operation_code(self, code, result_code,
William Stein's avatar
William Stein committed
8697
            operand1, op , operand2):
8698
        if self.type.is_pyobject:
8699 8700 8701
            coerce_result = "__Pyx_PyBool_FromLong"
        else:
            coerce_result = ""
8702
        if 'not' in op:
8703
            negation = "!"
8704
        else:
8705
            negation = ""
8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722
        if self.special_bool_cmp_function:
            if operand1.type.is_pyobject:
                result1 = operand1.py_result()
            else:
                result1 = operand1.result()
            if operand2.type.is_pyobject:
                result2 = operand2.py_result()
            else:
                result2 = operand2.result()
            code.putln("%s = %s(%s, %s, %s); %s" % (
                result_code,
                self.special_bool_cmp_function,
                result1,
                result2,
                richcmp_constants[op],
                code.error_goto_if_neg(result_code, self.pos)))
        elif op == 'in' or op == 'not_in':
Stefan Behnel's avatar
typo  
Stefan Behnel committed
8723
            code.globalstate.use_utility_code(contains_utility_code)
8724
            if self.type.is_pyobject:
8725
                coerce_result = "__Pyx_PyBoolOrNull_FromLong"
8726
            if op == 'not_in':
8727
                negation = "__Pyx_NegateNonNeg"
8728
            if operand2.type is dict_type:
8729
                method = "PyDict_Contains"
8730
            else:
8731
                method = "PySequence_Contains"
8732
            if self.type.is_pyobject:
8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743
                error_clause = code.error_goto_if_null
                got_ref = "__Pyx_XGOTREF(%s); " % result_code
            else:
                error_clause = code.error_goto_if_neg
                got_ref = ""
            code.putln(
                "%s = %s(%s(%s(%s, %s))); %s%s" % (
                    result_code,
                    coerce_result,
                    negation,
                    method,
8744 8745
                    operand2.py_result(),
                    operand1.py_result(),
8746 8747
                    got_ref,
                    error_clause(result_code, self.pos)))
William Stein's avatar
William Stein committed
8748 8749
        elif (operand1.type.is_pyobject
            and op not in ('is', 'is_not')):
8750
                code.putln("%s = PyObject_RichCompare(%s, %s, %s); %s" % (
8751 8752 8753
                        result_code,
                        operand1.py_result(),
                        operand2.py_result(),
8754 8755
                        richcmp_constants[op],
                        code.error_goto_if_null(result_code, self.pos)))
8756
                code.put_gotref(result_code)
8757
        elif operand1.type.is_complex:
8758
            if op == "!=":
8759
                negation = "!"
8760
            else:
8761
                negation = ""
8762
            code.putln("%s = %s(%s%s(%s, %s));" % (
8763
                result_code,
8764 8765
                coerce_result,
                negation,
8766 8767
                operand1.type.unary_op('eq'),
                operand1.result(),
8768
                operand2.result()))
William Stein's avatar
William Stein committed
8769
        else:
8770 8771 8772 8773 8774
            type1 = operand1.type
            type2 = operand2.type
            if (type1.is_extension_type or type2.is_extension_type) \
                    and not type1.same_as(type2):
                common_type = py_object_type
8775 8776
            elif type1.is_numeric:
                common_type = PyrexTypes.widest_numeric_type(type1, type2)
8777
            else:
8778 8779 8780
                common_type = type1
            code1 = operand1.result_as(common_type)
            code2 = operand2.result_as(common_type)
8781
            code.putln("%s = %s(%s %s %s);" % (
8782 8783 8784 8785
                result_code,
                coerce_result,
                code1,
                self.c_operator(op),
8786 8787
                code2))

William Stein's avatar
William Stein committed
8788 8789 8790 8791 8792 8793 8794
    def c_operator(self, op):
        if op == 'is':
            return "=="
        elif op == 'is_not':
            return "!="
        else:
            return op
8795

Stefan Behnel's avatar
typo  
Stefan Behnel committed
8796
contains_utility_code = UtilityCode(
8797
proto="""
8798 8799
static CYTHON_INLINE int __Pyx_NegateNonNeg(int b) {
    return unlikely(b < 0) ? b : !b;
Lisandro Dalcin's avatar
Lisandro Dalcin committed
8800
}
8801
static CYTHON_INLINE PyObject* __Pyx_PyBoolOrNull_FromLong(long b) {
8802 8803 8804 8805
    return unlikely(b < 0) ? NULL : __Pyx_PyBool_FromLong(b);
}
""")

William Stein's avatar
William Stein committed
8806

8807
class PrimaryCmpNode(ExprNode, CmpNode):
William Stein's avatar
William Stein committed
8808 8809 8810 8811 8812 8813 8814
    #  Non-cascaded comparison or first comparison of
    #  a cascaded sequence.
    #
    #  operator      string
    #  operand1      ExprNode
    #  operand2      ExprNode
    #  cascade       CascadedCmpNode
8815

William Stein's avatar
William Stein committed
8816 8817 8818 8819
    #  We don't use the subexprs mechanism, because
    #  things here are too complicated for it to handle.
    #  Instead, we override all the framework methods
    #  which use it.
8820

Robert Bradshaw's avatar
Robert Bradshaw committed
8821
    child_attrs = ['operand1', 'operand2', 'cascade']
8822

William Stein's avatar
William Stein committed
8823
    cascade = None
8824
    is_memslice_nonecheck = False
8825

Robert Bradshaw's avatar
Robert Bradshaw committed
8826 8827 8828 8829 8830 8831 8832
    def infer_type(self, env):
        # TODO: Actually implement this (after merging with -unstable).
        return py_object_type

    def type_dependencies(self, env):
        return ()

8833
    def calculate_constant_result(self):
8834
        self.calculate_cascaded_constant_result(self.operand1.constant_result)
8835

8836
    def compile_time_value(self, denv):
8837
        operand1 = self.operand1.compile_time_value(denv)
8838 8839
        return self.cascaded_compile_time_value(operand1, denv)

William Stein's avatar
William Stein committed
8840 8841 8842
    def analyse_types(self, env):
        self.operand1.analyse_types(env)
        self.operand2.analyse_types(env)
8843 8844
        if self.is_cpp_comparison():
            self.analyse_cpp_comparison(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
8845 8846 8847
            if self.cascade:
                error(self.pos, "Cascading comparison not yet supported for cpp types.")
            return
8848 8849 8850 8851

        if self.analyse_memoryviewslice_comparison(env):
            return

William Stein's avatar
William Stein committed
8852
        if self.cascade:
8853 8854
            self.cascade.analyse_types(env)

8855
        if self.operator in ('in', 'not_in'):
8856 8857 8858 8859 8860 8861 8862
            if self.is_c_string_contains():
                self.is_pycmp = False
                common_type = None
                if self.cascade:
                    error(self.pos, "Cascading comparison not yet supported for 'int_val in string'.")
                    return
                if self.operand2.type is unicode_type:
8863
                    env.use_utility_code(UtilityCode.load_cached("PyUCS4InUnicode", "StringTools.c"))
8864 8865 8866 8867 8868
                else:
                    if self.operand1.type is PyrexTypes.c_uchar_type:
                        self.operand1 = self.operand1.coerce_to(PyrexTypes.c_char_type, env)
                    if self.operand2.type is not bytes_type:
                        self.operand2 = self.operand2.coerce_to(bytes_type, env)
8869
                    env.use_utility_code(UtilityCode.load_cached("BytesContains", "StringTools.c"))
Stefan Behnel's avatar
Stefan Behnel committed
8870 8871
                self.operand2 = self.operand2.as_none_safe_node(
                    "argument of type 'NoneType' is not iterable")
8872 8873 8874 8875 8876 8877
            elif self.is_ptr_contains():
                if self.cascade:
                    error(self.pos, "Cascading comparison not yet supported for 'val in sliced pointer'.")
                self.type = PyrexTypes.c_bint_type
                # Will be transformed by IterationTransform
                return
8878
            else:
8879 8880
                if self.operand2.type is dict_type:
                    self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
8881 8882
                common_type = py_object_type
                self.is_pycmp = True
8883 8884 8885 8886
        elif self.find_special_bool_compare_function(env):
            common_type = None # if coercion needed, the method call above has already done it
            self.is_pycmp = False # result is bint
            self.is_temp = True # must check for error return
8887 8888 8889 8890
        else:
            common_type = self.find_common_type(env, self.operator, self.operand1)
            self.is_pycmp = common_type.is_pyobject

8891
        if common_type is not None and not common_type.is_error:
8892 8893 8894
            if self.operand1.type != common_type:
                self.operand1 = self.operand1.coerce_to(common_type, env)
            self.coerce_operands_to(common_type, env)
8895

William Stein's avatar
William Stein committed
8896 8897 8898
        if self.cascade:
            self.operand2 = self.operand2.coerce_to_simple(env)
            self.cascade.coerce_cascaded_operands_to_temp(env)
8899 8900 8901 8902 8903 8904 8905 8906
        if self.is_python_result():
            self.type = PyrexTypes.py_object_type
        else:
            self.type = PyrexTypes.c_bint_type
        cdr = self.cascade
        while cdr:
            cdr.type = self.type
            cdr = cdr.cascade
William Stein's avatar
William Stein committed
8907 8908
        if self.is_pycmp or self.cascade:
            self.is_temp = 1
8909

8910 8911 8912
    def analyse_cpp_comparison(self, env):
        type1 = self.operand1.type
        type2 = self.operand2.type
8913 8914
        entry = env.lookup_operator(self.operator, [self.operand1, self.operand2])
        if entry is None:
8915 8916
            error(self.pos, "Invalid types for '%s' (%s, %s)" %
                (self.operator, type1, type2))
8917 8918 8919
            self.type = PyrexTypes.error_type
            self.result_code = "<error>"
            return
8920 8921 8922 8923 8924
        func_type = entry.type
        if func_type.is_ptr:
            func_type = func_type.base_type
        if len(func_type.args) == 1:
            self.operand2 = self.operand2.coerce_to(func_type.args[0].type, env)
8925
        else:
8926 8927 8928
            self.operand1 = self.operand1.coerce_to(func_type.args[0].type, env)
            self.operand2 = self.operand2.coerce_to(func_type.args[1].type, env)
        self.type = func_type.return_type
8929

8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942
    def analyse_memoryviewslice_comparison(self, env):
        have_none = self.operand1.is_none or self.operand2.is_none
        have_slice = (self.operand1.type.is_memoryviewslice or
                      self.operand2.type.is_memoryviewslice)
        ops = ('==', '!=', 'is', 'is_not')
        if have_slice and have_none and self.operator in ops:
            self.is_pycmp = False
            self.type = PyrexTypes.c_bint_type
            self.is_memslice_nonecheck = True
            return True

        return False

William Stein's avatar
William Stein committed
8943 8944 8945
    def has_python_operands(self):
        return (self.operand1.type.is_pyobject
            or self.operand2.type.is_pyobject)
8946

William Stein's avatar
William Stein committed
8947 8948 8949
    def check_const(self):
        if self.cascade:
            self.not_const()
8950 8951 8952
            return False
        else:
            return self.operand1.check_const() and self.operand2.check_const()
William Stein's avatar
William Stein committed
8953 8954

    def calculate_result_code(self):
8955 8956 8957 8958 8959 8960 8961
        if self.operand1.type.is_complex:
            if self.operator == "!=":
                negation = "!"
            else:
                negation = ""
            return "(%s%s(%s, %s))" % (
                negation,
8962 8963
                self.operand1.type.binary_op('=='),
                self.operand1.result(),
8964
                self.operand2.result())
8965
        elif self.is_c_string_contains():
8966
            if self.operand2.type is unicode_type:
8967
                method = "__Pyx_UnicodeContainsUCS4"
8968
            else:
8969
                method = "__Pyx_BytesContains"
8970 8971 8972 8973 8974 8975 8976
            if self.operator == "not_in":
                negation = "!"
            else:
                negation = ""
            return "(%s%s(%s, %s))" % (
                negation,
                method,
8977
                self.operand2.result(),
8978
                self.operand1.result())
8979
        else:
8980 8981 8982 8983 8984 8985 8986 8987
            result1 = self.operand1.result()
            result2 = self.operand2.result()
            if self.is_memslice_nonecheck:
                if self.operand1.type.is_memoryviewslice:
                    result1 = "((PyObject *) %s.memview)" % result1
                else:
                    result2 = "((PyObject *) %s.memview)" % result2

8988
            return "(%s %s %s)" % (
8989
                result1,
8990
                self.c_operator(self.operator),
8991
                result2)
8992

William Stein's avatar
William Stein committed
8993 8994 8995 8996
    def generate_evaluation_code(self, code):
        self.operand1.generate_evaluation_code(code)
        self.operand2.generate_evaluation_code(code)
        if self.is_temp:
8997
            self.allocate_temp_result(code)
8998
            self.generate_operation_code(code, self.result(),
William Stein's avatar
William Stein committed
8999 9000 9001
                self.operand1, self.operator, self.operand2)
            if self.cascade:
                self.cascade.generate_evaluation_code(code,
9002
                    self.result(), self.operand2)
William Stein's avatar
William Stein committed
9003
            self.operand1.generate_disposal_code(code)
9004
            self.operand1.free_temps(code)
William Stein's avatar
William Stein committed
9005
            self.operand2.generate_disposal_code(code)
9006
            self.operand2.free_temps(code)
9007

William Stein's avatar
William Stein committed
9008 9009 9010 9011 9012
    def generate_subexpr_disposal_code(self, code):
        #  If this is called, it is a non-cascaded cmp,
        #  so only need to dispose of the two main operands.
        self.operand1.generate_disposal_code(code)
        self.operand2.generate_disposal_code(code)
9013

9014 9015 9016 9017 9018
    def free_subexpr_temps(self, code):
        #  If this is called, it is a non-cascaded cmp,
        #  so only need to dispose of the two main operands.
        self.operand1.free_temps(code)
        self.operand2.free_temps(code)
9019

9020 9021 9022 9023 9024
    def annotate(self, code):
        self.operand1.annotate(code)
        self.operand2.annotate(code)
        if self.cascade:
            self.cascade.annotate(code)
William Stein's avatar
William Stein committed
9025 9026 9027


class CascadedCmpNode(Node, CmpNode):
9028 9029 9030
    #  A CascadedCmpNode is not a complete expression node. It
    #  hangs off the side of another comparison node, shares
    #  its left operand with that node, and shares its result
William Stein's avatar
William Stein committed
9031 9032 9033 9034 9035 9036
    #  with the PrimaryCmpNode at the head of the chain.
    #
    #  operator      string
    #  operand2      ExprNode
    #  cascade       CascadedCmpNode

Robert Bradshaw's avatar
Robert Bradshaw committed
9037 9038
    child_attrs = ['operand2', 'cascade']

William Stein's avatar
William Stein committed
9039
    cascade = None
9040 9041
    constant_result = constant_value_not_set # FIXME: where to calculate this?

Robert Bradshaw's avatar
Robert Bradshaw committed
9042 9043 9044 9045 9046 9047 9048
    def infer_type(self, env):
        # TODO: Actually implement this (after merging with -unstable).
        return py_object_type

    def type_dependencies(self, env):
        return ()

9049 9050 9051 9052
    def has_constant_result(self):
        return self.constant_result is not constant_value_not_set and \
               self.constant_result is not not_a_constant

9053
    def analyse_types(self, env):
William Stein's avatar
William Stein committed
9054 9055
        self.operand2.analyse_types(env)
        if self.cascade:
9056
            self.cascade.analyse_types(env)
9057

William Stein's avatar
William Stein committed
9058 9059
    def has_python_operands(self):
        return self.operand2.type.is_pyobject
9060

William Stein's avatar
William Stein committed
9061 9062
    def coerce_operands_to_pyobjects(self, env):
        self.operand2 = self.operand2.coerce_to_pyobject(env)
9063 9064
        if self.operand2.type is dict_type and self.operator in ('in', 'not_in'):
            self.operand2 = self.operand2.as_none_safe_node("'NoneType' object is not iterable")
William Stein's avatar
William Stein committed
9065 9066 9067 9068 9069 9070 9071 9072
        if self.cascade:
            self.cascade.coerce_operands_to_pyobjects(env)

    def coerce_cascaded_operands_to_temp(self, env):
        if self.cascade:
            #self.operand2 = self.operand2.coerce_to_temp(env) #CTT
            self.operand2 = self.operand2.coerce_to_simple(env)
            self.cascade.coerce_cascaded_operands_to_temp(env)
9073

William Stein's avatar
William Stein committed
9074
    def generate_evaluation_code(self, code, result, operand1):
9075 9076
        if self.type.is_pyobject:
            code.putln("if (__Pyx_PyObject_IsTrue(%s)) {" % result)
9077
            code.put_decref(result, self.type)
9078 9079
        else:
            code.putln("if (%s) {" % result)
William Stein's avatar
William Stein committed
9080
        self.operand2.generate_evaluation_code(code)
9081
        self.generate_operation_code(code, result,
William Stein's avatar
William Stein committed
9082 9083 9084 9085 9086 9087
            operand1, self.operator, self.operand2)
        if self.cascade:
            self.cascade.generate_evaluation_code(
                code, result, self.operand2)
        # Cascaded cmp result is always temp
        self.operand2.generate_disposal_code(code)
9088
        self.operand2.free_temps(code)
William Stein's avatar
William Stein committed
9089 9090
        code.putln("}")

9091 9092 9093 9094 9095
    def annotate(self, code):
        self.operand2.annotate(code)
        if self.cascade:
            self.cascade.annotate(code)

William Stein's avatar
William Stein committed
9096 9097

binop_node_classes = {
9098 9099
    "or":       BoolBinopNode,
    "and":      BoolBinopNode,
Robert Bradshaw's avatar
Robert Bradshaw committed
9100 9101 9102
    "|":        IntBinopNode,
    "^":        IntBinopNode,
    "&":        IntBinopNode,
9103 9104
    "<<":       IntBinopNode,
    ">>":       IntBinopNode,
Robert Bradshaw's avatar
Robert Bradshaw committed
9105 9106 9107
    "+":        AddNode,
    "-":        SubNode,
    "*":        MulNode,
9108 9109
    "/":        DivNode,
    "//":       DivNode,
Robert Bradshaw's avatar
Robert Bradshaw committed
9110
    "%":        ModNode,
9111
    "**":       PowNode
William Stein's avatar
William Stein committed
9112 9113
}

9114
def binop_node(pos, operator, operand1, operand2, inplace=False):
9115
    # Construct binop node of appropriate class for
William Stein's avatar
William Stein committed
9116
    # given operator.
9117 9118 9119
    return binop_node_classes[operator](pos,
        operator = operator,
        operand1 = operand1,
9120 9121
        operand2 = operand2,
        inplace = inplace)
William Stein's avatar
William Stein committed
9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133

#-------------------------------------------------------------------
#
#  Coercion nodes
#
#  Coercion nodes are special in that they are created during
#  the analyse_types phase of parse tree processing.
#  Their __init__ methods consequently incorporate some aspects
#  of that phase.
#
#-------------------------------------------------------------------

9134
class CoercionNode(ExprNode):
William Stein's avatar
William Stein committed
9135 9136 9137
    #  Abstract base class for coercion nodes.
    #
    #  arg       ExprNode       node being coerced
9138

William Stein's avatar
William Stein committed
9139
    subexprs = ['arg']
9140
    constant_result = not_a_constant
9141

William Stein's avatar
William Stein committed
9142 9143 9144 9145
    def __init__(self, arg):
        self.pos = arg.pos
        self.arg = arg
        if debug_coercion:
Stefan Behnel's avatar
Stefan Behnel committed
9146
            print("%s Coercing %s" % (self, self.arg))
9147 9148

    def calculate_constant_result(self):
9149 9150
        # constant folding can break type coercion, so this is disabled
        pass
9151

9152 9153 9154 9155 9156
    def annotate(self, code):
        self.arg.annotate(code)
        if self.arg.type != self.type:
            file, line, col = self.pos
            code.annotate((file, line, col-1), AnnotationItem(style='coerce', tag='coerce', text='[%s] to [%s]' % (self.arg.type, self.type)))
William Stein's avatar
William Stein committed
9157

9158
class CoerceToMemViewSliceNode(CoercionNode):
9159 9160 9161 9162
    """
    Coerce an object to a memoryview slice. This holds a new reference in
    a managed temp.
    """
9163 9164

    def __init__(self, arg, dst_type, env):
9165 9166
        assert dst_type.is_memoryviewslice
        assert not arg.type.is_memoryviewslice
9167 9168
        CoercionNode.__init__(self, arg)
        self.type = dst_type
9169
        self.is_temp = 1
9170 9171
        self.env = env
        self.use_managed_ref = True
9172
        self.arg = arg
9173 9174

    def generate_result_code(self, code):
9175 9176 9177 9178 9179
        self.type.create_from_py_utility_code(self.env)
        code.putln("%s = %s(%s);" % (self.result(),
                                     self.type.from_py_function,
                                     self.arg.py_result()))

9180 9181 9182
        error_cond = self.type.error_condition(self.result())
        code.putln(code.error_goto_if(error_cond, self.pos))

William Stein's avatar
William Stein committed
9183 9184 9185

class CastNode(CoercionNode):
    #  Wrap a node in a C type cast.
9186

William Stein's avatar
William Stein committed
9187 9188 9189
    def __init__(self, arg, new_type):
        CoercionNode.__init__(self, arg)
        self.type = new_type
Stefan Behnel's avatar
Stefan Behnel committed
9190 9191 9192

    def may_be_none(self):
        return self.arg.may_be_none()
9193

William Stein's avatar
William Stein committed
9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205
    def calculate_result_code(self):
        return self.arg.result_as(self.type)

    def generate_result_code(self, code):
        self.arg.generate_result_code(code)


class PyTypeTestNode(CoercionNode):
    #  This node is used to check that a generic Python
    #  object is an instance of a particular extension type.
    #  This node borrows the result of its argument node.

9206
    def __init__(self, arg, dst_type, env, notnone=False):
William Stein's avatar
William Stein committed
9207 9208
        #  The arg is know to be a Python object, and
        #  the dst_type is known to be an extension type.
Robert Bradshaw's avatar
Robert Bradshaw committed
9209
        assert dst_type.is_extension_type or dst_type.is_builtin_type, "PyTypeTest on non extension type"
William Stein's avatar
William Stein committed
9210 9211 9212
        CoercionNode.__init__(self, arg)
        self.type = dst_type
        self.result_ctype = arg.ctype()
9213
        self.notnone = notnone
9214

9215
    nogil_check = Node.gil_error
9216
    gil_message = "Python type test"
9217

9218 9219
    def analyse_types(self, env):
        pass
Stefan Behnel's avatar
Stefan Behnel committed
9220 9221 9222 9223 9224

    def may_be_none(self):
        if self.notnone:
            return False
        return self.arg.may_be_none()
9225

9226 9227 9228
    def is_simple(self):
        return self.arg.is_simple()

William Stein's avatar
William Stein committed
9229 9230
    def result_in_temp(self):
        return self.arg.result_in_temp()
9231

William Stein's avatar
William Stein committed
9232 9233
    def is_ephemeral(self):
        return self.arg.is_ephemeral()
9234 9235 9236 9237 9238

    def calculate_constant_result(self):
        # FIXME
        pass

William Stein's avatar
William Stein committed
9239
    def calculate_result_code(self):
9240
        return self.arg.result()
9241

William Stein's avatar
William Stein committed
9242 9243
    def generate_result_code(self, code):
        if self.type.typeobj_is_available():
9244
            if not self.type.is_builtin_type:
9245
                code.globalstate.use_utility_code(UtilityCode.load_cached("ExtTypeTest", "ObjectHandling.c"))
William Stein's avatar
William Stein committed
9246
            code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
9247
                "if (!(%s)) %s" % (
9248
                    self.type.type_test_code(self.arg.py_result(), self.notnone),
William Stein's avatar
William Stein committed
9249 9250 9251 9252
                    code.error_goto(self.pos)))
        else:
            error(self.pos, "Cannot test type of extern C class "
                "without type object name specification")
9253

William Stein's avatar
William Stein committed
9254 9255
    def generate_post_assignment_code(self, code):
        self.arg.generate_post_assignment_code(code)
9256 9257 9258

    def free_temps(self, code):
        self.arg.free_temps(code)
9259 9260 9261 9262 9263 9264 9265


class NoneCheckNode(CoercionNode):
    # This node is used to check that a Python object is not None and
    # raises an appropriate exception (as specified by the creating
    # transform).

9266 9267
    is_nonecheck = True

9268 9269
    def __init__(self, arg, exception_type_cname, exception_message,
                 exception_format_args):
9270 9271 9272 9273 9274
        CoercionNode.__init__(self, arg)
        self.type = arg.type
        self.result_ctype = arg.ctype()
        self.exception_type_cname = exception_type_cname
        self.exception_message = exception_message
9275
        self.exception_format_args = tuple(exception_format_args or ())
9276

9277 9278
    nogil_check = None # this node only guards an operation that would fail already

9279 9280 9281
    def analyse_types(self, env):
        pass

9282 9283 9284
    def may_be_none(self):
        return False

9285 9286 9287
    def is_simple(self):
        return self.arg.is_simple()

9288 9289 9290 9291 9292
    def result_in_temp(self):
        return self.arg.result_in_temp()

    def calculate_result_code(self):
        return self.arg.result()
9293

9294 9295 9296 9297
    def condition(self):
        if self.type.is_pyobject:
            return self.arg.py_result()
        elif self.type.is_memoryviewslice:
9298
            return "((PyObject *) %s.memview)" % self.arg.result()
9299 9300 9301 9302
        else:
            raise Exception("unsupported type")

    def put_nonecheck(self, code):
9303
        code.putln(
9304 9305 9306 9307 9308
            "if (unlikely(%s == Py_None)) {" % self.condition())

        if self.in_nogil_context:
            code.put_ensure_gil()

9309 9310
        escape = StringEncoding.escape_byte_string
        if self.exception_format_args:
9311
            code.putln('PyErr_Format(%s, "%s", %s);' % (
9312 9313 9314 9315
                self.exception_type_cname,
                StringEncoding.escape_byte_string(
                    self.exception_message.encode('UTF-8')),
                ', '.join([ '"%s"' % escape(str(arg).encode('UTF-8'))
9316
                            for arg in self.exception_format_args ])))
9317
        else:
9318
            code.putln('PyErr_SetString(%s, "%s");' % (
9319
                self.exception_type_cname,
9320 9321 9322 9323 9324 9325
                escape(self.exception_message.encode('UTF-8'))))

        if self.in_nogil_context:
            code.put_release_ensured_gil()

        code.putln(code.error_goto(self.pos))
9326 9327
        code.putln("}")

9328 9329 9330
    def generate_result_code(self, code):
        self.put_nonecheck(code)

9331 9332 9333 9334 9335 9336
    def generate_post_assignment_code(self, code):
        self.arg.generate_post_assignment_code(code)

    def free_temps(self, code):
        self.arg.free_temps(code)

9337

William Stein's avatar
William Stein committed
9338 9339 9340
class CoerceToPyTypeNode(CoercionNode):
    #  This node is used to convert a C data type
    #  to a Python object.
9341

9342
    type = py_object_type
Robert Bradshaw's avatar
Robert Bradshaw committed
9343
    is_temp = 1
William Stein's avatar
William Stein committed
9344

9345
    def __init__(self, arg, env, type=py_object_type):
9346
        if not arg.type.create_to_py_utility_code(env):
9347 9348 9349 9350 9351 9352 9353
            error(arg.pos, "Cannot convert '%s' to Python object" % arg.type)
        elif arg.type.is_complex:
            # special case: complex coercion is so complex that it
            # uses a macro ("__pyx_PyComplex_FromComplex()"), for
            # which the argument must be simple
            arg = arg.coerce_to_simple(env)
        CoercionNode.__init__(self, arg)
9354 9355 9356 9357
        if type is py_object_type:
            # be specific about some known types
            if arg.type.is_string:
                self.type = bytes_type
Stefan Behnel's avatar
Stefan Behnel committed
9358
            elif arg.type.is_unicode_char:
9359 9360 9361 9362 9363 9364
                self.type = unicode_type
            elif arg.type.is_complex:
                self.type = Builtin.complex_type
        else:
            # FIXME: check that the target type and the resulting type are compatible
            pass
9365

9366 9367 9368 9369
        if arg.type.is_memoryviewslice:
            # Register utility codes at this point
            arg.type.get_to_py_function(env, arg)

9370 9371
        self.env = env

9372
    gil_message = "Converting to Python object"
9373

9374 9375 9376 9377
    def may_be_none(self):
        # FIXME: is this always safe?
        return False

9378
    def coerce_to_boolean(self, env):
9379 9380 9381 9382 9383 9384
        arg_type = self.arg.type
        if (arg_type == PyrexTypes.c_bint_type or
            (arg_type.is_pyobject and arg_type.name == 'bool')):
            return self.arg.coerce_to_temp(env)
        else:
            return CoerceToBooleanNode(self, env)
9385

9386 9387 9388 9389 9390 9391
    def coerce_to_integer(self, env):
        # If not already some C integer type, coerce to longint.
        if self.arg.type.is_int:
            return self.arg
        else:
            return self.arg.coerce_to(PyrexTypes.c_long_type, env)
9392

9393 9394 9395 9396
    def analyse_types(self, env):
        # The arg is always already analysed
        pass

William Stein's avatar
William Stein committed
9397
    def generate_result_code(self, code):
9398
        if self.arg.type.is_memoryviewslice:
9399
            funccall = self.arg.type.get_to_py_function(self.env, self.arg)
9400 9401 9402 9403 9404
        else:
            funccall = "%s(%s)" % (self.arg.type.to_py_function,
                                   self.arg.result())

        code.putln('%s = %s; %s' % (
9405
            self.result(),
9406
            funccall,
9407
            code.error_goto_if_null(self.result(), self.pos)))
9408

9409
        code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
9410 9411


9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451
class CoerceIntToBytesNode(CoerceToPyTypeNode):
    #  This node is used to convert a C int type to a Python bytes
    #  object.

    is_temp = 1

    def __init__(self, arg, env):
        arg = arg.coerce_to_simple(env)
        CoercionNode.__init__(self, arg)
        self.type = Builtin.bytes_type

    def generate_result_code(self, code):
        arg = self.arg
        arg_result = arg.result()
        if arg.type not in (PyrexTypes.c_char_type,
                            PyrexTypes.c_uchar_type,
                            PyrexTypes.c_schar_type):
            if arg.type.signed:
                code.putln("if ((%s < 0) || (%s > 255)) {" % (
                    arg_result, arg_result))
            else:
                code.putln("if (%s > 255) {" % arg_result)
            code.putln('PyErr_Format(PyExc_OverflowError, '
                       '"value too large to pack into a byte"); %s' % (
                           code.error_goto(self.pos)))
            code.putln('}')
        temp = None
        if arg.type is not PyrexTypes.c_char_type:
            temp = code.funcstate.allocate_temp(PyrexTypes.c_char_type, manage_ref=False)
            code.putln("%s = (char)%s;" % (temp, arg_result))
            arg_result = temp
        code.putln('%s = PyBytes_FromStringAndSize(&%s, 1); %s' % (
            self.result(),
            arg_result,
            code.error_goto_if_null(self.result(), self.pos)))
        if temp is not None:
            code.funcstate.release_temp(temp)
        code.put_gotref(self.py_result())


William Stein's avatar
William Stein committed
9452 9453 9454 9455 9456 9457 9458 9459
class CoerceFromPyTypeNode(CoercionNode):
    #  This node is used to convert a Python object
    #  to a C data type.

    def __init__(self, result_type, arg, env):
        CoercionNode.__init__(self, arg)
        self.type = result_type
        self.is_temp = 1
9460
        if not result_type.create_from_py_utility_code(env):
William Stein's avatar
William Stein committed
9461
            error(arg.pos,
Craig Citro's avatar
Craig Citro committed
9462
                  "Cannot convert Python object to '%s'" % result_type)
9463 9464 9465 9466 9467 9468 9469 9470
        if self.type.is_string:
            if self.arg.is_ephemeral():
                error(arg.pos,
                      "Obtaining char* from temporary Python value")
            elif self.arg.is_name and self.arg.entry and self.arg.entry.is_pyglobal:
                warning(arg.pos,
                        "Obtaining char* from externally modifiable global Python value",
                        level=1)
9471

9472 9473 9474 9475
    def analyse_types(self, env):
        # The arg is always already analysed
        pass

William Stein's avatar
William Stein committed
9476 9477
    def generate_result_code(self, code):
        function = self.type.from_py_function
9478 9479 9480 9481
        operand = self.arg.py_result()
        rhs = "%s(%s)" % (function, operand)
        if self.type.is_enum:
            rhs = typecast(self.type, c_long_type, rhs)
Robert Bradshaw's avatar
Robert Bradshaw committed
9482
        code.putln('%s = %s; %s' % (
9483
            self.result(),
9484
            rhs,
9485
            code.error_goto_if(self.type.error_condition(self.result()), self.pos)))
9486
        if self.type.is_pyobject:
9487
            code.put_gotref(self.py_result())
William Stein's avatar
William Stein committed
9488

9489 9490 9491
    def nogil_check(self, env):
        error(self.pos, "Coercion from Python not allowed without the GIL")

William Stein's avatar
William Stein committed
9492 9493 9494 9495

class CoerceToBooleanNode(CoercionNode):
    #  This node is used when a result needs to be used
    #  in a boolean context.
9496

9497
    type = PyrexTypes.c_bint_type
9498 9499 9500 9501

    _special_builtins = {
        Builtin.list_type    : 'PyList_GET_SIZE',
        Builtin.tuple_type   : 'PyTuple_GET_SIZE',
9502
        Builtin.bytes_type   : 'PyBytes_GET_SIZE',
9503 9504 9505
        Builtin.unicode_type : 'PyUnicode_GET_SIZE',
        }

William Stein's avatar
William Stein committed
9506 9507 9508 9509
    def __init__(self, arg, env):
        CoercionNode.__init__(self, arg)
        if arg.type.is_pyobject:
            self.is_temp = 1
9510

9511
    def nogil_check(self, env):
9512
        if self.arg.type.is_pyobject and self._special_builtins.get(self.arg.type) is None:
9513
            self.gil_error()
9514

9515
    gil_message = "Truth-testing Python object"
9516

William Stein's avatar
William Stein committed
9517 9518 9519
    def check_const(self):
        if self.is_temp:
            self.not_const()
9520 9521
            return False
        return self.arg.check_const()
9522

William Stein's avatar
William Stein committed
9523
    def calculate_result_code(self):
9524
        return "(%s != 0)" % self.arg.result()
William Stein's avatar
William Stein committed
9525 9526

    def generate_result_code(self, code):
9527 9528 9529 9530
        if not self.is_temp:
            return
        test_func = self._special_builtins.get(self.arg.type)
        if test_func is not None:
Stefan Behnel's avatar
Stefan Behnel committed
9531
            code.putln("%s = (%s != Py_None) && (%s(%s) != 0);" % (
9532 9533 9534 9535 9536
                       self.result(),
                       self.arg.py_result(),
                       test_func,
                       self.arg.py_result()))
        else:
William Stein's avatar
William Stein committed
9537
            code.putln(
9538
                "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
9539 9540
                    self.result(),
                    self.arg.py_result(),
9541
                    code.error_goto_if_neg(self.result(), self.pos)))
William Stein's avatar
William Stein committed
9542

9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553
class CoerceToComplexNode(CoercionNode):

    def __init__(self, arg, dst_type, env):
        if arg.type.is_complex:
            arg = arg.coerce_to_simple(env)
        self.type = dst_type
        CoercionNode.__init__(self, arg)
        dst_type.create_declaration_utility_code(env)

    def calculate_result_code(self):
        if self.arg.type.is_complex:
9554 9555
            real_part = "__Pyx_CREAL(%s)" % self.arg.result()
            imag_part = "__Pyx_CIMAG(%s)" % self.arg.result()
9556 9557 9558 9559 9560 9561 9562
        else:
            real_part = self.arg.result()
            imag_part = "0"
        return "%s(%s, %s)" % (
                self.type.from_parts,
                real_part,
                imag_part)
9563

9564 9565
    def generate_result_code(self, code):
        pass
William Stein's avatar
William Stein committed
9566 9567 9568 9569 9570 9571 9572 9573 9574

class CoerceToTempNode(CoercionNode):
    #  This node is used to force the result of another node
    #  to be stored in a temporary. It is only used if the
    #  argument node's result is not already in a temporary.

    def __init__(self, arg, env):
        CoercionNode.__init__(self, arg)
        self.type = self.arg.type
9575
        self.constant_result = self.arg.constant_result
William Stein's avatar
William Stein committed
9576 9577 9578
        self.is_temp = 1
        if self.type.is_pyobject:
            self.result_ctype = py_object_type
9579 9580 9581

    gil_message = "Creating temporary Python reference"

9582 9583 9584
    def analyse_types(self, env):
        # The arg is always already analysed
        pass
9585

9586 9587
    def coerce_to_boolean(self, env):
        self.arg = self.arg.coerce_to_boolean(env)
9588 9589
        if self.arg.is_simple():
            return self.arg
9590 9591 9592
        self.type = self.arg.type
        self.result_ctype = self.type
        return self
9593

William Stein's avatar
William Stein committed
9594 9595 9596 9597
    def generate_result_code(self, code):
        #self.arg.generate_evaluation_code(code) # Already done
        # by generic generate_subexpr_evaluation_code!
        code.putln("%s = %s;" % (
9598
            self.result(), self.arg.result_as(self.ctype())))
9599 9600 9601 9602 9603 9604
        if self.use_managed_ref:
            if self.type.is_pyobject:
                code.put_incref(self.result(), self.ctype())
            elif self.type.is_memoryviewslice:
                code.put_incref_memoryviewslice(self.result(),
                                                not self.in_nogil_context)
William Stein's avatar
William Stein committed
9605

9606 9607 9608 9609 9610 9611 9612 9613 9614
class ProxyNode(CoercionNode):
    """
    A node that should not be replaced by transforms or other means,
    and hence can be useful to wrap the argument to a clone node

    MyNode    -> ProxyNode -> ArgNode
    CloneNode -^
    """

9615 9616
    nogil_check = None

9617 9618
    def __init__(self, arg):
        super(ProxyNode, self).__init__(arg)
9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630
        self._proxy_type()

    def analyse_expressions(self, env):
        self.arg.analyse_expressions(env)
        self._proxy_type()

    def _proxy_type(self):
        if hasattr(self.arg, 'type'):
            self.type = self.arg.type
            self.result_ctype = self.arg.result_ctype
        if hasattr(self.arg, 'entry'):
            self.entry = self.arg.entry
9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654

    def generate_result_code(self, code):
        self.arg.generate_result_code(code)

    def result(self):
        return self.arg.result()

    def is_simple(self):
        return self.arg.is_simple()

    def may_be_none(self):
        return self.arg.may_be_none()

    def generate_evaluation_code(self, code):
        self.arg.generate_evaluation_code(code)

    def generate_result_code(self, code):
        self.arg.generate_result_code(code)

    def generate_disposal_code(self, code):
        self.arg.generate_disposal_code(code)

    def free_temps(self, code):
        self.arg.free_temps(code)
William Stein's avatar
William Stein committed
9655 9656 9657 9658 9659 9660

class CloneNode(CoercionNode):
    #  This node is employed when the result of another node needs
    #  to be used multiple times. The argument node's result must
    #  be in a temporary. This node "borrows" the result from the
    #  argument node, and does not generate any evaluation or
9661
    #  disposal code for it. The original owner of the argument
William Stein's avatar
William Stein committed
9662
    #  node is responsible for doing those things.
9663

William Stein's avatar
William Stein committed
9664
    subexprs = [] # Arg is not considered a subexpr
9665
    nogil_check = None
9666

William Stein's avatar
William Stein committed
9667 9668
    def __init__(self, arg):
        CoercionNode.__init__(self, arg)
9669 9670 9671 9672 9673
        if hasattr(arg, 'type'):
            self.type = arg.type
            self.result_ctype = arg.result_ctype
        if hasattr(arg, 'entry'):
            self.entry = arg.entry
9674

9675
    def result(self):
9676
        return self.arg.result()
9677

9678 9679 9680
    def may_be_none(self):
        return self.arg.may_be_none()

Robert Bradshaw's avatar
Robert Bradshaw committed
9681 9682
    def type_dependencies(self, env):
        return self.arg.type_dependencies(env)
9683

9684 9685
    def infer_type(self, env):
        return self.arg.infer_type(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
9686

Robert Bradshaw's avatar
Robert Bradshaw committed
9687 9688 9689 9690
    def analyse_types(self, env):
        self.type = self.arg.type
        self.result_ctype = self.arg.result_ctype
        self.is_temp = 1
9691 9692
        if hasattr(self.arg, 'entry'):
            self.entry = self.arg.entry
9693

9694 9695 9696
    def is_simple(self):
        return True # result is always in a temp (or a name)

William Stein's avatar
William Stein committed
9697 9698 9699 9700 9701
    def generate_evaluation_code(self, code):
        pass

    def generate_result_code(self, code):
        pass
9702

9703
    def generate_disposal_code(self, code):
9704
        pass
9705

9706 9707
    def free_temps(self, code):
        pass
9708

9709

Stefan Behnel's avatar
Stefan Behnel committed
9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721
class CMethodSelfCloneNode(CloneNode):
    # Special CloneNode for the self argument of builtin C methods
    # that accepts subtypes of the builtin type.  This is safe only
    # for 'final' subtypes, as subtypes of the declared type may
    # override the C method.

    def coerce_to(self, dst_type, env):
        if dst_type.is_builtin_type and self.type.subtype_of(dst_type):
            return self
        return CloneNode.coerce_to(self, dst_type, env)


9722 9723
class ModuleRefNode(ExprNode):
    # Simple returns the module object
9724

9725 9726 9727
    type = py_object_type
    is_temp = False
    subexprs = []
9728

9729 9730 9731
    def analyse_types(self, env):
        pass

9732 9733 9734
    def may_be_none(self):
        return False

9735 9736 9737 9738 9739 9740 9741 9742
    def calculate_result_code(self):
        return Naming.module_cname

    def generate_result_code(self, code):
        pass

class DocstringRefNode(ExprNode):
    # Extracts the docstring of the body element
9743

9744 9745 9746
    subexprs = ['body']
    type = py_object_type
    is_temp = True
9747

9748 9749 9750 9751 9752 9753 9754 9755 9756
    def __init__(self, pos, body):
        ExprNode.__init__(self, pos)
        assert body.type.is_pyobject
        self.body = body

    def analyse_types(self, env):
        pass

    def generate_result_code(self, code):
9757 9758 9759
        code.putln('%s = __Pyx_GetAttrString(%s, "__doc__"); %s' % (
            self.result(), self.body.result(),
            code.error_goto_if_null(self.result(), self.pos)))
9760 9761 9762 9763
        code.put_gotref(self.result())



William Stein's avatar
William Stein committed
9764 9765 9766 9767 9768 9769
#------------------------------------------------------------------------------------
#
#  Runtime support code
#
#------------------------------------------------------------------------------------

9770 9771
get_name_interned_utility_code = UtilityCode(
proto = """
9772
static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
9773 9774
""",
impl = """
William Stein's avatar
William Stein committed
9775 9776 9777
static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
    PyObject *result;
    result = PyObject_GetAttr(dict, name);
9778 9779 9780 9781 9782 9783 9784 9785 9786
    if (!result) {
        if (dict != %(BUILTINS)s) {
            PyErr_Clear();
            result = PyObject_GetAttr(%(BUILTINS)s, name);
        }
        if (!result) {
            PyErr_SetObject(PyExc_NameError, name);
        }
    }
William Stein's avatar
William Stein committed
9787 9788
    return result;
}
9789
""" % {'BUILTINS' : Naming.builtins_cname})
William Stein's avatar
William Stein committed
9790 9791 9792

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

9793 9794
import_utility_code = UtilityCode(
proto = """
Haoyu Bai's avatar
Haoyu Bai committed
9795
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level); /*proto*/
9796 9797
""",
impl = """
Haoyu Bai's avatar
Haoyu Bai committed
9798
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, long level) {
9799
    PyObject *py_import = 0;
William Stein's avatar
William Stein committed
9800 9801 9802 9803 9804
    PyObject *empty_list = 0;
    PyObject *module = 0;
    PyObject *global_dict = 0;
    PyObject *empty_dict = 0;
    PyObject *list;
9805 9806
    py_import = __Pyx_GetAttrString(%(BUILTINS)s, "__import__");
    if (!py_import)
William Stein's avatar
William Stein committed
9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821
        goto bad;
    if (from_list)
        list = from_list;
    else {
        empty_list = PyList_New(0);
        if (!empty_list)
            goto bad;
        list = empty_list;
    }
    global_dict = PyModule_GetDict(%(GLOBALS)s);
    if (!global_dict)
        goto bad;
    empty_dict = PyDict_New();
    if (!empty_dict)
        goto bad;
Haoyu Bai's avatar
Haoyu Bai committed
9822 9823
    #if PY_VERSION_HEX >= 0x02050000
    {
9824
        #if PY_MAJOR_VERSION >= 3
9825
        if (level == -1) {
9826 9827 9828 9829
            if (strchr(__Pyx_MODULE_NAME, '.')) {
                /* try package relative import first */
                PyObject *py_level = PyInt_FromLong(1);
                if (!py_level)
9830
                    goto bad;
9831 9832 9833 9834 9835 9836 9837 9838
                module = PyObject_CallFunctionObjArgs(py_import,
                    name, global_dict, empty_dict, list, py_level, NULL);
                Py_DECREF(py_level);
                if (!module) {
                    if (!PyErr_ExceptionMatches(PyExc_ImportError))
                        goto bad;
                    PyErr_Clear();
                }
9839
            }
9840
            level = 0; /* try absolute import on failure */
9841 9842 9843 9844 9845 9846 9847 9848 9849 9850
        }
        #endif
        if (!module) {
            PyObject *py_level = PyInt_FromLong(level);
            if (!py_level)
                goto bad;
            module = PyObject_CallFunctionObjArgs(py_import,
                name, global_dict, empty_dict, list, py_level, NULL);
            Py_DECREF(py_level);
        }
Haoyu Bai's avatar
Haoyu Bai committed
9851 9852 9853 9854 9855 9856
    }
    #else
    if (level>0) {
        PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4.");
        goto bad;
    }
9857
    module = PyObject_CallFunctionObjArgs(py_import,
9858
        name, global_dict, empty_dict, list, NULL);
Haoyu Bai's avatar
Haoyu Bai committed
9859
    #endif
William Stein's avatar
William Stein committed
9860 9861
bad:
    Py_XDECREF(empty_list);
9862
    Py_XDECREF(py_import);
William Stein's avatar
William Stein committed
9863 9864 9865 9866 9867 9868
    Py_XDECREF(empty_dict);
    return module;
}
""" % {
    "BUILTINS": Naming.builtins_cname,
    "GLOBALS":  Naming.module_cname,
9869
})
William Stein's avatar
William Stein committed
9870 9871 9872

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

9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891
pyerr_occurred_withgil_utility_code= UtilityCode(
proto = """
static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void); /* proto */
""",
impl = """
static CYTHON_INLINE int __Pyx_ErrOccurredWithGIL(void) {
  int err;
  #ifdef WITH_THREAD
  PyGILState_STATE _save = PyGILState_Ensure();
  #endif
  err = !!PyErr_Occurred();
  #ifdef WITH_THREAD
  PyGILState_Release(_save);
  #endif
  return err;
}
"""
)

Robert Bradshaw's avatar
Robert Bradshaw committed
9892
#------------------------------------------------------------------------------------
Robert Bradshaw's avatar
Robert Bradshaw committed
9893

9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913
raise_unbound_local_error_utility_code = UtilityCode(
proto = """
static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname);
""",
impl = """
static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) {
    PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname);
}
""")

raise_closure_name_error_utility_code = UtilityCode(
proto = """
static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname);
""",
impl = """
static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname) {
    PyErr_Format(PyExc_NameError, "free variable '%s' referenced before assignment in enclosing scope", varname);
}
""")

9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924
# Don't inline the function, it should really never be called in production
raise_unbound_memoryview_utility_code_nogil = UtilityCode(
proto = """
static void __Pyx_RaiseUnboundMemoryviewSliceNogil(const char *varname);
""",
impl = """
static void __Pyx_RaiseUnboundMemoryviewSliceNogil(const char *varname) {
    #ifdef WITH_THREAD
    PyGILState_STATE gilstate = PyGILState_Ensure();
    #endif
    __Pyx_RaiseUnboundLocalError(varname);
9925
    #ifdef WITH_THREAD
9926 9927 9928 9929 9930 9931
    PyGILState_Release(gilstate);
    #endif
}
""",
requires = [raise_unbound_local_error_utility_code])

9932 9933
#------------------------------------------------------------------------------------

9934 9935 9936 9937
getitem_int_pyunicode_utility_code = UtilityCode(
proto = '''
#define __Pyx_GetItemInt_Unicode(o, i, size, to_py_func) (((size) <= sizeof(Py_ssize_t)) ? \\
                                               __Pyx_GetItemInt_Unicode_Fast(o, i) : \\
Stefan Behnel's avatar
Stefan Behnel committed
9938
                                               __Pyx_GetItemInt_Unicode_Generic(o, to_py_func(i)))
9939

9940
static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Fast(PyObject* ustring, Py_ssize_t i) {
9941
    Py_ssize_t length;
9942 9943 9944
#if CYTHON_PEP393_ENABLED
    if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return (Py_UCS4)-1;
#endif
9945
    length = __Pyx_PyUnicode_GET_LENGTH(ustring);
9946 9947 9948 9949
    if (likely((0 <= i) & (i < length))) {
        return __Pyx_PyUnicode_READ_CHAR(ustring, i);
    } else if ((-length <= i) & (i < 0)) {
        return __Pyx_PyUnicode_READ_CHAR(ustring, i + length);
9950 9951
    } else {
        PyErr_SetString(PyExc_IndexError, "string index out of range");
9952
        return (Py_UCS4)-1;
9953 9954 9955
    }
}

9956 9957
static CYTHON_INLINE Py_UCS4 __Pyx_GetItemInt_Unicode_Generic(PyObject* ustring, PyObject* j) {
    Py_UCS4 uchar;
9958
    PyObject *uchar_string;
9959
    if (!j) return (Py_UCS4)-1;
9960
    uchar_string = PyObject_GetItem(ustring, j);
9961
    Py_DECREF(j);
9962
    if (!uchar_string) return (Py_UCS4)-1;
9963 9964 9965 9966 9967 9968
#if CYTHON_PEP393_ENABLED
    if (unlikely(__Pyx_PyUnicode_READY(uchar_string) < 0)) {
        Py_DECREF(uchar_string);
        return (Py_UCS4)-1;
    }
#endif
9969
    uchar = __Pyx_PyUnicode_READ_CHAR(uchar_string, 0);
9970
    Py_DECREF(uchar_string);
9971 9972
    return uchar;
}
9973
''')
9974

9975 9976
#------------------------------------------------------------------------------------

9977 9978 9979
raise_too_many_values_to_unpack = UtilityCode.load_cached("RaiseTooManyValuesToUnpack", "ObjectHandling.c")
raise_need_more_values_to_unpack = UtilityCode.load_cached("RaiseNeedMoreValuesToUnpack", "ObjectHandling.c")
tuple_unpacking_error_code = UtilityCode.load_cached("UnpackTupleError", "ObjectHandling.c")
Robert Bradshaw's avatar
Robert Bradshaw committed
9980 9981 9982 9983 9984

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

int_pow_utility_code = UtilityCode(
proto="""
9985
static CYTHON_INLINE %(type)s %(func_name)s(%(type)s, %(type)s); /* proto */
Robert Bradshaw's avatar
Robert Bradshaw committed
9986 9987
""",
impl="""
9988
static CYTHON_INLINE %(type)s %(func_name)s(%(type)s b, %(type)s e) {
Robert Bradshaw's avatar
Robert Bradshaw committed
9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009
    %(type)s t = b;
    switch (e) {
        case 3:
            t *= b;
        case 2:
            t *= b;
        case 1:
            return t;
        case 0:
            return 1;
    }
    if (unlikely(e<0)) return 0;
    t = 1;
    while (likely(e)) {
        t *= (b * (e&1)) | ((~e)&1);    /* 1 or b */
        b *= b;
        e >>= 1;
    }
    return t;
}
""")
10010 10011 10012

# ------------------------------ Division ------------------------------------

10013 10014
div_int_utility_code = UtilityCode(
proto="""
10015
static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s, %(type)s); /* proto */
10016 10017
""",
impl="""
10018
static CYTHON_INLINE %(type)s __Pyx_div_%(type_name)s(%(type)s a, %(type)s b) {
10019 10020 10021 10022 10023
    %(type)s q = a / b;
    %(type)s r = a - q*b;
    q -= ((r != 0) & ((r ^ b) < 0));
    return q;
}
10024 10025
""")

10026
mod_int_utility_code = UtilityCode(
10027
proto="""
10028
static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
10029 10030
""",
impl="""
10031
static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
10032 10033 10034
    %(type)s r = a %% b;
    r += ((r != 0) & ((r ^ b) < 0)) * b;
    return r;
10035 10036 10037
}
""")

10038
mod_float_utility_code = UtilityCode(
10039
proto="""
10040
static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s, %(type)s); /* proto */
10041 10042
""",
impl="""
10043
static CYTHON_INLINE %(type)s __Pyx_mod_%(type_name)s(%(type)s a, %(type)s b) {
10044 10045 10046
    %(type)s r = fmod%(math_h_modifier)s(a, b);
    r += ((r != 0) & ((r < 0) ^ (b < 0))) * b;
    return r;
10047 10048
}
""")
Robert Bradshaw's avatar
Robert Bradshaw committed
10049

10050
cdivision_warning_utility_code = UtilityCode(
Robert Bradshaw's avatar
Robert Bradshaw committed
10051
proto="""
10052
static int __Pyx_cdivision_warning(const char *, int); /* proto */
Robert Bradshaw's avatar
Robert Bradshaw committed
10053 10054
""",
impl="""
10055
static int __Pyx_cdivision_warning(const char *filename, int lineno) {
10056
    return PyErr_WarnExplicit(PyExc_RuntimeWarning,
10057
                              "division with oppositely signed operands, C and Python semantics differ",
10058 10059
                              filename,
                              lineno,
10060
                              __Pyx_MODULE_NAME,
10061
                              NULL);
Robert Bradshaw's avatar
Robert Bradshaw committed
10062
}
10063
""")
10064 10065 10066 10067

# from intobject.c
division_overflow_test_code = UtilityCode(
proto="""
Vitja Makarov's avatar
Vitja Makarov committed
10068 10069
#define UNARY_NEG_WOULD_OVERFLOW(x)    \
        (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x)))
10070
""")
Robert Bradshaw's avatar
Robert Bradshaw committed
10071

10072 10073 10074
binding_cfunc_utility_code = TempitaUtilityCode.load(
    "CythonFunction", context=vars(Naming))
fused_function_utility_code = TempitaUtilityCode.load(
10075 10076 10077 10078
        "FusedFunction",
        "CythonFunction.c",
        context=vars(Naming),
        requires=[binding_cfunc_utility_code])
10079 10080 10081 10082
cyfunction_class_cell_utility_code = UtilityCode.load(
    "CyFunctionClassCell",
    "CythonFunction.c",
    requires=[binding_cfunc_utility_code])
10083

10084 10085 10086 10087
generator_utility_code = UtilityCode.load(
    "Generator",
    "Generator.c",
    requires=[Nodes.raise_utility_code, Nodes.swap_exception_utility_code],
Stefan Behnel's avatar
Stefan Behnel committed
10088
)