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

5
import operator
William Stein's avatar
William Stein committed
6

7
from Errors import error, warning, InternalError
8
from Errors import hold_errors, release_errors, held_errors, report_error
9
from Cython.Utils import UtilityCode
10
import StringEncoding
William Stein's avatar
William Stein committed
11 12 13
import Naming
from Nodes import Node
import PyrexTypes
14
from PyrexTypes import py_object_type, c_long_type, typecast, error_type
15
from Builtin import list_type, tuple_type, dict_type, unicode_type
William Stein's avatar
William Stein committed
16 17
import Symtab
import Options
18
from Annotate import AnnotationItem
William Stein's avatar
William Stein committed
19

William Stein's avatar
William Stein committed
20
from Cython.Debugging import print_call_chain
William Stein's avatar
William Stein committed
21 22 23
from DebugFlags import debug_disposal_code, debug_temp_alloc, \
    debug_coercion

24

William Stein's avatar
William Stein committed
25 26 27 28 29 30 31 32 33 34 35 36 37
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
    #  is_sequence_constructor  
    #               boolean      Is a list or tuple constructor expression
    #  saved_subexpr_nodes
    #               [ExprNode or [ExprNode or None] or None]
    #                            Cached result of subexpr_nodes()
    
    result_ctype = None
38
    type = None
William Stein's avatar
William Stein committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

    #  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.
    #  
    #  The framework makes use of a number of abstract methods. 
    #  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
    #        the LHS of an assignment or argument of a del 
    #        statement. Similar responsibilities to analyse_types.
    #
    #      allocate_temps
    #        - Call allocate_temps for all sub-nodes.
    #        - Call allocate_temp for this node.
    #        - If a temporary was allocated, call release_temp on 
    #          all sub-expressions.
    #
99 100 101 102 103 104 105
    #      allocate_target_temps
    #        - Call allocate_temps on sub-nodes and allocate any other
    #          temps used during assignment.
    #        - Fill in result_code with a C lvalue if needed.
    #        - If a rhs node is supplied, call release_temp on it.
    #        - Call release_temp on sub-nodes and release any other
    #          temps used during assignment.
William Stein's avatar
William Stein committed
106
    #
107 108 109 110
    #      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
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    #
    #      check_const
    #        - Check that this node and its subnodes form a
    #          legal constant expression. If so, do nothing,
    #          otherwise call not_const. 
    #
    #        The default implementation of check_const 
    #        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
    #        assumes that the expression is not a constant 
    #        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
139
    #        is provided which uses the following abstract methods:
William Stein's avatar
William Stein committed
140 141 142 143 144 145
    #
    #          generate_result_code
    #            - Generate any C statements necessary to calculate
    #              the result of this node from the results of its
    #              sub-expressions.
    #
146 147 148 149 150
    #          calculate_result_code
    #            - Should return a C code fragment evaluating to the 
    #              result. This is only called when the result is not 
    #              a temporary.
    #
William Stein's avatar
William Stein committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    #      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.
    #
    #
    
    is_sequence_constructor = 0
    is_attribute = 0
    
    saved_subexpr_nodes = None
    is_temp = 0
172
    is_target = 0
William Stein's avatar
William Stein committed
173

174
    def get_child_attrs(self):
175 176
        return self.subexprs
    child_attrs = property(fget=get_child_attrs)
177
        
William Stein's avatar
William Stein committed
178 179 180 181
    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
182
                (self.__class__.__name__, method_name))
William Stein's avatar
William Stein committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
                
    def is_lvalue(self):
        return 0
    
    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.
198 199 200 201 202 203 204 205 206
        nodes = []
        for name in self.subexprs:
            item = getattr(self, name)
            if item:
                if isinstance(item, ExprNode):
                    nodes.append(item)
                else:
                    nodes.extend(item)
        return nodes
207 208
        
    def result(self):
209
        if not self.is_temp or self.is_target:
210
            return self.calculate_result_code()
211 212
        else: # i.e. self.is_temp:
            return self.result_code
William Stein's avatar
William Stein committed
213 214 215
    
    def result_as(self, type = None):
        #  Return the result code cast to the specified C type.
216
        return typecast(type, self.ctype(), self.result())
William Stein's avatar
William Stein committed
217 218 219 220 221 222 223 224 225 226
    
    def py_result(self):
        #  Return the result code cast to PyObject *.
        return self.result_as(py_object_type)
    
    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
    
227 228 229 230 231 232 233 234
    def compile_time_value(self, denv):
        #  Return value of compile-time expression, or report error.
        error(self.pos, "Invalid compile-time expression")
    
    def compile_time_value_error(self, e):
        error(self.pos, "Error in compile-time expression: %s: %s" % (
            e.__class__.__name__, e))
    
William Stein's avatar
William Stein committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    # ------------- Declaration Analysis ----------------
    
    def analyse_target_declaration(self, env):
        error(self.pos, "Cannot assign to or delete this")
    
    # ------------- Expression Analysis ----------------
    
    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)
        self.allocate_temps(env)
        self.check_const()
    
    def analyse_expressions(self, env):
        #  Convenience routine performing both the Type
        #  Analysis and Temp Allocation phases for a whole 
        #  expression.
        self.analyse_types(env)
        self.allocate_temps(env)
    
258
    def analyse_target_expression(self, env, rhs):
William Stein's avatar
William Stein committed
259 260 261 262
        #  Convenience routine performing both the Type
        #  Analysis and Temp Allocation phases for the LHS of
        #  an assignment.
        self.analyse_target_types(env)
263
        self.allocate_target_temps(env, rhs)
William Stein's avatar
William Stein committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    
    def analyse_boolean_expression(self, env):
        #  Analyse expression and coerce to a boolean.
        self.analyse_types(env)
        bool = self.coerce_to_boolean(env)
        bool.allocate_temps(env)
        return bool
    
    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)
        bool = self.coerce_to_boolean(env)
        temp_bool = bool.coerce_to_temp(env)
        temp_bool.allocate_temps(env)
        return temp_bool
    
    # --------------- Type Analysis ------------------
    
    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
292 293 294 295 296
        
    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
William Stein's avatar
William Stein committed
297 298 299 300 301 302 303 304 305 306 307
    
    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
    
    def analyse_types(self, env):
        self.not_implemented("analyse_types")
    
    def analyse_target_types(self, env):
        self.analyse_types(env)
308 309 310 311 312

    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
313 314 315 316 317 318 319 320 321 322 323
    def check_const(self):
        self.not_const()
    
    def not_const(self):
        error(self.pos, "Not allowed in a constant expression")
    
    def check_const_addr(self):
        self.addr_not_const()
    
    def addr_not_const(self):
        error(self.pos, "Address is not constant")
324 325 326 327 328

    def gil_check(self, env):
        if env.nogil and self.type.is_pyobject:
            self.gil_error()

William Stein's avatar
William Stein committed
329 330 331 332 333 334 335 336 337
    # ----------------- Result Allocation -----------------
    
    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
            
338 339
    def allocate_target_temps(self, env, rhs):
        #  Perform temp allocation for the LHS of an assignment.
William Stein's avatar
William Stein committed
340
        if debug_temp_alloc:
Stefan Behnel's avatar
Stefan Behnel committed
341
            print("%s Allocating target temps" % self)
William Stein's avatar
William Stein committed
342
        self.allocate_subexpr_temps(env)
343
        self.is_target = True
344 345 346
        if rhs:
            rhs.release_temp(env)
        self.release_subexpr_temps(env)
William Stein's avatar
William Stein committed
347 348 349 350 351 352 353 354
    
    def allocate_temps(self, env, result = None):
        #  Allocate temporary variables for this node and
        #  all its sub-expressions. If a result is specified,
        #  this must be a temp node and the specified variable
        #  is used as the result instead of allocating a new
        #  one.
        if debug_temp_alloc:
Stefan Behnel's avatar
Stefan Behnel committed
355
            print("%s Allocating temps" % self)
William Stein's avatar
William Stein committed
356 357 358 359 360 361 362 363 364
        self.allocate_subexpr_temps(env)
        self.allocate_temp(env, result)
        if self.is_temp:
            self.release_subexpr_temps(env)
    
    def allocate_subexpr_temps(self, env):
        #  Allocate temporary variables for all sub-expressions
        #  of this node.
        if debug_temp_alloc:
Stefan Behnel's avatar
Stefan Behnel committed
365
            print("%s Allocating temps for: %s" % (self, self.subexprs))
William Stein's avatar
William Stein committed
366 367 368
        for node in self.subexpr_nodes():
            if node:
                if debug_temp_alloc:
Stefan Behnel's avatar
Stefan Behnel committed
369
                    print("%s Allocating temps for %s" % (self, node))
William Stein's avatar
William Stein committed
370 371 372 373 374 375 376 377 378 379
                node.allocate_temps(env)
    
    def allocate_temp(self, env, result = None):
        #  If this node requires a temporary variable for its
        #  result, allocate one, otherwise set the result to
        #  a C code fragment. If a result is specified,
        #  this must be a temp node and the specified variable
        #  is used as the result instead of allocating a new
        #  one.
        if debug_temp_alloc:
Stefan Behnel's avatar
Stefan Behnel committed
380
            print("%s Allocating temp" % self)
William Stein's avatar
William Stein committed
381 382 383 384 385 386 387 388 389 390 391 392 393
        if result:
            if not self.is_temp:
                raise InternalError("Result forced on non-temp node")
            self.result_code = result
        elif self.is_temp:
            type = self.type
            if not type.is_void:
                if type.is_pyobject:
                    type = PyrexTypes.py_object_type
                self.result_code = env.allocate_temp(type)
            else:
                self.result_code = None
            if debug_temp_alloc:
Stefan Behnel's avatar
Stefan Behnel committed
394
                print("%s Allocated result %s" % (self, self.result_code))
395
                
William Stein's avatar
William Stein committed
396 397 398 399 400 401 402
    def target_code(self):
        #  Return code fragment for use as LHS of a C assignment.
        return self.calculate_result_code()
    
    def calculate_result_code(self):
        self.not_implemented("calculate_result_code")
    
403 404 405
#	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
406 407 408 409 410 411

    def release_temp(self, env):
        #  If this node owns a temporary result, release it,
        #  otherwise release results of its sub-expressions.
        if self.is_temp:
            if debug_temp_alloc:
Stefan Behnel's avatar
Stefan Behnel committed
412
                print("%s Releasing result %s" % (self, self.result_code))
William Stein's avatar
William Stein committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
            env.release_temp(self.result_code)
        else:
            self.release_subexpr_temps(env)
    
    def release_subexpr_temps(self, env):
        #  Release the results of all sub-expressions of
        #  this node.
        for node in self.subexpr_nodes():
            if node:
                node.release_temp(env)
    
    # ---------------- Code Generation -----------------
    
    def make_owned_reference(self, code):
        #  If result is a pyobject, make sure we own
        #  a reference to it.
        if self.type.is_pyobject and not self.result_in_temp():
430
            code.put_incref(self.result(), self.ctype())
William Stein's avatar
William Stein committed
431 432
    
    def generate_evaluation_code(self, code):
433
        code.mark_pos(self.pos)
William Stein's avatar
William Stein committed
434 435 436 437 438 439 440
        #  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)
        self.generate_result_code(code)
        if self.is_temp:
            self.generate_subexpr_disposal_code(code)
441
            self.free_subexpr_temps(code)
442

William Stein's avatar
William Stein committed
443 444 445 446 447 448 449
    def generate_subexpr_evaluation_code(self, code):
        for node in self.subexpr_nodes():
            node.generate_evaluation_code(code)
    
    def generate_result_code(self, code):
        self.not_implemented("generate_result_code")
    
450
    def generate_disposal_code(self, code):
William Stein's avatar
William Stein committed
451 452
        # If necessary, generate code to dispose of 
        # temporary Python reference.
453 454 455
        if self.is_temp:
            if self.type.is_pyobject:
                code.put_decref_clear(self.result(), self.ctype())
William Stein's avatar
William Stein committed
456
        else:
457
            self.generate_subexpr_disposal_code(code)
William Stein's avatar
William Stein committed
458 459 460 461 462 463 464 465 466 467 468 469 470
    
    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)
    
    def generate_post_assignment_code(self, code):
        # Same as generate_disposal_code except that
        # assignment will have absorbed a reference to
        # the result if it is a Python object.
        if self.is_temp:
            if self.type.is_pyobject:
471
                code.putln("%s = 0;" % self.result())
William Stein's avatar
William Stein committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485
        else:
            self.generate_subexpr_disposal_code(code)
    
    def generate_assignment_code(self, rhs, code):
        #  Stub method for nodes which are not legal as
        #  the LHS of an assignment. An error will have 
        #  been reported earlier.
        pass
    
    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
486 487 488

    def free_temps(self, code):
        pass
William Stein's avatar
William Stein committed
489
    
490 491 492 493
    def free_subexpr_temps(self, code):
        for sub in self.subexpr_nodes():
            sub.free_temps(code)

494 495 496 497 498 499
    # ---------------- Annotation ---------------------
    
    def annotate(self, code):
        for node in self.subexpr_nodes():
            node.annotate(code)
    
William Stein's avatar
William Stein committed
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    # ----------------- Coercion ----------------------
    
    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.
        src = self
        src_type = self.type
        src_is_py_type = src_type.is_pyobject
        dst_is_py_type = dst_type.is_pyobject
        
        if dst_type.is_pyobject:
            if not src.type.is_pyobject:
                src = CoerceToPyTypeNode(src, env)
            if not src.type.subtype_of(dst_type):
519 520
                if not isinstance(src, NoneNode):
                    src = PyTypeTestNode(src, dst_type, env)
William Stein's avatar
William Stein committed
521 522 523
        elif src.type.is_pyobject:
            src = CoerceFromPyTypeNode(dst_type, src, env)
        else: # neither src nor dst are py types
524
            # Added the string comparison, since for c types that
525
            # is enough, but Cython gets confused when the types are
526
            # in different files.
527
            if not (str(src.type) == str(dst_type) or dst_type.assignable_from(src_type)):
William Stein's avatar
William Stein committed
528 529 530 531 532 533 534 535 536 537 538 539 540 541
                error(self.pos, "Cannot assign type '%s' to '%s'" %
                    (src.type, dst_type))
        return src

    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.
        type = self.type
        if type.is_pyobject or type.is_ptr or type.is_float:
            return CoerceToBooleanNode(self, env)
        else:
542
            if not type.is_int and not type.is_error:
William Stein's avatar
William Stein committed
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
                error(self.pos, 
                    "Type '%s' not acceptable as a boolean" % type)
            return self
    
    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)
    
    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)
    
    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)
    
    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()
574
        
575
    def as_cython_attribute(self):
576
        return None
William Stein's avatar
William Stein committed
577 578


579 580 581 582 583 584 585 586
class RemoveAllocateTemps(type):
    def __init__(cls, name, bases, dct):
        super(RemoveAllocateTemps, cls).__init__(name, bases, dct)
        def noop(self, env): pass
        setattr(cls, 'allocate_temps', noop)
        setattr(cls, 'allocate_temp', noop)
        setattr(cls, 'release_temp', noop)

587 588
class NewTempExprNode(ExprNode):
    backwards_compatible_result = None
589 590
    temp_code = None
    
591 592 593 594
#   Do not enable this unless you are trying to make all ExprNodes
#   NewTempExprNodes (child nodes reached via recursion may not have
#   transferred).
#    __metaclass__ = RemoveAllocateTemps
595

596 597 598 599 600 601 602 603
    def result(self):
        if self.is_temp:
            return self.temp_code
        else:
            return self.calculate_result_code()

    def allocate_target_temps(self, env, rhs):
        self.allocate_subexpr_temps(env)
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
604 605 606
        self.is_target = True
        if rhs:
            rhs.release_temp(env)
607
        self.release_subexpr_temps(env)
608 609 610 611 612 613 614 615 616 617 618

    def allocate_temps(self, env, result = None):
        self.allocate_subexpr_temps(env)
        self.backwards_compatible_result = result
        if self.is_temp:
            self.release_subexpr_temps(env)

    def allocate_temp(self, env, result = None):
        assert result is None

    def release_temp(self, env):
619 620 621 622
        if self.is_temp:
            pass
        else:
            self.release_subexpr_temps(env)
623

624
    def allocate_temp_result(self, code):
625 626
        if self.temp_code:
            raise RuntimeError("Temp allocated multiple times")
627 628 629 630 631 632 633 634 635 636 637 638 639
        type = self.type
        if not type.is_void:
            if type.is_pyobject:
                type = PyrexTypes.py_object_type
            if self.backwards_compatible_result:
                self.temp_code = self.backwards_compatible_result
            else:
                self.temp_code = code.funcstate.allocate_temp(
                    type, manage_ref=True)
        else:
            self.temp_code = None

    def release_temp_result(self, code):
640 641
        if not self.temp_code:
            raise RuntimeError("No temp (perhaps released multiple times? See self.old_temp)")
642
        code.funcstate.release_temp(self.temp_code)
643 644
        self.old_temp = self.temp_code
        self.temp_code = None
645

646 647 648 649 650 651 652 653
    def generate_evaluation_code(self, code):
        code.mark_pos(self.pos)
        
        #  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)

654
        if self.is_temp:
655
            self.allocate_temp_result(code)
656

657 658
        self.generate_result_code(code)
        if self.is_temp:
659
            # If we are temp we do not need to wait until this node is disposed
660
            # before disposing children.
661
            self.generate_subexpr_disposal_code(code)
662
            self.free_subexpr_temps(code)
663

664
    def generate_disposal_code(self, code):
665
        if self.is_temp:
666
            if self.type.is_pyobject:
667
                code.put_decref_clear(self.result(), self.ctype())
668
        else:
669
            # Already done if self.is_temp
670 671 672
            self.generate_subexpr_disposal_code(code)

    def generate_post_assignment_code(self, code):
673 674 675 676 677
        if self.is_temp:
            if self.type.is_pyobject:
                code.putln("%s = 0;" % self.result())
        else:
            self.generate_subexpr_disposal_code(code)
678 679 680

    def free_temps(self, code):
        if self.is_temp:
681 682 683 684
            self.release_temp_result(code)
        else:
            self.free_subexpr_temps(code)
        
685
# ExprNode = NewTempExprNode     
686

William Stein's avatar
William Stein committed
687 688 689 690 691 692
class AtomicExprNode(ExprNode):
    #  Abstract base class for expression nodes which have
    #  no sub-expressions.
    
    subexprs = []

693 694 695 696 697 698 699 700 701 702 703 704
class AtomicNewTempExprNode(NewTempExprNode):
    # I do not dare to convert NameNode yet. This is now
    # ancestor of all former AtomicExprNode except
    # NameNode. Should be renamed to AtomicExprNode
    # when done.
    
    #  Abstract base class for expression nodes which have
    #  no sub-expressions.
    
    subexprs = []

    # Override to optimize -- we know we have no children
705 706 707 708
    def generate_subexpr_evaluation_code(self, code):
        pass
    def generate_subexpr_disposal_code(self, code):
        pass
709 710

class PyConstNode(AtomicNewTempExprNode):
William Stein's avatar
William Stein committed
711 712
    #  Abstract base class for constant Python values.
    
713 714
    is_literal = 1
    
William Stein's avatar
William Stein committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    def is_simple(self):
        return 1
    
    def analyse_types(self, env):
        self.type = py_object_type
    
    def calculate_result_code(self):
        return self.value

    def generate_result_code(self, code):
        pass


class NoneNode(PyConstNode):
    #  The constant value None
    
    value = "Py_None"
    
733 734 735
    def compile_time_value(self, denv):
        return None
    
William Stein's avatar
William Stein committed
736 737 738 739 740
class EllipsisNode(PyConstNode):
    #  '...' in a subscript list.
    
    value = "Py_Ellipsis"

741 742 743
    def compile_time_value(self, denv):
        return Ellipsis

William Stein's avatar
William Stein committed
744

745
class ConstNode(AtomicNewTempExprNode):
William Stein's avatar
William Stein committed
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
    # Abstract base type for literal constant nodes.
    #
    # value     string      C code fragment
    
    is_literal = 1
    
    def is_simple(self):
        return 1
    
    def analyse_types(self, env):
        pass # Types are held in class variables
    
    def check_const(self):
        pass
    
    def calculate_result_code(self):
        return str(self.value)

    def generate_result_code(self, code):
        pass


768 769 770 771 772 773 774 775
class BoolNode(ConstNode):
    type = PyrexTypes.c_bint_type
    #  The constant value True or False
    
    def compile_time_value(self, denv):
        return self.value
    
    def calculate_result_code(self):
776
        return str(int(self.value))
777

William Stein's avatar
William Stein committed
778 779
class NullNode(ConstNode):
    type = PyrexTypes.c_null_ptr_type
780
    value = "NULL"
William Stein's avatar
William Stein committed
781 782 783 784 785


class CharNode(ConstNode):
    type = PyrexTypes.c_char_type
    
786
    def compile_time_value(self, denv):
787
        return ord(self.value)
788
    
William Stein's avatar
William Stein committed
789
    def calculate_result_code(self):
790
        return "'%s'" % StringEncoding.escape_character(self.value)
William Stein's avatar
William Stein committed
791 792 793


class IntNode(ConstNode):
794 795 796 797 798 799

    # unsigned     "" or "U"
    # longness     "" or "L" or "LL"

    unsigned = ""
    longness = ""
William Stein's avatar
William Stein committed
800 801
    type = PyrexTypes.c_long_type

802
    def coerce_to(self, dst_type, env):
803 804 805 806
        if dst_type.is_numeric:
            self.type = PyrexTypes.c_long_type
            return self
        # Arrange for a Python version of the number to be pre-allocated
807 808
        # when coercing to a Python type.
        if dst_type.is_pyobject:
809
            self.entry = env.get_py_num(self.value, self.longness)
810 811 812 813 814
            self.type = PyrexTypes.py_object_type
        # 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(self, dst_type, env)
815 816 817 818
        
    def coerce_to_boolean(self, env):
        self.type = PyrexTypes.c_bint_type
        return self
819 820 821 822 823

    def calculate_result_code(self):
        if self.type.is_pyobject:
            return self.entry.cname
        else:
824
            return str(self.value) + self.unsigned + self.longness
William Stein's avatar
William Stein committed
825

826
    def compile_time_value(self, denv):
827
        return int(self.value, 0)
828 829


William Stein's avatar
William Stein committed
830 831 832
class FloatNode(ConstNode):
    type = PyrexTypes.c_double_type

833 834
    def compile_time_value(self, denv):
        return float(self.value)
Stefan Behnel's avatar
Stefan Behnel committed
835 836 837 838
    
    def calculate_result_code(self):
        strval = str(self.value)
        if strval == 'nan':
839
            return "(Py_HUGE_VAL * 0)"
Stefan Behnel's avatar
Stefan Behnel committed
840
        elif strval == 'inf':
841
            return "Py_HUGE_VAL"
Stefan Behnel's avatar
Stefan Behnel committed
842
        elif strval == '-inf':
843
            return "(-Py_HUGE_VAL)"
Stefan Behnel's avatar
Stefan Behnel committed
844 845
        else:
            return strval
846

William Stein's avatar
William Stein committed
847 848 849 850 851

class StringNode(ConstNode):
    #  entry   Symtab.Entry
    
    type = PyrexTypes.c_char_ptr_type
852 853

    def compile_time_value(self, denv):
854
        return self.value
William Stein's avatar
William Stein committed
855 856 857
    
    def analyse_types(self, env):
        self.entry = env.add_string_const(self.value)
858 859
        
    def analyse_as_type(self, env):
860 861 862
        type = PyrexTypes.parse_basic_type(self.value)
        if type is not None:    
            return type
863 864 865 866 867 868 869
        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
William Stein's avatar
William Stein committed
870 871
    
    def coerce_to(self, dst_type, env):
872 873 874 875
        if dst_type == PyrexTypes.c_char_ptr_type:
            self.type = PyrexTypes.c_char_ptr_type
            return self
            
876
        if dst_type.is_int:
877
            if not self.type.is_pyobject and len(self.entry.init) == 1:
Robert Bradshaw's avatar
Robert Bradshaw committed
878
                return CharNode(self.pos, value=self.value)
879 880 881
            else:
                error(self.pos, "Only coerce single-character ascii strings can be used as ints.")
                return self
William Stein's avatar
William Stein committed
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
        # Arrange for a Python version of the string to be pre-allocated
        # when coercing to a Python type.
        if dst_type.is_pyobject and not self.type.is_pyobject:
            node = self.as_py_string_node(env)
        else:
            node = self
        # 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)

    def as_py_string_node(self, env):
        # Return a new StringNode with the same entry as this node
        # but whose type is a Python type instead of a C type.
        entry = self.entry
        env.add_py_string(entry)
898
        return StringNode(self.pos, value = self.value, entry = entry, type = py_object_type)
William Stein's avatar
William Stein committed
899 900 901 902 903 904 905 906
            
    def calculate_result_code(self):
        if self.type.is_pyobject:
            return self.entry.pystring_cname
        else:
            return self.entry.cname


907 908 909
class UnicodeNode(PyConstNode):
    #  entry   Symtab.Entry

910
    type = unicode_type
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927

    def analyse_types(self, env):
        self.entry = env.add_string_const(self.value)
        env.add_py_string(self.entry)

    def calculate_result_code(self):
        return self.entry.pystring_cname
    
    def _coerce_to(self, dst_type, env):
        if not dst_type.is_pyobject:
            node = StringNode(self.pos, entry = entry, type = py_object_type)
            return ConstNode.coerce_to(node, dst_type, env)
        else:
            return self
        # 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.
928 929 930
        
    def compile_time_value(self, env):
        return self.value
931 932


933 934 935
class IdentifierStringNode(ConstNode):
    # A Python string that behaves like an identifier, e.g. for
    # keyword arguments in a call, or for imported names
936 937 938 939 940 941 942 943 944
    type = PyrexTypes.py_object_type

    def analyse_types(self, env):
        self.cname = env.intern_identifier(self.value)

    def calculate_result_code(self):
        return self.cname


945
class LongNode(AtomicNewTempExprNode):
William Stein's avatar
William Stein committed
946 947 948 949
    #  Python long integer literal
    #
    #  value   string
    
950 951
    def compile_time_value(self, denv):
        return long(self.value)
952 953

    gil_message = "Constructing Python long int"
954
    
William Stein's avatar
William Stein committed
955 956
    def analyse_types(self, env):
        self.type = py_object_type
957
        self.gil_check(env)
William Stein's avatar
William Stein committed
958
        self.is_temp = 1
959 960 961

    gil_message = "Constructing Python long int"

962
    def generate_result_code(self, code):
William Stein's avatar
William Stein committed
963
        code.putln(
964
            '%s = PyLong_FromString((char *)"%s", 0, 0); %s' % (
965
                self.result(),
William Stein's avatar
William Stein committed
966
                self.value,
967
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
968 969


970
class ImagNode(AtomicNewTempExprNode):
William Stein's avatar
William Stein committed
971 972 973 974
    #  Imaginary number literal
    #
    #  value   float    imaginary part
    
975 976 977
    def compile_time_value(self, denv):
        return complex(0.0, self.value)
    
William Stein's avatar
William Stein committed
978 979
    def analyse_types(self, env):
        self.type = py_object_type
980
        self.gil_check(env)
William Stein's avatar
William Stein committed
981
        self.is_temp = 1
982 983 984

    gil_message = "Constructing complex number"

985
    def generate_result_code(self, code):
William Stein's avatar
William Stein committed
986
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
987
            "%s = PyComplex_FromDoubles(0.0, %s); %s" % (
988
                self.result(),
William Stein's avatar
William Stein committed
989
                self.value,
990
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
991 992 993 994 995 996


class NameNode(AtomicExprNode):
    #  Reference to a local or global variable name.
    #
    #  name            string    Python name of the variable
997
    #
William Stein's avatar
William Stein committed
998
    #  entry           Entry     Symbol table entry
999
    #  interned_cname  string
William Stein's avatar
William Stein committed
1000
    
1001 1002
    is_name = True
    is_cython_module = False
Robert Bradshaw's avatar
Robert Bradshaw committed
1003
    cython_attribute = None
1004
    lhs_of_first_assignment = False
1005
    entry = None
1006 1007 1008 1009 1010

    def create_analysed_rvalue(pos, env, entry):
        node = NameNode(pos)
        node.analyse_types(env, entry=entry)
        return node
Robert Bradshaw's avatar
Robert Bradshaw committed
1011
        
1012
    def as_cython_attribute(self):
Robert Bradshaw's avatar
Robert Bradshaw committed
1013
        return self.cython_attribute
1014 1015
    
    create_analysed_rvalue = staticmethod(create_analysed_rvalue)
William Stein's avatar
William Stein committed
1016
    
1017 1018 1019 1020
    def compile_time_value(self, denv):
        try:
            return denv.lookup(self.name)
        except KeyError:
Stefan Behnel's avatar
Stefan Behnel committed
1021
            error(self.pos, "Compile-time name '%s' not defined" % self.name)
1022 1023 1024 1025 1026 1027 1028 1029
    
    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
1030
            if entry and entry.is_cfunction:
1031 1032
                var_entry = entry.as_variable
                if var_entry:
1033 1034
                    if var_entry.is_builtin and Options.cache_builtins:
                        var_entry = env.declare_builtin(var_entry.name, self.pos)
1035 1036 1037 1038 1039 1040
                    node = NameNode(self.pos, name = self.name)
                    node.entry = var_entry
                    node.analyse_rvalue_entry(env)
                    return node
        return AtomicExprNode.coerce_to(self, dst_type, env)
    
William Stein's avatar
William Stein committed
1041 1042 1043
    def analyse_as_module(self, env):
        # Try to interpret this as a reference to a cimported module.
        # Returns the module scope, or None.
1044 1045 1046
        entry = self.entry
        if not entry:
            entry = env.lookup(self.name)
William Stein's avatar
William Stein committed
1047 1048 1049
        if entry and entry.as_module:
            return entry.as_module
        return None
1050 1051
        
    def analyse_as_type(self, env):
1052 1053 1054 1055
        if self.cython_attribute:
            type = PyrexTypes.parse_basic_type(self.cython_attribute)
        else:
            type = PyrexTypes.parse_basic_type(self.name)
1056 1057
        if type:
            return type
1058 1059 1060 1061 1062 1063 1064
        entry = self.entry
        if not entry:
            entry = env.lookup(self.name)
        if entry and entry.is_type:
            return entry.type
        else:
            return None
William Stein's avatar
William Stein committed
1065 1066 1067 1068
    
    def analyse_as_extension_type(self, env):
        # Try to interpret this as a reference to an extension type.
        # Returns the extension type, or None.
1069 1070 1071
        entry = self.entry
        if not entry:
            entry = env.lookup(self.name)
William Stein's avatar
William Stein committed
1072
        if entry and entry.is_type and entry.type.is_extension_type:
1073 1074 1075
            return entry.type
        else:
            return None
William Stein's avatar
William Stein committed
1076 1077
    
    def analyse_target_declaration(self, env):
1078 1079
        if not self.entry:
            self.entry = env.lookup_here(self.name)
William Stein's avatar
William Stein committed
1080 1081
        if not self.entry:
            self.entry = env.declare_var(self.name, py_object_type, self.pos)
1082
        env.control_flow.set_state(self.pos, (self.name, 'initalized'), True)
Robert Bradshaw's avatar
Robert Bradshaw committed
1083
        env.control_flow.set_state(self.pos, (self.name, 'source'), 'assignment')
1084 1085
        if self.entry.is_declared_generic:
            self.result_ctype = py_object_type
William Stein's avatar
William Stein committed
1086
    
1087 1088 1089
    def analyse_types(self, env):
        if self.entry is None:
            self.entry = env.lookup(self.name)
William Stein's avatar
William Stein committed
1090 1091
        if not self.entry:
            self.entry = env.declare_builtin(self.name, self.pos)
1092 1093 1094
        if not self.entry:
            self.type = PyrexTypes.error_type
            return
1095 1096 1097
        self.analyse_rvalue_entry(env)
        
    def analyse_target_types(self, env):
William Stein's avatar
William Stein committed
1098
        self.analyse_entry(env)
1099 1100 1101 1102
        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
1103
        self.entry.used = 1
1104
        if self.entry.type.is_buffer:
1105 1106 1107
            import Buffer
            Buffer.used_buffer_aux_vars(self.entry)
                
1108 1109 1110 1111
    def analyse_rvalue_entry(self, env):
        #print "NameNode.analyse_rvalue_entry:", self.name ###
        #print "Entry:", self.entry.__dict__ ###
        self.analyse_entry(env)
1112 1113
        entry = self.entry
        if entry.is_declared_generic:
William Stein's avatar
William Stein committed
1114
            self.result_ctype = py_object_type
1115
        if entry.is_pyglobal or entry.is_builtin:
1116 1117 1118 1119
            if Options.cache_builtins and entry.is_builtin:
                self.is_temp = 0
            else:
                self.is_temp = 1
1120
            env.use_utility_code(get_name_interned_utility_code)
1121 1122 1123 1124
            self.gil_check(env)

    gil_message = "Accessing Python global or builtin"

1125 1126
    def analyse_entry(self, env):
        #print "NameNode.analyse_entry:", self.name ###
William Stein's avatar
William Stein committed
1127
        self.check_identifier_kind()
1128 1129 1130 1131 1132
        entry = self.entry
        type = entry.type
        self.type = type
        if entry.is_pyglobal or entry.is_builtin:
            assert type.is_pyobject, "Python global or builtin not a Python object"
1133 1134
            self.interned_cname = self.entry.interned_cname = \
                env.intern_identifier(self.entry.name)
1135

William Stein's avatar
William Stein committed
1136
    def check_identifier_kind(self):
1137
        #print "NameNode.check_identifier_kind:", self.entry.name ###
1138
        #print self.entry.__dict__ ###
William Stein's avatar
William Stein committed
1139
        entry = self.entry
Stefan Behnel's avatar
Stefan Behnel committed
1140
        #entry.used = 1
William Stein's avatar
William Stein committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        if not (entry.is_const or entry.is_variable 
            or entry.is_builtin or entry.is_cfunction):
                if self.entry.as_variable:
                    self.entry = self.entry.as_variable
                else:
                    error(self.pos, 
                        "'%s' is not a constant, variable or function identifier" % self.name)
    
    def is_simple(self):
        #  If it's not a C variable, it'll be in a temp.
        return 1
    
    def calculate_target_results(self, env):
        pass
    
    def check_const(self):
        entry = self.entry
Robert Bradshaw's avatar
Robert Bradshaw committed
1158
        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
1159 1160 1161 1162
            self.not_const()
    
    def check_const_addr(self):
        entry = self.entry
1163
        if not (entry.is_cglobal or entry.is_cfunction or entry.is_builtin):
William Stein's avatar
William Stein committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
            self.addr_not_const()

    def is_lvalue(self):
        return self.entry.is_variable and \
            not self.entry.type.is_array and \
            not self.entry.is_readonly
    
    def is_ephemeral(self):
        #  Name nodes are never ephemeral, even if the
        #  result is in a temporary.
        return 0
Stefan Behnel's avatar
Stefan Behnel committed
1175 1176 1177
    
    def allocate_temp(self, env, result = None):
        AtomicExprNode.allocate_temp(self, env, result)
Stefan Behnel's avatar
Stefan Behnel committed
1178 1179 1180
        entry = self.entry
        if entry:
            entry.used = 1
1181 1182 1183
            if entry.type.is_buffer:
                import Buffer
                Buffer.used_buffer_aux_vars(entry)
Stefan Behnel's avatar
Stefan Behnel committed
1184 1185
            if entry.utility_code:
                env.use_utility_code(entry.utility_code)
Stefan Behnel's avatar
Stefan Behnel committed
1186
        
William Stein's avatar
William Stein committed
1187
    def calculate_result_code(self):
Stefan Behnel's avatar
Stefan Behnel committed
1188 1189
        entry = self.entry
        if not entry:
William Stein's avatar
William Stein committed
1190
            return "<error>" # There was an error earlier
Stefan Behnel's avatar
Stefan Behnel committed
1191
        return entry.cname
William Stein's avatar
William Stein committed
1192 1193
    
    def generate_result_code(self, code):
1194
        assert hasattr(self, 'entry')
William Stein's avatar
William Stein committed
1195 1196 1197
        entry = self.entry
        if entry is None:
            return # There was an error earlier
1198 1199 1200
        if entry.is_builtin and Options.cache_builtins:
            return # Lookup already cached
        elif entry.is_pyglobal or entry.is_builtin:
William Stein's avatar
William Stein committed
1201 1202 1203
            if entry.is_builtin:
                namespace = Naming.builtins_cname
            else: # entry.is_pyglobal
1204
                namespace = entry.scope.namespace_cname
1205 1206
            code.putln(
                '%s = __Pyx_GetName(%s, %s); %s' % (
1207
                self.result(),
1208 1209
                namespace, 
                self.interned_cname,
1210
                code.error_goto_if_null(self.result(), self.pos)))
1211 1212
        elif entry.is_local and False:
            # control flow not good enough yet
Robert Bradshaw's avatar
Robert Bradshaw committed
1213
            assigned = entry.scope.control_flow.get_state((entry.name, 'initalized'), self.pos)
1214 1215
            if assigned is False:
                error(self.pos, "local variable '%s' referenced before assignment" % entry.name)
Robert Bradshaw's avatar
Robert Bradshaw committed
1216 1217 1218
            elif not Options.init_local_none and assigned is None:
                code.putln('if (%s == 0) { PyErr_SetString(PyExc_UnboundLocalError, "%s"); %s }' % (entry.cname, entry.name, code.error_goto(self.pos)))
                entry.scope.control_flow.set_state(self.pos, (entry.name, 'initalized'), True)
William Stein's avatar
William Stein committed
1219 1220

    def generate_assignment_code(self, rhs, code):
1221
        #print "NameNode.generate_assignment_code:", self.name ###
William Stein's avatar
William Stein committed
1222 1223 1224
        entry = self.entry
        if entry is None:
            return # There was an error earlier
1225 1226 1227 1228

        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")
1229
        
1230 1231
        # 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
1232
        if entry.is_pyglobal:
1233
            namespace = self.entry.scope.namespace_cname
1234
            if entry.is_member:
Stefan Behnel's avatar
Stefan Behnel committed
1235
                # if the entry is a member we have to cheat: SetAttr does not work
1236
                # on types, so we create a descriptor which is then added to tp_dict
1237 1238 1239 1240 1241
                code.put_error_if_neg(self.pos,
                    'PyDict_SetItem(%s->tp_dict, %s, %s)' % (
                        namespace,
                        self.interned_cname,
                        rhs.py_result()))
1242
                # in Py2.6+, we need to invalidate the method cache
1243
                code.putln("PyType_Modified(%s);" %
1244
                           entry.scope.parent_type.typeptr_cname)
1245
            else: 
1246 1247 1248 1249 1250
                code.put_error_if_neg(self.pos,
                    'PyObject_SetAttr(%s, %s, %s)' % (
                        namespace,
                        self.interned_cname,
                        rhs.py_result()))
1251
                if debug_disposal_code:
Stefan Behnel's avatar
Stefan Behnel committed
1252 1253
                    print("NameNode.generate_assignment_code:")
                    print("...generating disposal code for %s" % rhs)
1254
                rhs.generate_disposal_code(code)
1255
                rhs.free_temps(code)
William Stein's avatar
William Stein committed
1256
        else:
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
            if self.type.is_buffer:
                # 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)

1267 1268
            if self.type.is_pyobject:
                rhs.make_owned_reference(code)
William Stein's avatar
William Stein committed
1269 1270 1271 1272
                #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() ###
1273
                if not self.lhs_of_first_assignment:
1274 1275 1276
                    if entry.is_local and not Options.init_local_none:
                        initalized = entry.scope.control_flow.get_state((entry.name, 'initalized'), self.pos)
                        if initalized is True:
1277
                            code.put_decref(self.result(), self.ctype())
1278
                        elif initalized is None:
1279
                            code.put_xdecref(self.result(), self.ctype())
1280
                    else:
1281 1282
                        code.put_decref(self.result(), self.ctype())
            code.putln('%s = %s;' % (self.result(), rhs.result_as(self.ctype())))
William Stein's avatar
William Stein committed
1283
            if debug_disposal_code:
Stefan Behnel's avatar
Stefan Behnel committed
1284 1285
                print("NameNode.generate_assignment_code:")
                print("...generating post-assignment code for %s" % rhs)
William Stein's avatar
William Stein committed
1286
            rhs.generate_post_assignment_code(code)
1287
            rhs.free_temps(code)
1288 1289

    def generate_acquire_buffer(self, rhs, code):
1290 1291 1292
        # 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.
1293 1294 1295 1296 1297 1298 1299
        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())))

1300 1301 1302
        buffer_aux = self.entry.buffer_aux
        bufstruct = buffer_aux.buffer_info_var.cname
        import Buffer
1303
        Buffer.put_assign_to_buffer(self.result(), rhstmp, buffer_aux, self.entry.type,
1304
                                    is_initialized=not self.lhs_of_first_assignment,
1305
                                    pos=self.pos, code=code)
1306 1307 1308 1309
        
        if not pretty_rhs:
            code.putln("%s = 0;" % rhstmp)
            code.funcstate.release_temp(rhstmp)
William Stein's avatar
William Stein committed
1310 1311 1312 1313 1314 1315 1316
    
    def generate_deletion_code(self, code):
        if self.entry is None:
            return # There was an error earlier
        if not self.entry.is_pyglobal:
            error(self.pos, "Deletion of local or C global name not supported")
            return
Robert Bradshaw's avatar
Robert Bradshaw committed
1317 1318
        code.put_error_if_neg(self.pos, 
            'PyObject_DelAttrString(%s, "%s")' % (
William Stein's avatar
William Stein committed
1319
                Naming.module_cname,
Robert Bradshaw's avatar
Robert Bradshaw committed
1320
                self.entry.name))
1321 1322 1323 1324 1325 1326 1327 1328
                
    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)))
William Stein's avatar
William Stein committed
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
            
class BackquoteNode(ExprNode):
    #  `expr`
    #
    #  arg    ExprNode
    
    subexprs = ['arg']
    
    def analyse_types(self, env):
        self.arg.analyse_types(env)
        self.arg = self.arg.coerce_to_pyobject(env)
        self.type = py_object_type
1341
        self.gil_check(env)
William Stein's avatar
William Stein committed
1342
        self.is_temp = 1
1343 1344 1345

    gil_message = "Backquote expression"

William Stein's avatar
William Stein committed
1346 1347
    def generate_result_code(self, code):
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
1348
            "%s = PyObject_Repr(%s); %s" % (
1349
                self.result(),
William Stein's avatar
William Stein committed
1350
                self.arg.py_result(),
1351
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
1352 1353 1354 1355 1356 1357 1358


class ImportNode(ExprNode):
    #  Used as part of import statement implementation.
    #  Implements result = 
    #    __import__(module_name, globals(), None, name_list)
    #
1359 1360
    #  module_name   IdentifierStringNode     dotted name of module
    #  name_list     ListNode or None         list of names to be imported
William Stein's avatar
William Stein committed
1361 1362 1363 1364 1365 1366 1367 1368
    
    subexprs = ['module_name', 'name_list']

    def analyse_types(self, env):
        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)
1369
            self.name_list.coerce_to_pyobject(env)
William Stein's avatar
William Stein committed
1370
        self.type = py_object_type
1371
        self.gil_check(env)
William Stein's avatar
William Stein committed
1372 1373
        self.is_temp = 1
        env.use_utility_code(import_utility_code)
1374 1375 1376

    gil_message = "Python import"

William Stein's avatar
William Stein committed
1377 1378 1379 1380 1381 1382
    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(
Robert Bradshaw's avatar
Robert Bradshaw committed
1383
            "%s = __Pyx_Import(%s, %s); %s" % (
1384
                self.result(),
William Stein's avatar
William Stein committed
1385 1386
                self.module_name.py_result(),
                name_list_code,
1387
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
1388 1389


1390
class IteratorNode(NewTempExprNode):
William Stein's avatar
William Stein committed
1391
    #  Used as part of for statement implementation.
1392 1393 1394 1395
    #
    #  allocate_counter_temp/release_counter_temp needs to be called
    #  by parent (ForInStatNode)
    #
William Stein's avatar
William Stein committed
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
    #  Implements result = iter(sequence)
    #
    #  sequence   ExprNode
    
    subexprs = ['sequence']
    
    def analyse_types(self, env):
        self.sequence.analyse_types(env)
        self.sequence = self.sequence.coerce_to_pyobject(env)
        self.type = py_object_type
1406
        self.gil_check(env)
William Stein's avatar
William Stein committed
1407
        self.is_temp = 1
1408 1409 1410

    gil_message = "Iterating over Python object"

1411 1412 1413 1414 1415 1416 1417
    def allocate_counter_temp(self, code):
        self.counter_cname = code.funcstate.allocate_temp(
            PyrexTypes.c_py_ssize_t_type, manage_ref=False)

    def release_counter_temp(self, code):
        code.funcstate.release_temp(self.counter_cname)

William Stein's avatar
William Stein committed
1418
    def generate_result_code(self, code):
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
        is_builtin_sequence = self.sequence.type is list_type or \
            self.sequence.type is tuple_type
        if is_builtin_sequence:
            code.putln(
                "if (likely(%s != Py_None)) {" % self.sequence.py_result())
        else:
            code.putln(
                "if (PyList_CheckExact(%s) || PyTuple_CheckExact(%s)) {" % (
                    self.sequence.py_result(),
                    self.sequence.py_result()))
1429 1430
        code.putln(
            "%s = 0; %s = %s; Py_INCREF(%s);" % (
1431
                self.counter_cname,
1432
                self.result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
1433
                self.sequence.py_result(),
1434
                self.result()))
1435
        code.putln("} else {")
1436 1437 1438 1439 1440 1441
        if is_builtin_sequence:
            code.putln(
                'PyErr_SetString(PyExc_TypeError, "\'NoneType\' object is not iterable"); %s' %
                code.error_goto(self.pos))
        else:
            code.putln("%s = -1; %s = PyObject_GetIter(%s); %s" % (
1442
                    self.counter_cname,
1443 1444 1445
                    self.result(),
                    self.sequence.py_result(),
                    code.error_goto_if_null(self.result(), self.pos)))
1446
        code.putln("}")
William Stein's avatar
William Stein committed
1447 1448


1449
class NextNode(AtomicNewTempExprNode):
William Stein's avatar
William Stein committed
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
    #  Used as part of for statement implementation.
    #  Implements result = iterator.next()
    #  Created during analyse_types phase.
    #  The iterator is not owned by this node.
    #
    #  iterator   ExprNode
    
    def __init__(self, iterator, env):
        self.pos = iterator.pos
        self.iterator = iterator
        self.type = py_object_type
        self.is_temp = 1
    
    def generate_result_code(self, code):
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
        if self.iterator.sequence.type is list_type:
            type_checks = [(list_type, "List")]
        elif self.iterator.sequence.type is tuple_type:
            type_checks = [(tuple_type, "Tuple")]
        else:
            type_checks = [(list_type, "List"), (tuple_type, "Tuple")]

        for py_type, prefix in type_checks:
            if len(type_checks) > 1:
                code.putln(
                    "if (likely(Py%s_CheckExact(%s))) {" % (
                        prefix, self.iterator.py_result()))
1476 1477
            code.putln(
                "if (%s >= Py%s_GET_SIZE(%s)) break;" % (
1478
                    self.iterator.counter_cname,
1479
                    prefix,
1480 1481 1482
                    self.iterator.py_result()))
            code.putln(
                "%s = Py%s_GET_ITEM(%s, %s); Py_INCREF(%s); %s++;" % (
1483
                    self.result(),
1484
                    prefix,
1485
                    self.iterator.py_result(),
1486
                    self.iterator.counter_cname,
1487
                    self.result(),
1488
                    self.iterator.counter_cname))
1489 1490 1491 1492
            if len(type_checks) > 1:
                code.put("} else ")
        if len(type_checks) == 1:
            return
1493
        code.putln("{")
William Stein's avatar
William Stein committed
1494 1495
        code.putln(
            "%s = PyIter_Next(%s);" % (
1496
                self.result(),
William Stein's avatar
William Stein committed
1497 1498 1499
                self.iterator.py_result()))
        code.putln(
            "if (!%s) {" %
1500
                self.result())
1501
        code.putln(code.error_goto_if_PyErr(self.pos))
Robert Bradshaw's avatar
Robert Bradshaw committed
1502 1503 1504
        code.putln("break;")
        code.putln("}")
        code.putln("}")
1505

William Stein's avatar
William Stein committed
1506

1507
class ExcValueNode(AtomicNewTempExprNode):
William Stein's avatar
William Stein committed
1508 1509 1510 1511
    #  Node created during analyse_types phase
    #  of an ExceptClauseNode to fetch the current
    #  exception value.
    
1512
    def __init__(self, pos, env, var):
William Stein's avatar
William Stein committed
1513 1514
        ExprNode.__init__(self, pos)
        self.type = py_object_type
1515
        self.var = var
William Stein's avatar
William Stein committed
1516
    
1517 1518 1519
    def calculate_result_code(self):
        return self.var

William Stein's avatar
William Stein committed
1520
    def generate_result_code(self, code):
1521
        pass
William Stein's avatar
William Stein committed
1522

1523 1524 1525
    def analyse_types(self, env):
        pass

William Stein's avatar
William Stein committed
1526

1527
class TempNode(ExprNode):
William Stein's avatar
William Stein committed
1528 1529
    #  Node created during analyse_types phase
    #  of some nodes to hold a temporary value.
1530 1531

    subexprs = []
William Stein's avatar
William Stein committed
1532 1533 1534 1535 1536 1537 1538
    
    def __init__(self, pos, type, env):
        ExprNode.__init__(self, pos)
        self.type = type
        if type.is_pyobject:
            self.result_ctype = py_object_type
        self.is_temp = 1
1539 1540 1541
        
    def analyse_types(self, env):
        return self.type
William Stein's avatar
William Stein committed
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
    
    def generate_result_code(self, code):
        pass


class PyTempNode(TempNode):
    #  TempNode holding a Python value.
    
    def __init__(self, pos, env):
        TempNode.__init__(self, pos, PyrexTypes.py_object_type, env)


#-------------------------------------------------------------------
#
#  Trailer nodes
#
#-------------------------------------------------------------------

class IndexNode(ExprNode):
    #  Sequence indexing.
    #
    #  base     ExprNode
    #  index    ExprNode
1565 1566 1567 1568 1569 1570
    #  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.
William Stein's avatar
William Stein committed
1571
    
1572 1573 1574 1575 1576 1577
    subexprs = ['base', 'index', 'indices']
    indices = None

    def __init__(self, pos, index, *args, **kw):
        ExprNode.__init__(self, pos, index=index, *args, **kw)
        self._index = index
William Stein's avatar
William Stein committed
1578
    
1579 1580 1581 1582 1583 1584 1585 1586
    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)
    
William Stein's avatar
William Stein committed
1587 1588 1589 1590 1591
    def is_ephemeral(self):
        return self.base.is_ephemeral()
    
    def analyse_target_declaration(self, env):
        pass
1592 1593 1594 1595 1596 1597
        
    def analyse_as_type(self, env):
        base_type = self.base.analyse_as_type(env)
        if base_type and not base_type.is_pyobject:
            return PyrexTypes.CArrayType(base_type, int(self.index.compile_time_value(env)))
        return None
William Stein's avatar
William Stein committed
1598 1599
    
    def analyse_types(self, env):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1600 1601 1602 1603
        self.analyse_base_and_index_types(env, getting = 1)
    
    def analyse_target_types(self, env):
        self.analyse_base_and_index_types(env, setting = 1)
1604

Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1605
    def analyse_base_and_index_types(self, env, getting = 0, setting = 0):
1606 1607 1608
        # Note: This might be cleaned up by having IndexNode
        # parsed in a saner way and only construct the tuple if
        # needed.
1609 1610 1611 1612

        # 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.
1613 1614
        self.is_buffer_access = False

William Stein's avatar
William Stein committed
1615
        self.base.analyse_types(env)
1616 1617 1618
        # Handle the case where base is a literal char* (and we expect a string, not an int)
        if isinstance(self.base, StringNode):
            self.base = self.base.coerce_to_pyobject(env)
1619 1620 1621

        skip_child_analysis = False
        buffer_access = False
1622
        if self.base.type.is_buffer:
1623 1624 1625
            assert hasattr(self.base, "entry") # Must be a NameNode-like node
            if self.indices:
                indices = self.indices
1626
            else:
1627 1628 1629 1630 1631 1632
                # On cloning, indices is cloned. Otherwise, unpack index into indices
                assert not isinstance(self.index, CloneNode)
                if isinstance(self.index, TupleNode):
                    indices = self.index.args
                else:
                    indices = [self.index]
1633
            if len(indices) == self.base.type.ndim:
1634 1635 1636 1637 1638 1639
                buffer_access = True
                skip_child_analysis = True
                for x in indices:
                    x.analyse_types(env)
                    if not x.type.is_int:
                        buffer_access = False
1640

1641 1642
        if buffer_access:
            self.indices = indices
1643
            self.index = None
1644 1645
            self.type = self.base.type.dtype
            self.is_buffer_access = True
1646
            self.buffer_type = self.base.entry.type
1647 1648

            if getting and self.type.is_pyobject:
1649
                self.is_temp = True
1650 1651 1652 1653 1654
            if setting:
                if not self.base.entry.type.writable:
                    error(self.pos, "Writing to readonly buffer")
                else:
                    self.base.entry.buffer_aux.writable_needed = True
1655
        else:
1656 1657 1658 1659
            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)
1660
            self.original_index_type = self.index.type
1661
            if self.base.type.is_pyobject:
1662
                if self.index.type.is_int and not self.index.type.is_longlong:
1663 1664 1665 1666 1667 1668
                    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)
                self.type = py_object_type
                self.gil_check(env)
                self.is_temp = 1
William Stein's avatar
William Stein committed
1669
            else:
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
                if self.base.type.is_ptr or self.base.type.is_array:
                    self.type = self.base.type.base_type
                else:
                    error(self.pos,
                        "Attempting to index non-array type '%s'" %
                            self.base.type)
                    self.type = PyrexTypes.error_type
                if self.index.type.is_pyobject:
                    self.index = self.index.coerce_to(
                        PyrexTypes.c_py_ssize_t_type, env)
                if not self.index.type.is_int:
                    error(self.pos,
                        "Invalid index type '%s'" %
                            self.index.type)
1684 1685 1686

    gil_message = "Indexing Python object"

William Stein's avatar
William Stein committed
1687 1688 1689 1690 1691 1692
    def check_const_addr(self):
        self.base.check_const_addr()
        self.index.check_const()
    
    def is_lvalue(self):
        return 1
Dag Sverre Seljebotn's avatar
merge  
Dag Sverre Seljebotn committed
1693

William Stein's avatar
William Stein committed
1694
    def calculate_result_code(self):
1695
        if self.is_buffer_access:
1696
            return "(*%s)" % self.buffer_ptr_code
1697 1698
        else:
            return "(%s[%s])" % (
1699
                self.base.result(), self.index.result())
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1700 1701 1702 1703 1704 1705 1706 1707 1708
            
    def index_unsigned_parameter(self):
        if self.index.type.is_int:
            if self.original_index_type.signed:
                return ", 0"
            else:
                return ", sizeof(Py_ssize_t) <= sizeof(%s)" % self.original_index_type.declaration_code("")
        else:
            return ""
1709 1710 1711

    def generate_subexpr_evaluation_code(self, code):
        self.base.generate_evaluation_code(code)
1712
        if not self.indices:
1713 1714
            self.index.generate_evaluation_code(code)
        else:
1715 1716
            for i in self.indices:
                i.generate_evaluation_code(code)
1717
        
1718 1719
    def generate_subexpr_disposal_code(self, code):
        self.base.generate_disposal_code(code)
1720
        if not self.indices:
1721 1722
            self.index.generate_disposal_code(code)
        else:
1723 1724
            for i in self.indices:
                i.generate_disposal_code(code)
1725

1726 1727 1728 1729 1730 1731 1732 1733
    def free_subexpr_temps(self, code):
        self.base.free_temps(code)
        if not self.indices:
            self.index.free_temps(code)
        else:
            for i in self.indices:
                i.free_temps(code)

William Stein's avatar
William Stein committed
1734
    def generate_result_code(self, code):
1735
        if self.is_buffer_access:
1736 1737
            if code.globalstate.directives['nonecheck']:
                self.put_nonecheck(code)
1738 1739 1740 1741
            self.buffer_ptr_code = self.buffer_lookup_code(code)
            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))
1742
                code.putln("Py_INCREF((PyObject*)%s);" % self.result())
1743
        elif self.type.is_pyobject:
1744
            if self.index.type.is_int:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1745
                function = "__Pyx_GetItemInt"
1746
                index_code = self.index.result()
1747
                code.globalstate.use_utility_code(getitem_int_utility_code)
1748
            else:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1749 1750 1751 1752 1753
                function = "PyObject_GetItem"
                index_code = self.index.py_result()
                sign_code = ""
            code.putln(
                "%s = %s(%s, %s%s); if (!%s) %s" % (
1754
                    self.result(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1755 1756 1757 1758
                    function,
                    self.base.py_result(),
                    index_code,
                    self.index_unsigned_parameter(),
1759
                    self.result(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1760
                    code.error_goto(self.pos)))
1761

Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1762 1763 1764
    def generate_setitem_code(self, value_code, code):
        if self.index.type.is_int:
            function = "__Pyx_SetItemInt"
1765
            index_code = self.index.result()
1766
            code.globalstate.use_utility_code(setitem_int_utility_code)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1767 1768
        else:
            index_code = self.index.py_result()
1769 1770 1771 1772
            if self.base.type is dict_type:
                function = "PyDict_SetItem"
            elif self.base.type is list_type:
                function = "PyList_SetItem"
1773 1774 1775 1776 1777 1778
            # don't use PyTuple_SetItem(), as we'd normally get a
            # TypeError when changing a tuple, while PyTuple_SetItem()
            # would allow updates
            #
            #elif self.base.type is tuple_type:
            #    function = "PyTuple_SetItem"
1779 1780
            else:
                function = "PyObject_SetItem"
1781
        code.putln(
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1782 1783
            "if (%s(%s, %s, %s%s) < 0) %s" % (
                function,
1784
                self.base.py_result(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1785 1786 1787 1788
                index_code,
                value_code,
                self.index_unsigned_parameter(),
                code.error_goto(self.pos)))
1789 1790 1791

    def generate_buffer_setitem_code(self, rhs, code, op=""):
        # Used from generate_assignment_code and InPlaceAssignmentNode
1792 1793
        if code.globalstate.directives['nonecheck']:
            self.put_nonecheck(code)
1794 1795 1796 1797
        ptrexpr = self.buffer_lookup_code(code)
        if self.buffer_type.dtype.is_pyobject:
            # Must manage refcounts. Decref what is already there
            # and incref what we put in.
1798
            ptr = code.funcstate.allocate_temp(self.buffer_type.buffer_ptr_type, manage_ref=False)
1799
            rhs_code = rhs.result()
1800 1801 1802 1803 1804 1805 1806 1807
            code.putln("%s = %s;" % (ptr, ptrexpr))
            code.putln("Py_DECREF(*%s); Py_INCREF(%s);" % (
                ptr, rhs_code
                ))
            code.putln("*%s %s= %s;" % (ptr, op, rhs_code))
            code.funcstate.release_temp(ptr)
        else: 
            # Simple case
1808
            code.putln("*%s %s= %s;" % (ptrexpr, op, rhs.result()))
1809

William Stein's avatar
William Stein committed
1810 1811
    def generate_assignment_code(self, rhs, code):
        self.generate_subexpr_evaluation_code(code)
1812
        if self.is_buffer_access:
1813
            self.generate_buffer_setitem_code(rhs, code)
1814
        elif self.type.is_pyobject:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1815
            self.generate_setitem_code(rhs.py_result(), code)
William Stein's avatar
William Stein committed
1816 1817 1818
        else:
            code.putln(
                "%s = %s;" % (
1819
                    self.result(), rhs.result()))
1820
        self.generate_subexpr_disposal_code(code)
1821
        self.free_subexpr_temps(code)
William Stein's avatar
William Stein committed
1822
        rhs.generate_disposal_code(code)
1823
        rhs.free_temps(code)
William Stein's avatar
William Stein committed
1824 1825 1826
    
    def generate_deletion_code(self, code):
        self.generate_subexpr_evaluation_code(code)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1827 1828
        #if self.type.is_pyobject:
        if self.index.type.is_int:
1829
            function = "__Pyx_DelItemInt"
1830
            index_code = self.index.result()
1831
            code.globalstate.use_utility_code(delitem_int_utility_code)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1832 1833
        else:
            index_code = self.index.py_result()
1834 1835 1836 1837
            if self.base.type is dict_type:
                function = "PyDict_DelItem"
            else:
                function = "PyObject_DelItem"
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1838
        code.putln(
1839
            "if (%s(%s, %s%s) < 0) %s" % (
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1840
                function,
William Stein's avatar
William Stein committed
1841
                self.base.py_result(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1842
                index_code,
1843
                self.index_unsigned_parameter(),
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1844
                code.error_goto(self.pos)))
William Stein's avatar
William Stein committed
1845
        self.generate_subexpr_disposal_code(code)
1846

1847
    def buffer_lookup_code(self, code):
1848
        # Assign indices to temps
1849
        index_temps = [code.funcstate.allocate_temp(i.type, manage_ref=False) for i in self.indices]
1850
        for temp, index in zip(index_temps, self.indices):
1851
            code.putln("%s = %s;" % (temp, index.result()))
1852 1853
        # Generate buffer access code using these temps
        import Buffer
1854 1855
        # The above could happen because child_attrs is wrong somewhere so that
        # options are not propagated.
1856 1857 1858
        return Buffer.put_buffer_lookup_code(entry=self.base.entry,
                                             index_signeds=[i.type.signed for i in self.indices],
                                             index_cnames=index_temps,
1859
                                             options=code.globalstate.directives,
1860
                                             pos=self.pos, code=code)
William Stein's avatar
William Stein committed
1861

1862 1863 1864 1865 1866 1867 1868
    def put_nonecheck(self, code):
        code.globalstate.use_utility_code(raise_noneindex_error_utility_code)
        code.putln("if (%s) {" % code.unlikely("%s == Py_None") % self.base.result_as(PyrexTypes.py_object_type))
        code.putln("__Pyx_RaiseNoneIndexingError();")
        code.putln(code.error_goto(self.pos))
        code.putln("}")

William Stein's avatar
William Stein committed
1869 1870 1871 1872 1873 1874 1875 1876 1877
class SliceIndexNode(ExprNode):
    #  2-element slice indexing
    #
    #  base      ExprNode
    #  start     ExprNode or None
    #  stop      ExprNode or None
    
    subexprs = ['base', 'start', 'stop']
    
1878 1879
    def compile_time_value(self, denv):
        base = self.base.compile_time_value(denv)
1880 1881 1882 1883 1884 1885 1886 1887
        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)
1888 1889 1890 1891 1892
        try:
            return base[start:stop]
        except Exception, e:
            self.compile_time_value_error(e)
    
William Stein's avatar
William Stein committed
1893 1894 1895 1896 1897 1898 1899 1900 1901
    def analyse_target_declaration(self, env):
        pass

    def analyse_types(self, env):
        self.base.analyse_types(env)
        if self.start:
            self.start.analyse_types(env)
        if self.stop:
            self.stop.analyse_types(env)
1902 1903 1904 1905 1906 1907 1908 1909
        if self.base.type.is_array or self.base.type.is_ptr:
            # we need a ptr type here instead of an array type, as
            # array types can result in invalid type casts in the C
            # code
            self.type = PyrexTypes.CPtrType(self.base.type.base_type)
        else:
            self.base = self.base.coerce_to_pyobject(env)
            self.type = py_object_type
1910
        c_int = PyrexTypes.c_py_ssize_t_type
William Stein's avatar
William Stein committed
1911 1912 1913 1914
        if self.start:
            self.start = self.start.coerce_to(c_int, env)
        if self.stop:
            self.stop = self.stop.coerce_to(c_int, env)
1915
        self.gil_check(env)
William Stein's avatar
William Stein committed
1916
        self.is_temp = 1
1917 1918 1919

    gil_message = "Slicing Python object"

William Stein's avatar
William Stein committed
1920
    def generate_result_code(self, code):
1921 1922 1923 1924
        if not self.type.is_pyobject:
            error(self.pos,
                  "Slicing is not currently supported for '%s'." % self.type)
            return
William Stein's avatar
William Stein committed
1925
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
1926
            "%s = PySequence_GetSlice(%s, %s, %s); %s" % (
1927
                self.result(),
William Stein's avatar
William Stein committed
1928 1929 1930
                self.base.py_result(),
                self.start_code(),
                self.stop_code(),
1931
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
1932 1933 1934
    
    def generate_assignment_code(self, rhs, code):
        self.generate_subexpr_evaluation_code(code)
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
        if self.type.is_pyobject:
            code.put_error_if_neg(self.pos, 
                "PySequence_SetSlice(%s, %s, %s, %s)" % (
                    self.base.py_result(),
                    self.start_code(),
                    self.stop_code(),
                    rhs.result()))
        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
1950 1951
            if rhs.type.is_array:
                array_length = rhs.type.size
1952
                self.generate_slice_guard_code(code, array_length)
Stefan Behnel's avatar
Stefan Behnel committed
1953
            else:
1954
                error("Slice assignments from pointers are not yet supported.")
Stefan Behnel's avatar
Stefan Behnel committed
1955 1956
                # FIXME: fix the array size according to start/stop
                array_length = self.base.type.size
1957 1958 1959 1960
            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
1961 1962
        self.generate_subexpr_disposal_code(code)
        rhs.generate_disposal_code(code)
1963
        rhs.free_temps(code)
William Stein's avatar
William Stein committed
1964 1965

    def generate_deletion_code(self, code):
1966 1967 1968 1969
        if not self.type.is_pyobject:
            error(self.pos,
                  "Deleting slices is only supported for Python types, not '%s'." % self.type)
            return
William Stein's avatar
William Stein committed
1970
        self.generate_subexpr_evaluation_code(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
1971 1972
        code.put_error_if_neg(self.pos,
            "PySequence_DelSlice(%s, %s, %s)" % (
William Stein's avatar
William Stein committed
1973 1974
                self.base.py_result(),
                self.start_code(),
Robert Bradshaw's avatar
Robert Bradshaw committed
1975
                self.stop_code()))
William Stein's avatar
William Stein committed
1976
        self.generate_subexpr_disposal_code(code)
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986

    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
1987
                if stop < 0:
1988
                    slice_size = self.base.type.size + stop
Stefan Behnel's avatar
Stefan Behnel committed
1989 1990
                else:
                    slice_size = stop
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
                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))
            code.putln('PyErr_Format(PyExc_ValueError, "Assignment to slice of wrong length, expected %%d, got %%d", %d, (%s));' % (
                        target_size, check))
            code.putln(code.error_goto(self.pos))
            code.putln("}")
William Stein's avatar
William Stein committed
2025 2026 2027
    
    def start_code(self):
        if self.start:
2028
            return self.start.result()
William Stein's avatar
William Stein committed
2029 2030 2031 2032 2033
        else:
            return "0"
    
    def stop_code(self):
        if self.stop:
2034
            return self.stop.result()
2035 2036
        elif self.base.type.is_array:
            return self.base.type.size
William Stein's avatar
William Stein committed
2037
        else:
2038
            return "PY_SSIZE_T_MAX"
William Stein's avatar
William Stein committed
2039 2040
    
    def calculate_result_code(self):
2041
        # self.result() is not used, but this method must exist
William Stein's avatar
William Stein committed
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
        return "<unused>"
    

class SliceNode(ExprNode):
    #  start:stop:step in subscript list
    #
    #  start     ExprNode
    #  stop      ExprNode
    #  step      ExprNode
    
2052 2053
    def compile_time_value(self, denv):
        start = self.start.compile_time_value(denv)
2054 2055 2056 2057 2058 2059 2060 2061
        if self.stop is None:
            stop = None
        else:
            stop = self.stop.compile_time_value(denv)
        if self.step is None:
            step = None
        else:
            step = self.step.compile_time_value(denv)
2062 2063 2064 2065 2066
        try:
            return slice(start, stop, step)
        except Exception, e:
            self.compile_time_value_error(e)

William Stein's avatar
William Stein committed
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
    subexprs = ['start', 'stop', 'step']
    
    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)
        self.type = py_object_type
2077
        self.gil_check(env)
William Stein's avatar
William Stein committed
2078
        self.is_temp = 1
2079 2080 2081

    gil_message = "Constructing Python slice object"

William Stein's avatar
William Stein committed
2082 2083
    def generate_result_code(self, code):
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
2084
            "%s = PySlice_New(%s, %s, %s); %s" % (
2085
                self.result(),
William Stein's avatar
William Stein committed
2086 2087 2088
                self.start.py_result(), 
                self.stop.py_result(), 
                self.step.py_result(),
2089
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
2090

2091 2092 2093 2094 2095 2096

class CallNode(ExprNode):
    def gil_check(self, env):
        # Make sure we're not in a nogil environment
        if env.nogil:
            error(self.pos, "Calling gil-requiring function without gil")
Robert Bradshaw's avatar
Robert Bradshaw committed
2097 2098 2099 2100 2101 2102 2103
    
    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):
2104
                items.append(DictItemNode(pos=arg.pos, key=IdentifierStringNode(pos=arg.pos, value=member.name), value=arg))
Robert Bradshaw's avatar
Robert Bradshaw committed
2105 2106 2107 2108 2109 2110 2111
            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
2112 2113 2114


class SimpleCallNode(CallNode):
William Stein's avatar
William Stein committed
2115 2116 2117 2118 2119 2120 2121
    #  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
2122
    #  wrapper_call   bool                 used internally
2123
    #  has_optional_args   bool            used internally
William Stein's avatar
William Stein committed
2124 2125 2126 2127 2128 2129
    
    subexprs = ['self', 'coerced_self', 'function', 'args', 'arg_tuple']
    
    self = None
    coerced_self = None
    arg_tuple = None
2130
    wrapper_call = False
2131
    has_optional_args = False
William Stein's avatar
William Stein committed
2132
    
2133 2134 2135 2136 2137 2138 2139
    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)
2140 2141
            
    def analyse_as_type(self, env):
2142
        attr = self.function.as_cython_attribute()
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
        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
2155

William Stein's avatar
William Stein committed
2156
    def analyse_types(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
2157 2158
        if self.analyse_as_type_constructor(env):
            return
William Stein's avatar
William Stein committed
2159 2160 2161
        function = self.function
        function.is_called = 1
        self.function.analyse_types(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
2162 2163 2164 2165 2166 2167 2168 2169 2170
        if function.is_attribute and function.is_py_attr and \
           function.attribute == "append" and len(self.args) == 1:
            # L.append(x) is almost always applied to a list
            self.py_func = self.function
            self.function = NameNode(pos=self.function.pos, name="__Pyx_PyObject_Append")
            self.function.analyse_types(env)
            self.self = self.py_func.obj
            function.obj = CloneNode(self.self)
            env.use_utility_code(append_utility_code)
William Stein's avatar
William Stein committed
2171 2172 2173 2174 2175 2176 2177
        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)
        func_type = self.function_type()
        if func_type.is_pyobject:
2178 2179
            self.arg_tuple = TupleNode(self.pos, args = self.args)
            self.arg_tuple.analyse_types(env)
William Stein's avatar
William Stein committed
2180 2181
            self.args = None
            self.type = py_object_type
2182
            self.gil_check(env)
William Stein's avatar
William Stein committed
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
            self.is_temp = 1
        else:
            for arg in self.args:
                arg.analyse_types(env)
            if self.self and func_type.args:
                # Coerce 'self' to the type expected by the method.
                expected_type = func_type.args[0].type
                self.coerced_self = CloneNode(self.self).coerce_to(
                    expected_type, env)
                # Insert coerced 'self' argument into argument list.
                self.args.insert(0, self.coerced_self)
            self.analyse_c_function_call(env)
    
    def function_type(self):
        # Return the type of the function being called, coercing a function
        # pointer to a function if necessary.
        func_type = self.function.type
        if func_type.is_ptr:
            func_type = func_type.base_type
        return func_type
    
    def analyse_c_function_call(self, env):
        func_type = self.function_type()
        # Check function type
        if not func_type.is_cfunction:
            if not func_type.is_error:
                error(self.pos, "Calling non-function type '%s'" %
                    func_type)
            self.type = PyrexTypes.error_type
            self.result_code = "<error>"
            return
        # Check no. of args
2215 2216
        max_nargs = len(func_type.args)
        expected_nargs = max_nargs - func_type.optional_arg_count
William Stein's avatar
William Stein committed
2217 2218
        actual_nargs = len(self.args)
        if actual_nargs < expected_nargs \
2219
            or (not func_type.has_varargs and actual_nargs > max_nargs):
William Stein's avatar
William Stein committed
2220 2221 2222
                expected_str = str(expected_nargs)
                if func_type.has_varargs:
                    expected_str = "at least " + expected_str
2223
                elif func_type.optional_arg_count:
2224
                    if actual_nargs < max_nargs:
2225 2226 2227
                        expected_str = "at least " + expected_str
                    else:
                        expected_str = "at most " + str(max_nargs)
William Stein's avatar
William Stein committed
2228 2229 2230 2231 2232 2233 2234
                error(self.pos, 
                    "Call with wrong number of arguments (expected %s, got %s)"
                        % (expected_str, actual_nargs))
                self.args = None
                self.type = PyrexTypes.error_type
                self.result_code = "<error>"
                return
2235 2236 2237 2238 2239
        if func_type.optional_arg_count and expected_nargs != actual_nargs:
            self.has_optional_args = 1
            self.is_temp = 1
            self.opt_arg_struct = env.allocate_temp(func_type.op_arg_struct.base_type)
            env.release_temp(self.opt_arg_struct)
William Stein's avatar
William Stein committed
2240
        # Coerce arguments
2241
        for i in range(min(max_nargs, actual_nargs)):
William Stein's avatar
William Stein committed
2242 2243
            formal_type = func_type.args[i].type
            self.args[i] = self.args[i].coerce_to(formal_type, env)
2244
        for i in range(max_nargs, actual_nargs):
William Stein's avatar
William Stein committed
2245 2246 2247 2248 2249
            if self.args[i].type.is_pyobject:
                error(self.args[i].pos, 
                    "Python object cannot be passed as a varargs parameter")
        # Calc result type and code fragment
        self.type = func_type.return_type
2250 2251 2252
        if self.type.is_pyobject \
            or func_type.exception_value is not None \
            or func_type.exception_check:
William Stein's avatar
William Stein committed
2253
                self.is_temp = 1
2254 2255
                if self.type.is_pyobject:
                    self.result_ctype = py_object_type
Robert Bradshaw's avatar
Robert Bradshaw committed
2256 2257 2258 2259
        # C++ exception handler
        if func_type.exception_check == '+':
            if func_type.exception_value is None:
                env.use_utility_code(cpp_exception_utility_code)
2260 2261 2262
        # Check gil
        if not func_type.nogil:
            self.gil_check(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
2263

William Stein's avatar
William Stein committed
2264 2265 2266 2267 2268 2269 2270 2271 2272
    def calculate_result_code(self):
        return self.c_call_code()
    
    def c_call_code(self):
        func_type = self.function_type()
        if self.args is None or not func_type.is_cfunction:
            return "<error>"
        formal_args = func_type.args
        arg_list_code = []
2273 2274 2275 2276 2277
        args = zip(formal_args, self.args)
        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
2278 2279
                arg_code = actual_arg.result_as(formal_arg.type)
                arg_list_code.append(arg_code)
2280
                
2281 2282 2283
        if func_type.is_overridable:
            arg_list_code.append(str(int(self.wrapper_call or self.function.entry.is_unbound_cmethod)))
                
2284
        if func_type.optional_arg_count:
2285
            if expected_nargs == actual_nargs:
2286
                optional_args = 'NULL'
2287
            else:
2288
                optional_args = "&%s" % self.opt_arg_struct
2289
            arg_list_code.append(optional_args)
2290
            
William Stein's avatar
William Stein committed
2291
        for actual_arg in self.args[len(formal_args):]:
2292 2293
            arg_list_code.append(actual_arg.result())
        result = "%s(%s)" % (self.function.result(),
Stefan Behnel's avatar
Stefan Behnel committed
2294
            ', '.join(arg_list_code))
2295 2296 2297
#        if self.wrapper_call or \
#                self.function.entry.is_unbound_cmethod and self.function.entry.type.is_overridable:
#            result = "(%s = 1, %s)" % (Naming.skip_dispatch_cname, result)
William Stein's avatar
William Stein committed
2298 2299 2300 2301 2302
        return result
    
    def generate_result_code(self, code):
        func_type = self.function_type()
        if func_type.is_pyobject:
2303
            arg_code = self.arg_tuple.py_result()
William Stein's avatar
William Stein committed
2304
            code.putln(
2305
                "%s = PyObject_Call(%s, %s, NULL); %s" % (
2306
                    self.result(),
William Stein's avatar
William Stein committed
2307
                    self.function.py_result(),
2308
                    arg_code,
2309
                    code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
2310
        elif func_type.is_cfunction:
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
            if self.has_optional_args:
                actual_nargs = len(self.args)
                expected_nargs = len(func_type.args) - func_type.optional_arg_count
                code.putln("%s.%s = %s;" % (
                        self.opt_arg_struct,
                        Naming.pyrex_prefix + "n",
                        len(self.args) - expected_nargs))
                args = zip(func_type.args, self.args)
                for formal_arg, actual_arg in args[expected_nargs:actual_nargs]:
                    code.putln("%s.%s = %s;" % (
                            self.opt_arg_struct,
                            formal_arg.name,
                            actual_arg.result_as(formal_arg.type)))
William Stein's avatar
William Stein committed
2324 2325
            exc_checks = []
            if self.type.is_pyobject:
2326
                exc_checks.append("!%s" % self.result())
William Stein's avatar
William Stein committed
2327
            else:
2328 2329
                exc_val = func_type.exception_value
                exc_check = func_type.exception_check
William Stein's avatar
William Stein committed
2330
                if exc_val is not None:
2331
                    exc_checks.append("%s == %s" % (self.result(), exc_val))
William Stein's avatar
William Stein committed
2332 2333 2334 2335
                if exc_check:
                    exc_checks.append("PyErr_Occurred()")
            if self.is_temp or exc_checks:
                rhs = self.c_call_code()
2336 2337
                if self.result():
                    lhs = "%s = " % self.result()
William Stein's avatar
William Stein committed
2338 2339 2340 2341 2342 2343 2344
                    if self.is_temp and self.type.is_pyobject:
                        #return_type = self.type # func_type.return_type
                        #print "SimpleCallNode.generate_result_code: casting", rhs, \
                        #	"from", return_type, "to pyobject" ###
                        rhs = typecast(py_object_type, self.type, rhs)
                else:
                    lhs = ""
Felix Wu's avatar
Felix Wu committed
2345
                if func_type.exception_check == '+':
Robert Bradshaw's avatar
Robert Bradshaw committed
2346 2347 2348 2349 2350 2351
                    if func_type.exception_value is None:
                        raise_py_exception = "__Pyx_CppExn2PyErr()"
                    elif func_type.exception_value.type.is_pyobject:
                        raise_py_exception = 'PyErr_SetString(%s, "")' % func_type.exception_value.entry.cname
                    else:
                        raise_py_exception = '%s(); if (!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError , "Error converting c++ exception.")' % func_type.exception_value.entry.cname
Felix Wu's avatar
Felix Wu committed
2352
                    code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
2353
                    "try {%s%s;} catch(...) {%s; %s}" % (
Felix Wu's avatar
Felix Wu committed
2354 2355
                        lhs,
                        rhs,
Robert Bradshaw's avatar
Robert Bradshaw committed
2356
                        raise_py_exception,
Felix Wu's avatar
Felix Wu committed
2357
                        code.error_goto(self.pos)))
2358 2359 2360 2361 2362 2363
                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))
William Stein's avatar
William Stein committed
2364

2365
class GeneralCallNode(CallNode):
William Stein's avatar
William Stein committed
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
    #  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
    #  starstar_arg     ExprNode or None  Dict of extra keyword args
    
    subexprs = ['function', 'positional_args', 'keyword_args', 'starstar_arg']

2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
    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)
        starstar_arg = self.starstar_arg.compile_time_value(denv)
        try:
            keyword_args.update(starstar_arg)
            return function(*positional_args, **keyword_args)
        except Exception, e:
            self.compile_time_value_error(e)
2386 2387 2388 2389 2390 2391
            
    def explicit_args_kwds(self):
        if self.starstar_arg or not isinstance(self.positional_args, TupleNode):
            raise PostParseError(self.pos,
                'Compile-time keyword arguments must be explicit.')
        return self.positional_args.args, self.keyword_args
2392

William Stein's avatar
William Stein committed
2393
    def analyse_types(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
2394 2395
        if self.analyse_as_type_constructor(env):
            return
William Stein's avatar
William Stein committed
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
        self.function.analyse_types(env)
        self.positional_args.analyse_types(env)
        if self.keyword_args:
            self.keyword_args.analyse_types(env)
        if self.starstar_arg:
            self.starstar_arg.analyse_types(env)
        self.function = self.function.coerce_to_pyobject(env)
        self.positional_args = \
            self.positional_args.coerce_to_pyobject(env)
        if self.starstar_arg:
            self.starstar_arg = \
                self.starstar_arg.coerce_to_pyobject(env)
        self.type = py_object_type
2409
        self.gil_check(env)
William Stein's avatar
William Stein committed
2410 2411 2412 2413
        self.is_temp = 1
        
    def generate_result_code(self, code):
        if self.keyword_args and self.starstar_arg:
Robert Bradshaw's avatar
Robert Bradshaw committed
2414 2415
            code.put_error_if_neg(self.pos, 
                "PyDict_Update(%s, %s)" % (
William Stein's avatar
William Stein committed
2416
                    self.keyword_args.py_result(), 
Robert Bradshaw's avatar
Robert Bradshaw committed
2417
                    self.starstar_arg.py_result()))
William Stein's avatar
William Stein committed
2418 2419 2420 2421 2422 2423 2424 2425
            keyword_code = self.keyword_args.py_result()
        elif self.keyword_args:
            keyword_code = self.keyword_args.py_result()
        elif self.starstar_arg:
            keyword_code = self.starstar_arg.py_result()
        else:
            keyword_code = None
        if not keyword_code:
2426
            call_code = "PyObject_Call(%s, %s, NULL)" % (
William Stein's avatar
William Stein committed
2427 2428 2429 2430 2431 2432 2433 2434
                self.function.py_result(),
                self.positional_args.py_result())
        else:
            call_code = "PyEval_CallObjectWithKeywords(%s, %s, %s)" % (
                self.function.py_result(),
                self.positional_args.py_result(),
                keyword_code)
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
2435
            "%s = %s; %s" % (
2436
                self.result(),
William Stein's avatar
William Stein committed
2437
                call_code,
2438
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448


class AsTupleNode(ExprNode):
    #  Convert argument to tuple. Used for normalising
    #  the * argument of a function call.
    #
    #  arg    ExprNode
    
    subexprs = ['arg']
    
2449 2450 2451 2452 2453 2454 2455
    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
2456 2457 2458
    def analyse_types(self, env):
        self.arg.analyse_types(env)
        self.arg = self.arg.coerce_to_pyobject(env)
2459
        self.type = tuple_type
2460
        self.gil_check(env)
William Stein's avatar
William Stein committed
2461
        self.is_temp = 1
2462 2463 2464

    gil_message = "Constructing Python tuple"

William Stein's avatar
William Stein committed
2465 2466
    def generate_result_code(self, code):
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
2467
            "%s = PySequence_Tuple(%s); %s" % (
2468
                self.result(),
William Stein's avatar
William Stein committed
2469
                self.arg.py_result(),
2470
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
2471 2472 2473 2474 2475 2476 2477
    

class AttributeNode(ExprNode):
    #  obj.attribute
    #
    #  obj          ExprNode
    #  attribute    string
2478
    #  needs_none_check boolean        Used if obj is an extension type.
2479
    #                                  If set to True, it is known that the type is not None.
William Stein's avatar
William Stein committed
2480 2481 2482 2483 2484 2485 2486
    #
    #  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
Stefan Behnel's avatar
Stefan Behnel committed
2487
    #  interned_attr_cname  string    C name of interned attribute name
William Stein's avatar
William Stein committed
2488 2489 2490 2491 2492 2493 2494
    
    is_attribute = 1
    subexprs = ['obj']
    
    type = PyrexTypes.error_type
    entry = None
    is_called = 0
2495
    needs_none_check = True
William Stein's avatar
William Stein committed
2496

2497
    def as_cython_attribute(self):
2498 2499 2500
        if isinstance(self.obj, NameNode) and self.obj.is_cython_module:
            return self.attribute

2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
    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
                self.analyse_as_python_attribute(env) 
                return self
2512
        return ExprNode.coerce_to(self, dst_type, env)
2513
    
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
    def compile_time_value(self, denv):
        attr = self.attribute
        if attr.beginswith("__") and attr.endswith("__"):
            self.error("Invalid attribute name '%s' in compile-time expression"
                % attr)
            return None
        obj = self.arg.compile_time_value(denv)
        try:
            return getattr(obj, attr)
        except Exception, e:
            self.compile_time_value_error(e)

William Stein's avatar
William Stein committed
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
    def analyse_target_declaration(self, env):
        pass
    
    def analyse_target_types(self, env):
        self.analyse_types(env, target = 1)
    
    def analyse_types(self, env, target = 0):
        if self.analyse_as_cimported_attribute(env, target):
            return
        if not target and self.analyse_as_unbound_cmethod(env):
            return
        self.analyse_as_ordinary_attribute(env, target)
    
    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)
                    return 1
        return 0
    
    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
2570
                ubcm_entry.is_unbound_cmethod = 1
William Stein's avatar
William Stein committed
2571 2572 2573
                self.mutate_into_name_node(env, ubcm_entry, None)
                return 1
        return 0
2574 2575 2576 2577
        
    def analyse_as_type(self, env):
        module_scope = self.obj.analyse_as_module(env)
        if module_scope:
2578
            return module_scope.lookup_type(self.attribute)
2579
        return None
William Stein's avatar
William Stein committed
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
    
    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
    
    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
                
    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:
2612
            NameNode.analyse_rvalue_entry(self, env)
William Stein's avatar
William Stein committed
2613 2614 2615 2616 2617
    
    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:
2618 2619
#            error(self.pos, "C method can only be called")
            pass
2620 2621 2622
        ## Reference to C array turns into pointer to first element.
        #while self.type.is_array:
        #	self.type = self.type.element_ptr_type()
William Stein's avatar
William Stein committed
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
        if self.is_py_attr:
            if not target:
                self.is_temp = 1
                self.result_ctype = py_object_type
    
    def analyse_attribute(self, env):
        # Look up attribute and set self.type and self.member.
        self.is_py_attr = 0
        self.member = self.attribute
        if self.obj.type.is_string:
            self.obj = self.obj.coerce_to_pyobject(env)
        obj_type = self.obj.type
2635
        if obj_type.is_ptr or obj_type.is_array:
William Stein's avatar
William Stein committed
2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
            obj_type = obj_type.base_type
            self.op = "->"
        elif obj_type.is_extension_type:
            self.op = "->"
        else:
            self.op = "."
        if obj_type.has_attributes:
            entry = None
            if obj_type.attributes_known():
                entry = obj_type.scope.lookup_here(self.attribute)
Robert Bradshaw's avatar
Robert Bradshaw committed
2646 2647
                if entry and entry.is_member:
                    entry = None
William Stein's avatar
William Stein committed
2648 2649 2650 2651
            else:
                error(self.pos, 
                    "Cannot select attribute of incomplete type '%s'" 
                    % obj_type)
Robert Bradshaw's avatar
Robert Bradshaw committed
2652 2653
                self.type = PyrexTypes.error_type
                return
William Stein's avatar
William Stein committed
2654 2655
            self.entry = entry
            if entry:
2656 2657
                if obj_type.is_extension_type and entry.name == "__weakref__":
                    error(self.pos, "Illegal use of special attribute __weakref__")
2658 2659
                # methods need the normal attribute lookup
                # because they do not have struct entries
2660 2661 2662 2663
                if entry.is_variable or entry.is_cmethod:
                    self.type = entry.type
                    self.member = entry.cname
                    return
William Stein's avatar
William Stein committed
2664 2665 2666 2667 2668 2669 2670 2671 2672
                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
        # If we get here, the base object is not a struct/union/extension 
        # 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.
2673 2674 2675 2676 2677
        self.analyse_as_python_attribute(env)
                    
    def analyse_as_python_attribute(self, env):
        obj_type = self.obj.type
        self.member = self.attribute
William Stein's avatar
William Stein committed
2678 2679 2680
        if obj_type.is_pyobject:
            self.type = py_object_type
            self.is_py_attr = 1
2681
            self.interned_attr_cname = env.intern_identifier(self.attribute)
2682
            self.gil_check(env)
William Stein's avatar
William Stein committed
2683 2684 2685 2686 2687
        else:
            if not obj_type.is_error:
                error(self.pos, 
                    "Object of type '%s' has no attribute '%s'" %
                    (obj_type, self.attribute))
2688 2689 2690

    gil_message = "Accessing Python attribute"

William Stein's avatar
William Stein committed
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710
    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:
            return 1
        else:
            return NameNode.is_lvalue(self)
    
    def is_ephemeral(self):
        if self.obj:
            return self.obj.is_ephemeral()
        else:
            return NameNode.is_ephemeral(self)
    
    def calculate_result_code(self):
        #print "AttributeNode.calculate_result_code:", self.member ###
2711
        #print "...obj node =", self.obj, "code", self.obj.result() ###
William Stein's avatar
William Stein committed
2712 2713 2714 2715 2716
        #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:
Robert Bradshaw's avatar
Robert Bradshaw committed
2717 2718 2719 2720 2721 2722
            if obj.type.is_extension_type:
                return "((struct %s *)%s%s%s)->%s" % (
                    obj.type.vtabstruct_cname, obj_code, self.op, 
                    obj.type.vtabslot_cname, self.member)
            else:
                return self.member
William Stein's avatar
William Stein committed
2723 2724 2725 2726 2727
        else:
            return "%s%s%s" % (obj_code, self.op, self.member)
    
    def generate_result_code(self, code):
        if self.is_py_attr:
2728 2729
            code.putln(
                '%s = PyObject_GetAttr(%s, %s); %s' % (
2730
                    self.result(),
2731 2732
                    self.obj.py_result(),
                    self.interned_attr_cname,
2733
                    code.error_goto_if_null(self.result(), self.pos)))
2734 2735 2736
        else:
            # result_code contains what is needed, but we may need to insert
            # a check and raise an exception
2737 2738 2739 2740
            if (self.obj.type.is_extension_type
                  and self.needs_none_check
                  and code.globalstate.directives['nonecheck']):
                self.put_nonecheck(code)
William Stein's avatar
William Stein committed
2741 2742 2743 2744
    
    def generate_assignment_code(self, rhs, code):
        self.obj.generate_evaluation_code(code)
        if self.is_py_attr:
2745 2746 2747 2748 2749
            code.put_error_if_neg(self.pos, 
                'PyObject_SetAttr(%s, %s, %s)' % (
                    self.obj.py_result(),
                    self.interned_attr_cname,
                    rhs.py_result()))
William Stein's avatar
William Stein committed
2750
            rhs.generate_disposal_code(code)
2751
            rhs.free_temps(code)
William Stein's avatar
William Stein committed
2752
        else:
2753 2754 2755 2756 2757
            if (self.obj.type.is_extension_type
                  and self.needs_none_check
                  and code.globalstate.directives['nonecheck']):
                self.put_nonecheck(code)

2758
            select_code = self.result()
William Stein's avatar
William Stein committed
2759 2760 2761 2762 2763 2764
            if self.type.is_pyobject:
                rhs.make_owned_reference(code)
                code.put_decref(select_code, self.ctype())
            code.putln(
                "%s = %s;" % (
                    select_code,
2765
                    rhs.result_as(self.ctype())))
2766
                    #rhs.result()))
William Stein's avatar
William Stein committed
2767
            rhs.generate_post_assignment_code(code)
2768
            rhs.free_temps(code)
William Stein's avatar
William Stein committed
2769
        self.obj.generate_disposal_code(code)
2770
        self.obj.free_temps(code)
William Stein's avatar
William Stein committed
2771 2772 2773 2774
    
    def generate_deletion_code(self, code):
        self.obj.generate_evaluation_code(code)
        if self.is_py_attr:
2775 2776 2777 2778
            code.put_error_if_neg(self.pos,
                'PyObject_DelAttr(%s, %s)' % (
                    self.obj.py_result(),
                    self.interned_attr_cname))
William Stein's avatar
William Stein committed
2779 2780 2781
        else:
            error(self.pos, "Cannot delete C attribute of extension type")
        self.obj.generate_disposal_code(code)
2782
        self.obj.free_temps(code)
2783 2784 2785 2786 2787 2788
        
    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
2789

2790 2791 2792 2793 2794 2795 2796 2797
    def put_nonecheck(self, code):
        code.globalstate.use_utility_code(raise_noneattr_error_utility_code)
        code.putln("if (%s) {" % code.unlikely("%s == Py_None") % self.obj.result_as(PyrexTypes.py_object_type))
        code.putln("__Pyx_RaiseNoneAttributeError(\"%s\");" % self.attribute.encode("UTF-8")) # todo: fix encoding
        code.putln(code.error_goto(self.pos))
        code.putln("}")


William Stein's avatar
William Stein committed
2798 2799 2800 2801 2802 2803
#-------------------------------------------------------------------
#
#  Constructor nodes
#
#-------------------------------------------------------------------

2804
class SequenceNode(NewTempExprNode):
William Stein's avatar
William Stein committed
2805 2806 2807 2808
    #  Base class for list and tuple constructor nodes.
    #  Contains common code for performing sequence unpacking.
    #
    #  args                    [ExprNode]
2809
    #  iterator                ExprNode
William Stein's avatar
William Stein committed
2810 2811 2812 2813 2814 2815 2816 2817
    #  unpacked_items          [ExprNode] or None
    #  coerced_unpacked_items  [ExprNode] or None
    
    subexprs = ['args']
    
    is_sequence_constructor = 1
    unpacked_items = None
    
2818 2819 2820
    def compile_time_value_list(self, denv):
        return [arg.compile_time_value(denv) for arg in self.args]

William Stein's avatar
William Stein committed
2821 2822 2823 2824
    def analyse_target_declaration(self, env):
        for arg in self.args:
            arg.analyse_target_declaration(env)

2825
    def analyse_types(self, env, skip_children=False):
William Stein's avatar
William Stein committed
2826 2827
        for i in range(len(self.args)):
            arg = self.args[i]
2828
            if not skip_children: arg.analyse_types(env)
William Stein's avatar
William Stein committed
2829 2830
            self.args[i] = arg.coerce_to_pyobject(env)
        self.type = py_object_type
2831
        self.gil_check(env)
William Stein's avatar
William Stein committed
2832
        self.is_temp = 1
2833

William Stein's avatar
William Stein committed
2834
    def analyse_target_types(self, env):
2835 2836
        self.iterator = PyTempNode(self.pos, env)
        self.unpacked_items = []
William Stein's avatar
William Stein committed
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
        self.coerced_unpacked_items = []
        for arg in self.args:
            arg.analyse_target_types(env)
            unpacked_item = PyTempNode(self.pos, env)
            coerced_unpacked_item = unpacked_item.coerce_to(arg.type, env)
            self.unpacked_items.append(unpacked_item)
            self.coerced_unpacked_items.append(coerced_unpacked_item)
        self.type = py_object_type
        env.use_utility_code(unpacking_utility_code)
    
2847 2848 2849
    def allocate_target_temps(self, env, rhs):
        self.iterator.allocate_temps(env)
        for arg, node in zip(self.args, self.coerced_unpacked_items):
William Stein's avatar
William Stein committed
2850
            node.allocate_temps(env)
2851
            arg.allocate_target_temps(env, None)
2852 2853
            #arg.release_target_temp(env)
            #node.release_temp(env)
2854 2855
        if rhs:
            rhs.release_temp(env)
2856
        self.iterator.release_temp(env)
2857 2858 2859
        for node in self.coerced_unpacked_items:
            node.release_temp(env)

2860 2861 2862 2863 2864 2865
#	def release_target_temp(self, env):
#		#for arg in self.args:
#		#	arg.release_target_temp(env)
#		#for node in self.coerced_unpacked_items:
#		#	node.release_temp(env)
#		self.iterator.release_temp(env)
William Stein's avatar
William Stein committed
2866 2867 2868 2869 2870
    
    def generate_result_code(self, code):
        self.generate_operation_code(code)
    
    def generate_assignment_code(self, rhs, code):
2871 2872 2873 2874
        # 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.

Robert Bradshaw's avatar
Robert Bradshaw committed
2875 2876 2877 2878 2879
        code.putln(
            "if (PyTuple_CheckExact(%s) && PyTuple_GET_SIZE(%s) == %s) {" % (
                rhs.py_result(), 
                rhs.py_result(), 
                len(self.args)))
Stefan Behnel's avatar
Stefan Behnel committed
2880
        code.putln("PyObject* tuple = %s;" % rhs.py_result())
Robert Bradshaw's avatar
Robert Bradshaw committed
2881 2882
        for i in range(len(self.args)):
            item = self.unpacked_items[i]
2883 2884
            code.put(
                "%s = PyTuple_GET_ITEM(tuple, %s); " % (
2885
                    item.result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
2886
                    i))
2887
            code.put_incref(item.result(), item.ctype())
2888 2889
            value_node = self.coerced_unpacked_items[i]
            value_node.generate_evaluation_code(code)
2890
        rhs.generate_disposal_code(code)
2891

2892 2893 2894 2895
        for i in range(len(self.args)):
            self.args[i].generate_assignment_code(
                self.coerced_unpacked_items[i], code)
                 
2896
        code.putln("} else {")
Robert Bradshaw's avatar
Robert Bradshaw committed
2897

2898
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
2899
            "%s = PyObject_GetIter(%s); %s" % (
2900
                self.iterator.result(),
2901
                rhs.py_result(),
2902
                code.error_goto_if_null(self.iterator.result(), self.pos)))
2903
        rhs.generate_disposal_code(code)
William Stein's avatar
William Stein committed
2904 2905
        for i in range(len(self.args)):
            item = self.unpacked_items[i]
2906 2907
            unpack_code = "__Pyx_UnpackItem(%s, %d)" % (
                self.iterator.py_result(), i)
William Stein's avatar
William Stein committed
2908
            code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
2909
                "%s = %s; %s" % (
2910
                    item.result(),
William Stein's avatar
William Stein committed
2911
                    typecast(item.ctype(), py_object_type, unpack_code),
2912
                    code.error_goto_if_null(item.result(), self.pos)))
2913 2914
            value_node = self.coerced_unpacked_items[i]
            value_node.generate_evaluation_code(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
2915 2916 2917
        code.put_error_if_neg(self.pos, 
            "__Pyx_EndUnpack(%s)" % (
                self.iterator.py_result()))
William Stein's avatar
William Stein committed
2918
        if debug_disposal_code:
Stefan Behnel's avatar
Stefan Behnel committed
2919
            print("UnpackNode.generate_assignment_code:")
2920
            print("...generating disposal code for %s" % self.iterator)
2921
        self.iterator.generate_disposal_code(code)
2922
        self.iterator.free_temps(code)
William Stein's avatar
William Stein committed
2923

2924
        for i in range(len(self.args)):
2925 2926
            self.args[i].generate_assignment_code(
                self.coerced_unpacked_items[i], code)
2927 2928
        code.putln("}")
        rhs.free_temps(code)
2929 2930 2931 2932 2933 2934 2935 2936 2937
        
    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
2938 2939 2940 2941


class TupleNode(SequenceNode):
    #  Tuple constructor.
2942 2943 2944

    gil_message = "Constructing Python tuple"

2945
    def analyse_types(self, env, skip_children=False):
Robert Bradshaw's avatar
Robert Bradshaw committed
2946 2947
        if len(self.args) == 0:
            self.is_temp = 0
2948
            self.is_literal = 1
Robert Bradshaw's avatar
Robert Bradshaw committed
2949
        else:
2950
            SequenceNode.analyse_types(self, env, skip_children)
Robert Bradshaw's avatar
Robert Bradshaw committed
2951
        self.type = tuple_type
Robert Bradshaw's avatar
Robert Bradshaw committed
2952 2953 2954
            
    def calculate_result_code(self):
        if len(self.args) > 0:
2955
            error(self.pos, "Positive length tuples must be constructed.")
Robert Bradshaw's avatar
Robert Bradshaw committed
2956 2957
        else:
            return Naming.empty_tuple
William Stein's avatar
William Stein committed
2958

2959 2960 2961 2962 2963 2964 2965
    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)
    
William Stein's avatar
William Stein committed
2966
    def generate_operation_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
2967 2968 2969
        if len(self.args) == 0:
            # result_code is Naming.empty_tuple
            return
William Stein's avatar
William Stein committed
2970
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
2971
            "%s = PyTuple_New(%s); %s" % (
2972
                self.result(),
William Stein's avatar
William Stein committed
2973
                len(self.args),
2974
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
2975 2976 2977
        for i in range(len(self.args)):
            arg = self.args[i]
            if not arg.result_in_temp():
2978
                code.put_incref(arg.result(), arg.ctype())
William Stein's avatar
William Stein committed
2979 2980
            code.putln(
                "PyTuple_SET_ITEM(%s, %s, %s);" % (
2981
                    self.result(),
William Stein's avatar
William Stein committed
2982 2983 2984 2985 2986 2987 2988 2989
                    i,
                    arg.py_result()))
    
    def generate_subexpr_disposal_code(self, code):
        # 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:
2990 2991 2992
            arg.generate_post_assignment_code(code)
            # Should NOT call free_temps -- this is invoked by the default
            # generate_evaluation_code which will do that.
William Stein's avatar
William Stein committed
2993 2994 2995 2996


class ListNode(SequenceNode):
    #  List constructor.
2997 2998 2999
    
    # obj_conversion_errors    [PyrexError]   used internally
    # orignial_args            [ExprNode]     used internally
3000 3001 3002

    gil_message = "Constructing Python list"

3003 3004 3005 3006
    def analyse_expressions(self, env):
        ExprNode.analyse_expressions(self, env)
        self.coerce_to_pyobject(env)

Robert Bradshaw's avatar
Robert Bradshaw committed
3007
    def analyse_types(self, env):
3008 3009 3010 3011 3012 3013
        hold_errors()
        self.original_args = list(self.args)
        SequenceNode.analyse_types(self, env)
        self.type = list_type
        self.obj_conversion_errors = held_errors()
        release_errors(ignore=True)
Robert Bradshaw's avatar
Robert Bradshaw committed
3014 3015 3016
        
    def coerce_to(self, dst_type, env):
        if dst_type.is_pyobject:
3017 3018 3019
            for err in self.obj_conversion_errors:
                report_error(err)
            self.obj_conversion_errors = []
Robert Bradshaw's avatar
Robert Bradshaw committed
3020 3021 3022 3023
            if not self.type.subtype_of(dst_type):
                error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
        elif dst_type.is_ptr:
            base_type = dst_type.base_type
Robert Bradshaw's avatar
Robert Bradshaw committed
3024
            self.type = PyrexTypes.CArrayType(base_type, len(self.args))
3025
            for i in range(len(self.original_args)):
Robert Bradshaw's avatar
Robert Bradshaw committed
3026
                arg = self.args[i]
3027 3028
                if isinstance(arg, CoerceToPyTypeNode):
                    arg = arg.arg
Robert Bradshaw's avatar
Robert Bradshaw committed
3029
                self.args[i] = arg.coerce_to(base_type, env)
Robert Bradshaw's avatar
Robert Bradshaw committed
3030 3031 3032 3033 3034 3035
        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)
3036 3037 3038
                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
3039 3040
                    self.args[i] = arg.coerce_to(member.type, env)
            self.type = dst_type
Robert Bradshaw's avatar
Robert Bradshaw committed
3041 3042 3043 3044
        else:
            self.type = error_type
            error(self.pos, "Cannot coerce list to type '%s'" % dst_type)
        return self
Robert Bradshaw's avatar
Robert Bradshaw committed
3045 3046 3047 3048 3049 3050 3051 3052
        
    def release_temp(self, env):
        if self.type.is_array:
            # To be valid C++, we must allocate the memory on the stack 
            # manually and be sure not to reuse it for something else. 
            pass
        else:
            SequenceNode.release_temp(self, env)
Robert Bradshaw's avatar
Robert Bradshaw committed
3053

3054 3055 3056
    def compile_time_value(self, denv):
        return self.compile_time_value_list(denv)

William Stein's avatar
William Stein committed
3057
    def generate_operation_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
3058
        if self.type.is_pyobject:
3059 3060
            for err in self.obj_conversion_errors:
                report_error(err)
Robert Bradshaw's avatar
Robert Bradshaw committed
3061
            code.putln("%s = PyList_New(%s); %s" %
3062
                (self.result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073
                len(self.args),
                code.error_goto_if_null(self.result(), self.pos)))
            for i in range(len(self.args)):
                arg = self.args[i]
                #if not arg.is_temp:
                if not arg.result_in_temp():
                    code.put_incref(arg.result(), arg.ctype())
                code.putln("PyList_SET_ITEM(%s, %s, %s);" %
                    (self.result(),
                    i,
                    arg.py_result()))
Robert Bradshaw's avatar
Robert Bradshaw committed
3074 3075 3076 3077 3078 3079
        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
3080
        elif self.type.is_struct:
Robert Bradshaw's avatar
Robert Bradshaw committed
3081 3082 3083 3084 3085
            for arg, member in zip(self.args, self.type.scope.var_entries):
                code.putln("%s.%s = %s;" % (
                        self.result(),
                        member.cname,
                        arg.result()))
3086 3087
        else:
            raise InternalError("List type never specified")
William Stein's avatar
William Stein committed
3088 3089 3090 3091 3092 3093
                
    def generate_subexpr_disposal_code(self, code):
        # We call generate_post_assignment_code here instead
        # of generate_disposal_code, because values were stored
        # in the list using a reference-stealing operation.
        for arg in self.args:
3094 3095 3096
            arg.generate_post_assignment_code(code)
            # Should NOT call free_temps -- this is invoked by the default
            # generate_evaluation_code which will do that.
William Stein's avatar
William Stein committed
3097

Robert Bradshaw's avatar
Robert Bradshaw committed
3098 3099 3100 3101
            
class ListComprehensionNode(SequenceNode):

    subexprs = []
3102
    is_sequence_constructor = 0 # not unpackable
Robert Bradshaw's avatar
Robert Bradshaw committed
3103

3104 3105
    child_attrs = ["loop", "append"]

Robert Bradshaw's avatar
Robert Bradshaw committed
3106
    def analyse_types(self, env): 
Robert Bradshaw's avatar
Robert Bradshaw committed
3107
        self.type = list_type
Robert Bradshaw's avatar
Robert Bradshaw committed
3108 3109 3110 3111 3112
        self.is_temp = 1
        self.append.target = self # this is a CloneNode used in the PyList_Append in the inner loop
        
    def allocate_temps(self, env, result = None): 
        if debug_temp_alloc:
Stefan Behnel's avatar
Stefan Behnel committed
3113
            print("%s Allocating temps" % self)
Robert Bradshaw's avatar
Robert Bradshaw committed
3114 3115 3116 3117 3118
        self.allocate_temp(env, result)
        self.loop.analyse_declarations(env)
        self.loop.analyse_expressions(env)
        
    def generate_operation_code(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
3119
        code.putln("%s = PyList_New(%s); %s" %
3120
            (self.result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
3121
            0,
3122
            code.error_goto_if_null(self.result(), self.pos)))
Robert Bradshaw's avatar
Robert Bradshaw committed
3123
        self.loop.generate_execution_code(code)
3124 3125 3126
        
    def annotate(self, code):
        self.loop.annotate(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
3127 3128 3129 3130


class ListComprehensionAppendNode(ExprNode):

3131 3132
    # Need to be careful to avoid infinite recursion:
    # target must not be in child_attrs/subexprs
Robert Bradshaw's avatar
Robert Bradshaw committed
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
    subexprs = ['expr']
    
    def analyse_types(self, env):
        self.expr.analyse_types(env)
        if self.expr.type != py_object_type:
            self.expr = self.expr.coerce_to_pyobject(env)
        self.type = PyrexTypes.c_int_type
        self.is_temp = 1
    
    def generate_result_code(self, code):
3143
        code.putln("%s = PyList_Append(%s, (PyObject*)%s); %s" %
3144 3145 3146 3147
            (self.result(),
            self.target.result(),
            self.expr.result(),
            code.error_goto_if(self.result(), self.pos)))
Robert Bradshaw's avatar
Robert Bradshaw committed
3148

William Stein's avatar
William Stein committed
3149 3150 3151 3152

class DictNode(ExprNode):
    #  Dictionary constructor.
    #
3153
    #  key_value_pairs  [DictItemNode]
3154 3155
    #
    # obj_conversion_errors    [PyrexError]   used internally
3156 3157
    
    subexprs = ['key_value_pairs']
William Stein's avatar
William Stein committed
3158
    
3159
    def compile_time_value(self, denv):
Robert Bradshaw's avatar
Robert Bradshaw committed
3160 3161
        pairs = [(item.key.compile_time_value(denv), item.value.compile_time_value(denv))
            for item in self.key_value_pairs]
3162 3163 3164 3165 3166
        try:
            return dict(pairs)
        except Exception, e:
            self.compile_time_value_error(e)
    
William Stein's avatar
William Stein committed
3167
    def analyse_types(self, env):
3168
        hold_errors()
Robert Bradshaw's avatar
Robert Bradshaw committed
3169
        self.type = dict_type
Robert Bradshaw's avatar
Robert Bradshaw committed
3170 3171
        for item in self.key_value_pairs:
            item.analyse_types(env)
3172
        self.gil_check(env)
3173 3174
        self.obj_conversion_errors = held_errors()
        release_errors(ignore=True)
William Stein's avatar
William Stein committed
3175
        self.is_temp = 1
3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190
        
    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
3191 3192 3193
                if not isinstance(item.key, (StringNode, IdentifierStringNode)):
                    error(item.key.pos, "Invalid struct field identifier")
                    item.key = IdentifierStringNode(item.key.pos, value="<error>")
3194
                else:
3195
                    member = dst_type.scope.lookup_here(item.key.value)
3196
                    if not member:
3197
                        error(item.key.pos, "struct '%s' has no field '%s'" % (dst_type, item.key.value))
3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211
                    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
    
    def release_errors(self):
        for err in self.obj_conversion_errors:
            report_error(err)
        self.obj_conversion_errors = []
3212 3213 3214

    gil_message = "Constructing Python dict"

William Stein's avatar
William Stein committed
3215 3216 3217 3218
    def allocate_temps(self, env, result = None):
        #  Custom method used here because key-value
        #  pairs are evaluated and used one at a time.
        self.allocate_temp(env, result)
Robert Bradshaw's avatar
Robert Bradshaw committed
3219 3220 3221 3222 3223
        for item in self.key_value_pairs:
            item.key.allocate_temps(env)
            item.value.allocate_temps(env)
            item.key.release_temp(env)
            item.value.release_temp(env)
William Stein's avatar
William Stein committed
3224 3225 3226 3227
    
    def generate_evaluation_code(self, code):
        #  Custom method used here because key-value
        #  pairs are evaluated and used one at a time.
3228 3229 3230 3231 3232 3233
        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)))
Robert Bradshaw's avatar
Robert Bradshaw committed
3234 3235
        for item in self.key_value_pairs:
            item.generate_evaluation_code(code)
3236 3237 3238 3239 3240 3241 3242 3243 3244
            if self.type.is_pyobject:
                code.put_error_if_neg(self.pos, 
                    "PyDict_SetItem(%s, %s, %s)" % (
                        self.result(),
                        item.key.py_result(),
                        item.value.py_result()))
            else:
                code.putln("%s.%s = %s;" % (
                        self.result(),
3245
                        item.key.value,
3246
                        item.value.result()))
Robert Bradshaw's avatar
Robert Bradshaw committed
3247
            item.generate_disposal_code(code)
3248
            item.free_temps(code)
3249 3250
            
    def annotate(self, code):
Robert Bradshaw's avatar
Robert Bradshaw committed
3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269
        for item in self.key_value_pairs:
            item.annotate(code)
            
class DictItemNode(ExprNode):
    # Represents a single item in a DictNode
    #
    # key          ExprNode
    # value        ExprNode
    subexprs = ['key', 'value']
            
    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)
        
    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
3270

3271 3272 3273
    def generate_disposal_code(self, code):
        self.key.generate_disposal_code(code)
        self.value.generate_disposal_code(code)
3274 3275 3276 3277

    def free_temps(self, code):
        self.key.free_temps(code)
        self.value.free_temps(code)
3278 3279 3280
        
    def __iter__(self):
        return iter([self.key, self.value])
William Stein's avatar
William Stein committed
3281

Stefan Behnel's avatar
Stefan Behnel committed
3282

William Stein's avatar
William Stein committed
3283 3284 3285 3286 3287
class ClassNode(ExprNode):
    #  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
3288 3289
    #  name         EncodedString      Name of the class
    #  cname        string             Class name as a Python string
William Stein's avatar
William Stein committed
3290 3291 3292 3293 3294
    #  bases        ExprNode           Base class tuple
    #  dict         ExprNode           Class dict (not owned by this node)
    #  doc          ExprNode or None   Doc string
    #  module_name  string             Name of defining module
    
3295 3296
    subexprs = ['bases', 'doc']

William Stein's avatar
William Stein committed
3297
    def analyse_types(self, env):
3298
        self.cname = env.intern_identifier(self.name)
William Stein's avatar
William Stein committed
3299 3300 3301 3302 3303 3304
        self.bases.analyse_types(env)
        if self.doc:
            self.doc.analyse_types(env)
            self.doc = self.doc.coerce_to_pyobject(env)
        self.module_name = env.global_scope().qualified_name
        self.type = py_object_type
3305
        self.gil_check(env)
William Stein's avatar
William Stein committed
3306 3307
        self.is_temp = 1
        env.use_utility_code(create_class_utility_code);
3308

3309 3310
    gil_message = "Constructing Python class"

William Stein's avatar
William Stein committed
3311 3312
    def generate_result_code(self, code):
        if self.doc:
Robert Bradshaw's avatar
Robert Bradshaw committed
3313 3314
            code.put_error_if_neg(self.pos, 
                'PyDict_SetItemString(%s, "__doc__", %s)' % (
William Stein's avatar
William Stein committed
3315
                    self.dict.py_result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
3316
                    self.doc.py_result()))
William Stein's avatar
William Stein committed
3317
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
3318
            '%s = __Pyx_CreateClass(%s, %s, %s, "%s"); %s' % (
3319
                self.result(),
William Stein's avatar
William Stein committed
3320 3321
                self.bases.py_result(),
                self.dict.py_result(),
3322
                self.cname,
William Stein's avatar
William Stein committed
3323
                self.module_name,
3324
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339


class UnboundMethodNode(ExprNode):
    #  Helper class used in the implementation of Python
    #  class definitions. Constructs an unbound method
    #  object from a class and a function.
    #
    #  class_cname   string     C var holding the class object
    #  function      ExprNode   Function object
    
    subexprs = ['function']
    
    def analyse_types(self, env):
        self.function.analyse_types(env)
        self.type = py_object_type
3340
        self.gil_check(env)
William Stein's avatar
William Stein committed
3341
        self.is_temp = 1
3342 3343 3344

    gil_message = "Constructing an unbound method"

William Stein's avatar
William Stein committed
3345 3346
    def generate_result_code(self, code):
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
3347
            "%s = PyMethod_New(%s, 0, %s); %s" % (
3348
                self.result(),
William Stein's avatar
William Stein committed
3349 3350
                self.function.py_result(),
                self.class_cname,
3351
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
3352 3353


3354
class PyCFunctionNode(AtomicNewTempExprNode):
William Stein's avatar
William Stein committed
3355 3356 3357 3358 3359 3360 3361 3362
    #  Helper class used in the implementation of Python
    #  class definitions. Constructs a PyCFunction object
    #  from a PyMethodDef struct.
    #
    #  pymethdef_cname   string   PyMethodDef structure
    
    def analyse_types(self, env):
        self.type = py_object_type
3363
        self.gil_check(env)
William Stein's avatar
William Stein committed
3364
        self.is_temp = 1
3365 3366 3367

    gil_message = "Constructing Python function"

William Stein's avatar
William Stein committed
3368 3369
    def generate_result_code(self, code):
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
3370
            "%s = PyCFunction_New(&%s, 0); %s" % (
3371
                self.result(),
William Stein's avatar
William Stein committed
3372
                self.pymethdef_cname,
3373
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
3374 3375 3376 3377 3378 3379 3380

#-------------------------------------------------------------------
#
#  Unary operator nodes
#
#-------------------------------------------------------------------

3381 3382 3383 3384 3385 3386 3387
compile_time_unary_operators = {
    'not': operator.not_,
    '~': operator.inv,
    '-': operator.neg,
    '+': operator.pos,
}

William Stein's avatar
William Stein committed
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401
class UnopNode(ExprNode):
    #  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.
    
    subexprs = ['operand']
    
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
    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)

William Stein's avatar
William Stein committed
3414 3415 3416 3417 3418
    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
3419
            self.gil_check(env)
William Stein's avatar
William Stein committed
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442
            self.is_temp = 1
        else:
            self.analyse_c_operation(env)
    
    def check_const(self):
        self.operand.check_const()
    
    def is_py_operation(self):
        return self.operand.type.is_pyobject
    
    def coerce_operand_to_pyobject(self, env):
        self.operand = self.operand.coerce_to_pyobject(env)
    
    def generate_result_code(self, code):
        if self.operand.type.is_pyobject:
            self.generate_py_operation_code(code)
        else:
            if self.is_temp:
                self.generate_c_operation_code(code)
    
    def generate_py_operation_code(self, code):
        function = self.py_operation_function()
        code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
3443
            "%s = %s(%s); %s" % (
3444
                self.result(), 
William Stein's avatar
William Stein committed
3445 3446
                function, 
                self.operand.py_result(),
3447
                code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460
        
    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


class NotNode(ExprNode):
    #  'not' operator
    #
    #  operand   ExprNode
    
3461 3462 3463 3464 3465 3466 3467
    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)

William Stein's avatar
William Stein committed
3468 3469 3470 3471 3472
    subexprs = ['operand']
    
    def analyse_types(self, env):
        self.operand.analyse_types(env)
        self.operand = self.operand.coerce_to_boolean(env)
3473
        self.type = PyrexTypes.c_bint_type
William Stein's avatar
William Stein committed
3474 3475
    
    def calculate_result_code(self):
3476
        return "(!%s)" % self.operand.result()
William Stein's avatar
William Stein committed
3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493
    
    def generate_result_code(self, code):
        pass


class UnaryPlusNode(UnopNode):
    #  unary '+' operator
    
    operator = '+'
    
    def analyse_c_operation(self, env):
        self.type = self.operand.type
    
    def py_operation_function(self):
        return "PyNumber_Positive"
    
    def calculate_result_code(self):
3494
        return self.operand.result()
William Stein's avatar
William Stein committed
3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511


class UnaryMinusNode(UnopNode):
    #  unary '-' operator
    
    operator = '-'
    
    def analyse_c_operation(self, env):
        if self.operand.type.is_numeric:
            self.type = self.operand.type
        else:
            self.type_error()
    
    def py_operation_function(self):
        return "PyNumber_Negative"
    
    def calculate_result_code(self):
3512
        return "(-%s)" % self.operand.result()
William Stein's avatar
William Stein committed
3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527


class TildeNode(UnopNode):
    #  unary '~' operator

    def analyse_c_operation(self, env):
        if self.operand.type.is_int:
            self.type = self.operand.type
        else:
            self.type_error()

    def py_operation_function(self):
        return "PyNumber_Invert"
    
    def calculate_result_code(self):
3528
        return "(~%s)" % self.operand.result()
William Stein's avatar
William Stein committed
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557


class AmpersandNode(ExprNode):
    #  The C address-of operator.
    #
    #  operand  ExprNode
    
    subexprs = ['operand']

    def analyse_types(self, env):
        self.operand.analyse_types(env)
        argtype = self.operand.type
        if not (argtype.is_cfunction or self.operand.is_lvalue()):
            self.error("Taking address of non-lvalue")
            return
        if argtype.is_pyobject:
            self.error("Cannot take address of Python variable")
            return
        self.type = PyrexTypes.c_ptr_type(argtype)
    
    def check_const(self):
        self.operand.check_const_addr()
    
    def error(self, mess):
        error(self.pos, mess)
        self.type = PyrexTypes.error_type
        self.result_code = "<error>"
    
    def calculate_result_code(self):
3558
        return "(&%s)" % self.operand.result()
William Stein's avatar
William Stein committed
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572

    def generate_result_code(self, code):
        pass
    

unop_node_classes = {
    "+":  UnaryPlusNode,
    "-":  UnaryMinusNode,
    "~":  TildeNode,
}

def unop_node(pos, operator, operand):
    # Construct unnop node of appropriate class for 
    # given operator.
3573
    if isinstance(operand, IntNode) and operator == '-':
3574
        return IntNode(pos = operand.pos, value = str(-int(operand.value, 0)))
Robert Bradshaw's avatar
Robert Bradshaw committed
3575 3576
    elif isinstance(operand, UnopNode) and operand.operator == operator:
        warning(pos, "Python has no increment/decrement operator: %s%sx = %s(%sx) = x" % ((operator,)*4), 5)
William Stein's avatar
William Stein committed
3577 3578 3579 3580 3581 3582 3583 3584
    return unop_node_classes[operator](pos, 
        operator = operator, 
        operand = operand)


class TypecastNode(ExprNode):
    #  C type cast
    #
3585
    #  operand      ExprNode
William Stein's avatar
William Stein committed
3586 3587
    #  base_type    CBaseTypeNode
    #  declarator   CDeclaratorNode
3588 3589 3590
    #
    #  If used from a transform, one can if wanted specify the attribute
    #  "type" directly and leave base_type and declarator to None
William Stein's avatar
William Stein committed
3591 3592
    
    subexprs = ['operand']
3593
    base_type = declarator = type = None
William Stein's avatar
William Stein committed
3594 3595
    
    def analyse_types(self, env):
3596 3597 3598
        if self.type is None:
            base_type = self.base_type.analyse(env)
            _, self.type = self.declarator.analyse(base_type, env)
3599 3600 3601 3602
        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
3603 3604 3605
        self.operand.analyse_types(env)
        to_py = self.type.is_pyobject
        from_py = self.operand.type.is_pyobject
3606 3607
        if from_py and not to_py and self.operand.is_ephemeral() and not self.type.is_numeric:
            error(self.pos, "Casting temporary Python object to non-numeric non-Python type")
William Stein's avatar
William Stein committed
3608
        if to_py and not from_py:
Robert Bradshaw's avatar
Robert Bradshaw committed
3609 3610
            if (self.operand.type.to_py_function and
                    self.operand.type.create_convert_utility_code(env)):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
3611
                self.result_ctype = py_object_type
3612
                self.operand = self.operand.coerce_to_pyobject(env)
3613 3614
            else:
                warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.operand.type, self.type))
3615
                self.operand = self.operand.coerce_to_simple(env)
3616 3617 3618
        elif from_py and not to_py:
            if self.type.from_py_function:
                self.operand = self.operand.coerce_to(self.type, env)
3619 3620
            else:
                warning(self.pos, "No conversion from %s to %s, python object pointer used." % (self.type, self.operand.type))
3621 3622 3623
        elif from_py and to_py:
            if self.typecheck and self.type.is_extension_type:
                self.operand = PyTypeTestNode(self.operand, self.type, env)
William Stein's avatar
William Stein committed
3624 3625 3626 3627 3628 3629
    
    def check_const(self):
        self.operand.check_const()
    
    def calculate_result_code(self):
        opnd = self.operand
3630
        return self.type.cast_code(opnd.result())
William Stein's avatar
William Stein committed
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
    
    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;" % (
3643 3644 3645
                    self.result(),
                    self.operand.result()))
            code.put_incref(self.result(), self.ctype())
William Stein's avatar
William Stein committed
3646 3647 3648 3649


class SizeofNode(ExprNode):
    #  Abstract base class for sizeof(x) expression nodes.
3650 3651
    
    type = PyrexTypes.c_int_type
William Stein's avatar
William Stein committed
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666

    def check_const(self):
        pass

    def generate_result_code(self, code):
        pass


class SizeofTypeNode(SizeofNode):
    #  C sizeof function applied to a type
    #
    #  base_type   CBaseTypeNode
    #  declarator  CDeclaratorNode
    
    subexprs = []
3667
    arg_type = None
William Stein's avatar
William Stein committed
3668 3669
    
    def analyse_types(self, env):
3670 3671
        # 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
3672
        if 0 and self.base_type.module_path:
3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
            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
3684 3685 3686 3687
        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
3688 3689 3690 3691
        self.check_type()
        
    def check_type(self):
        arg_type = self.arg_type
3692
        if arg_type.is_pyobject and not arg_type.is_extension_type:
William Stein's avatar
William Stein committed
3693 3694 3695 3696 3697 3698 3699
            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)
        
    def calculate_result_code(self):
3700 3701 3702 3703 3704 3705
        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
3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
        return "(sizeof(%s))" % arg_code
    

class SizeofVarNode(SizeofNode):
    #  C sizeof function applied to a variable
    #
    #  operand   ExprNode
    
    subexprs = ['operand']
    
    def analyse_types(self, env):
3717 3718 3719 3720 3721 3722 3723 3724 3725
        # 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
            self.__class__ = SizeofTypeNode
            self.check_type()
        else:
            self.operand.analyse_types(env)
William Stein's avatar
William Stein committed
3726 3727
    
    def calculate_result_code(self):
3728
        return "(sizeof(%s))" % self.operand.result()
William Stein's avatar
William Stein committed
3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739
    
    def generate_result_code(self, code):
        pass


#-------------------------------------------------------------------
#
#  Binary operator nodes
#
#-------------------------------------------------------------------

Stefan Behnel's avatar
Stefan Behnel committed
3740 3741 3742
def _not_in(x, seq):
    return x not in seq

3743 3744 3745
compile_time_binary_operators = {
    '<': operator.lt,
    '<=': operator.le,
3746
    '==': operator.eq,
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
    '!=': operator.ne,
    '>=': operator.ge,
    '>': operator.gt,
    'is': operator.is_,
    'is_not': operator.is_not,
    '+': operator.add,
    '&': operator.and_,
    '/': operator.div,
    '//': operator.floordiv,
    '<<': operator.lshift,
    '%': operator.mod,
    '*': operator.mul,
    '|': operator.or_,
    '**': operator.pow,
    '>>': operator.rshift,
    '-': operator.sub,
    #'/': operator.truediv,
    '^': operator.xor,
Stefan Behnel's avatar
Stefan Behnel committed
3765 3766
    'in': operator.contains,
    'not_in': _not_in,
3767 3768 3769 3770 3771 3772 3773
}

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"
3774
                % node.operator)
3775 3776
    return func

3777
class BinopNode(NewTempExprNode):
William Stein's avatar
William Stein committed
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791
    #  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.
    
    subexprs = ['operand1', 'operand2']
    
3792 3793 3794 3795 3796 3797 3798 3799 3800
    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)

William Stein's avatar
William Stein committed
3801 3802 3803 3804 3805 3806
    def analyse_types(self, env):
        self.operand1.analyse_types(env)
        self.operand2.analyse_types(env)
        if self.is_py_operation():
            self.coerce_operands_to_pyobjects(env)
            self.type = py_object_type
3807
            self.gil_check(env)
William Stein's avatar
William Stein committed
3808
            self.is_temp = 1
3809 3810
            if Options.incref_local_binop and self.operand1.type.is_pyobject:
                self.operand1 = self.operand1.coerce_to_temp(env)
William Stein's avatar
William Stein committed
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834
        else:
            self.analyse_c_operation(env)
    
    def is_py_operation(self):
        return (self.operand1.type.is_pyobject 
            or self.operand2.type.is_pyobject)
    
    def coerce_operands_to_pyobjects(self, env):
        self.operand1 = self.operand1.coerce_to_pyobject(env)
        self.operand2 = self.operand2.coerce_to_pyobject(env)
    
    def check_const(self):
        self.operand1.check_const()
        self.operand2.check_const()
    
    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()
            if function == "PyNumber_Power":
                extra_args = ", Py_None"
            else:
                extra_args = ""
            code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
3835
                "%s = %s(%s, %s%s); %s" % (
3836
                    self.result(), 
William Stein's avatar
William Stein committed
3837 3838 3839 3840
                    function, 
                    self.operand1.py_result(),
                    self.operand2.py_result(),
                    extra_args,
3841
                    code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
        else:
            if self.is_temp:
                self.generate_c_operation_code(code)
    
    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)" %
                (self.operator, self.operand1.type, 
                    self.operand2.type))
        self.type = PyrexTypes.error_type


class NumBinopNode(BinopNode):
    #  Binary operation taking numeric arguments.
    
    def analyse_c_operation(self, env):
        type1 = self.operand1.type
        type2 = self.operand2.type
3861 3862 3863 3864
        if self.operator == "**" and type1.is_int and type2.is_int:
            error(self.pos, "** with two C int types is ambiguous")
            self.type = error_type
            return
William Stein's avatar
William Stein committed
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875
        self.type = self.compute_c_result_type(type1, type2)
        if not self.type:
            self.type_error()
    
    def compute_c_result_type(self, type1, type2):
        if self.c_types_okay(type1, type2):
            return PyrexTypes.widest_numeric_type(type1, type2)
        else:
            return None
    
    def c_types_okay(self, type1, type2):
3876 3877 3878
        #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
3879 3880 3881

    def calculate_result_code(self):
        return "(%s %s %s)" % (
3882
            self.operand1.result(), 
William Stein's avatar
William Stein committed
3883
            self.operator, 
3884
            self.operand2.result())
William Stein's avatar
William Stein committed
3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897
    
    def py_operation_function(self):
        return self.py_functions[self.operator]

    py_functions = {
        "|":		"PyNumber_Or",
        "^":		"PyNumber_Xor",
        "&":		"PyNumber_And",
        "<<":		"PyNumber_Lshift",
        ">>":		"PyNumber_Rshift",
        "+":		"PyNumber_Add",
        "-":		"PyNumber_Subtract",
        "*":		"PyNumber_Multiply",
Robert Bradshaw's avatar
Robert Bradshaw committed
3898
        "/":		"__Pyx_PyNumber_Divide",
Robert Bradshaw's avatar
Robert Bradshaw committed
3899
        "//":		"PyNumber_FloorDivide",
William Stein's avatar
William Stein committed
3900
        "%":		"PyNumber_Remainder",
3901
        "**":       "PyNumber_Power"
William Stein's avatar
William Stein committed
3902 3903 3904 3905 3906 3907 3908
    }


class IntBinopNode(NumBinopNode):
    #  Binary operation taking integer arguments.
    
    def c_types_okay(self, type1, type2):
3909 3910 3911
        #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
3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924

    
class AddNode(NumBinopNode):
    #  '+' operator.
    
    def is_py_operation(self):
        if self.operand1.type.is_string \
            and self.operand2.type.is_string:
                return 1
        else:
            return NumBinopNode.is_py_operation(self)

    def compute_c_result_type(self, type1, type2):
3925 3926
        #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
3927
            return type1
3928
        elif (type2.is_ptr or type2.is_array) and (type1.is_int or type1.is_enum):
William Stein's avatar
William Stein committed
3929 3930 3931 3932 3933 3934 3935 3936 3937 3938
            return type2
        else:
            return NumBinopNode.compute_c_result_type(
                self, type1, type2)


class SubNode(NumBinopNode):
    #  '-' operator.
    
    def compute_c_result_type(self, type1, type2):
3939
        if (type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum):
William Stein's avatar
William Stein committed
3940
            return type1
3941
        elif (type1.is_ptr or type1.is_array) and (type2.is_ptr or type2.is_array):
William Stein's avatar
William Stein committed
3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960
            return PyrexTypes.c_int_type
        else:
            return NumBinopNode.compute_c_result_type(
                self, type1, type2)


class MulNode(NumBinopNode):
    #  '*' operator.
    
    def is_py_operation(self):
        type1 = self.operand1.type
        type2 = self.operand2.type
        if (type1.is_string and type2.is_int) \
            or (type2.is_string and type1.is_int):
                return 1
        else:
            return NumBinopNode.is_py_operation(self)


Robert Bradshaw's avatar
Robert Bradshaw committed
3961 3962 3963 3964 3965
class FloorDivNode(NumBinopNode):
    #  '//' operator.
    
    def calculate_result_code(self):
        return "(%s %s %s)" % (
3966
            self.operand1.result(), 
Robert Bradshaw's avatar
Robert Bradshaw committed
3967
            "/",  # c division is by default floor-div 
3968
            self.operand2.result())
Robert Bradshaw's avatar
Robert Bradshaw committed
3969 3970


Robert Bradshaw's avatar
Robert Bradshaw committed
3971
class ModNode(NumBinopNode):
William Stein's avatar
William Stein committed
3972 3973 3974 3975 3976
    #  '%' operator.
    
    def is_py_operation(self):
        return (self.operand1.type.is_string
            or self.operand2.type.is_string
Robert Bradshaw's avatar
Robert Bradshaw committed
3977
            or NumBinopNode.is_py_operation(self))
William Stein's avatar
William Stein committed
3978

Robert Bradshaw's avatar
Robert Bradshaw committed
3979 3980 3981 3982 3983 3984 3985 3986 3987
    def calculate_result_code(self):
        if self.operand1.type.is_float or self.operand2.type.is_float:
            return "fmod(%s, %s)" % (
                self.operand1.result(), 
                self.operand2.result())
        else:
            return "(%s %% %s)" % (
                self.operand1.result(), 
                self.operand2.result())
William Stein's avatar
William Stein committed
3988 3989 3990

class PowNode(NumBinopNode):
    #  '**' operator.
3991

William Stein's avatar
William Stein committed
3992 3993 3994 3995 3996
    def compute_c_result_type(self, type1, type2):
        if self.c_types_okay(type1, type2):
            return PyrexTypes.c_double_type
        else:
            return None
3997

3998
    def c_types_okay(self, type1, type2):
3999 4000
        return (type1.is_float or type2.is_float) and \
                NumBinopNode.c_types_okay(self, type1, type2)
4001

4002 4003 4004 4005 4006 4007 4008 4009
    def type_error(self):
        if not (self.operand1.type.is_error or self.operand2.type.is_error):
            if self.operand1.type.is_int and self.operand2.type.is_int:
                error(self.pos, "C has no integer powering, use python ints or floats instead '%s' (%s; %s)" %
                    (self.operator, self.operand1.type, self.operand2.type))
            else:
                NumBinopNode.type_error(self)
        self.type = PyrexTypes.error_type
4010

William Stein's avatar
William Stein committed
4011 4012
    def calculate_result_code(self):
        return "pow(%s, %s)" % (
4013
            self.operand1.result(), self.operand2.result())
4014

William Stein's avatar
William Stein committed
4015

4016 4017 4018 4019 4020 4021 4022 4023
# Note: This class is temporary "shut down" into an ineffective mode temp
# allocation mode.
#
# 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).
class BoolBinopNode(NewTempExprNode):
William Stein's avatar
William Stein committed
4024 4025 4026 4027 4028 4029
    #  Short-circuiting boolean operation.
    #
    #  operator     string
    #  operand1     ExprNode
    #  operand2     ExprNode
    
4030
    subexprs = ['operand1', 'operand2']
William Stein's avatar
William Stein committed
4031
    
4032 4033 4034 4035 4036 4037 4038
    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)
4039 4040 4041 4042 4043 4044
    
    def coerce_to_boolean(self, env):
        self.operand1 = self.operand1.coerce_to_boolean(env)
        self.operand2 = self.operand2.coerce_to_boolean(env)
        self.type = PyrexTypes.c_bint_type
        return self
4045

William Stein's avatar
William Stein committed
4046 4047 4048 4049 4050 4051 4052 4053
    def analyse_types(self, env):
        self.operand1.analyse_types(env)
        self.operand2.analyse_types(env)
        if self.operand1.type.is_pyobject or \
                self.operand2.type.is_pyobject:
            self.operand1 = self.operand1.coerce_to_pyobject(env)
            self.operand2 = self.operand2.coerce_to_pyobject(env)
            self.type = py_object_type
4054
            self.gil_check(env)
William Stein's avatar
William Stein committed
4055 4056 4057
        else:
            self.operand1 = self.operand1.coerce_to_boolean(env)
            self.operand2 = self.operand2.coerce_to_boolean(env)
4058
            self.type = PyrexTypes.c_bint_type
4059 4060 4061

        # Below disabled for 
        
William Stein's avatar
William Stein committed
4062 4063
        # For what we're about to do, it's vital that
        # both operands be temp nodes.
4064 4065
#        self.operand1 = self.operand1.coerce_to_temp(env) #CTT
#        self.operand2 = self.operand2.coerce_to_temp(env)
William Stein's avatar
William Stein committed
4066
        self.is_temp = 1
4067 4068 4069

    gil_message = "Truth-testing Python object"

4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087
##     def allocate_temps(self, env, result_code = None):
##         #  We don't need both operands at the same time, and
##         #  one of the operands will also be our result. So we
##         #  use an allocation strategy here which results in
##         #  this node and both its operands sharing the same
##         #  result variable. This allows us to avoid some 
##         #  assignments and increfs/decrefs that would otherwise
##         #  be necessary.
##         self.allocate_temp(env, result_code)
##         self.operand1.allocate_temps(env, self.result())
##         self.operand2.allocate_temps(env, self.result())
##         #  We haven't called release_temp on either operand,
##         #  because although they are temp nodes, they don't own 
##         #  their result variable. And because they are temp
##         #  nodes, any temps in their subnodes will have been
##         #  released before their allocate_temps returned.
##         #  Therefore, they contain no temp vars that need to
##         #  be released.
William Stein's avatar
William Stein committed
4088 4089 4090 4091 4092 4093 4094

    def check_const(self):
        self.operand1.check_const()
        self.operand2.check_const()
    
    def calculate_result_code(self):
        return "(%s %s %s)" % (
4095
            self.operand1.result(),
William Stein's avatar
William Stein committed
4096
            self.py_to_c_op[self.operator],
4097
            self.operand2.result())
William Stein's avatar
William Stein committed
4098 4099 4100 4101
    
    py_to_c_op = {'and': "&&", 'or': "||"}

    def generate_evaluation_code(self, code):
4102
        code.mark_pos(self.pos)
William Stein's avatar
William Stein committed
4103
        self.operand1.generate_evaluation_code(code)
4104
        test_result, uses_temp = self.generate_operand1_test(code)
William Stein's avatar
William Stein committed
4105 4106 4107 4108 4109 4110 4111 4112
        if self.operator == 'and':
            sense = ""
        else:
            sense = "!"
        code.putln(
            "if (%s%s) {" % (
                sense,
                test_result))
4113 4114
        if uses_temp:
            code.funcstate.release_temp(test_result)
4115
        self.operand1.generate_disposal_code(code)
William Stein's avatar
William Stein committed
4116
        self.operand2.generate_evaluation_code(code)
4117
        self.allocate_temp_result(code)
4118
        code.putln("%s = %s;" % (self.result(), self.operand2.result()))
4119 4120
        self.operand2.generate_post_assignment_code(code)
        self.operand2.free_temps(code)
4121 4122
        code.putln("} else {")
        code.putln("%s = %s;" % (self.result(), self.operand1.result()))
4123 4124
        self.operand1.generate_post_assignment_code(code)
        self.operand1.free_temps(code)
4125
        code.putln("}")
William Stein's avatar
William Stein committed
4126 4127 4128 4129
    
    def generate_operand1_test(self, code):
        #  Generate code to test the truth of the first operand.
        if self.type.is_pyobject:
4130 4131
            test_result = code.funcstate.allocate_temp(PyrexTypes.c_bint_type,
                                                       manage_ref=False)
William Stein's avatar
William Stein committed
4132
            code.putln(
4133
                "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
William Stein's avatar
William Stein committed
4134 4135
                    test_result,
                    self.operand1.py_result(),
Robert Bradshaw's avatar
Robert Bradshaw committed
4136
                    code.error_goto_if_neg(test_result, self.pos)))
William Stein's avatar
William Stein committed
4137
        else:
4138
            test_result = self.operand1.result()
4139
        return (test_result, self.type.is_pyobject)
William Stein's avatar
William Stein committed
4140 4141


Robert Bradshaw's avatar
Robert Bradshaw committed
4142 4143 4144 4145 4146 4147 4148
class CondExprNode(ExprNode):
    #  Short-circuiting conditional expression.
    #
    #  test        ExprNode
    #  true_val    ExprNode
    #  false_val   ExprNode
    
4149 4150
    true_val = None
    false_val = None
Robert Bradshaw's avatar
Robert Bradshaw committed
4151 4152 4153 4154 4155 4156 4157 4158 4159
    
    subexprs = ['test', 'true_val', 'false_val']
    
    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)
        self.type = self.compute_result_type(self.true_val.type, self.false_val.type)
4160 4161 4162 4163 4164 4165 4166 4167
        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)
        # must be tmp variables so they can share a result
        self.true_val = self.true_val.coerce_to_temp(env)
        self.false_val = self.false_val.coerce_to_temp(env)
        self.is_temp = 1
        if self.type == PyrexTypes.error_type:
Robert Bradshaw's avatar
Robert Bradshaw committed
4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179
            self.type_error()
    
    def allocate_temps(self, env, result_code = None):
        #  We only ever evaluate one side, and this is 
        #  after evaluating the truth value, so we may
        #  use an allocation strategy here which results in
        #  this node and both its operands sharing the same
        #  result variable. This allows us to avoid some 
        #  assignments and increfs/decrefs that would otherwise
        #  be necessary.
        self.allocate_temp(env, result_code)
        self.test.allocate_temps(env, result_code)
4180 4181
        self.true_val.allocate_temps(env, self.result())
        self.false_val.allocate_temps(env, self.result())
Robert Bradshaw's avatar
Robert Bradshaw committed
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198
        #  We haven't called release_temp on either value,
        #  because although they are temp nodes, they don't own 
        #  their result variable. And because they are temp
        #  nodes, any temps in their subnodes will have been
        #  released before their allocate_temps returned.
        #  Therefore, they contain no temp vars that need to
        #  be released.
        
    def compute_result_type(self, type1, type2):
        if type1 == type2:
            return type1
        elif type1.is_numeric and type2.is_numeric:
            return PyrexTypes.widest_numeric_type(type1, type2)
        elif type1.is_extension_type and type1.subtype_of_resolved_type(type2):
            return type2
        elif type2.is_extension_type and type2.subtype_of_resolved_type(type1):
            return type1
4199 4200
        elif type1.is_pyobject or type2.is_pyobject:
            return py_object_type
4201 4202 4203 4204
        elif type1.assignable_from(type2):
            return type1
        elif type2.assignable_from(type1):
            return type2
Robert Bradshaw's avatar
Robert Bradshaw committed
4205
        else:
4206
            return PyrexTypes.error_type
Robert Bradshaw's avatar
Robert Bradshaw committed
4207 4208 4209 4210 4211 4212
        
    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
4213
    
Robert Bradshaw's avatar
Robert Bradshaw committed
4214 4215 4216 4217 4218 4219 4220
    def check_const(self):
        self.test.check_const()
        self.true_val.check_const()
        self.false_val.check_const()
    
    def generate_evaluation_code(self, code):
        self.test.generate_evaluation_code(code)
4221
        code.putln("if (%s) {" % self.test.result() )
Robert Bradshaw's avatar
Robert Bradshaw committed
4222 4223 4224 4225 4226
        self.true_val.generate_evaluation_code(code)
        code.putln("} else {")
        self.false_val.generate_evaluation_code(code)
        code.putln("}")
        self.test.generate_disposal_code(code)
4227
        self.test.free_temps(code)
Robert Bradshaw's avatar
Robert Bradshaw committed
4228

4229 4230 4231 4232 4233 4234 4235 4236 4237 4238
richcmp_constants = {
    "<" : "Py_LT",
    "<=": "Py_LE",
    "==": "Py_EQ",
    "!=": "Py_NE",
    "<>": "Py_NE",
    ">" : "Py_GT",
    ">=": "Py_GE",
}

William Stein's avatar
William Stein committed
4239 4240 4241 4242
class CmpNode:
    #  Mixin class containing code common to PrimaryCmpNodes
    #  and CascadedCmpNodes.
    
4243 4244
    def cascaded_compile_time_value(self, operand1, denv):
        func = get_compile_time_binop(self)
4245
        operand2 = self.operand2.compile_time_value(denv)
4246 4247 4248 4249
        try:
            result = func(operand1, operand2)
        except Exception, e:
            self.compile_time_value_error(e)
4250
            result = None
4251 4252 4253 4254 4255 4256
        if result:
            cascade = self.cascade
            if cascade:
                result = result and cascade.compile_time_value(operand2, denv)
        return result

William Stein's avatar
William Stein committed
4257 4258 4259 4260 4261
    def is_python_comparison(self):
        return (self.has_python_operands()
            or (self.cascade and self.cascade.is_python_comparison())
            or self.operator in ('in', 'not_in'))

4262 4263 4264 4265
    def is_python_result(self):
        return ((self.has_python_operands() and self.operator not in ('is', 'is_not', 'in', 'not_in'))
            or (self.cascade and self.cascade.is_python_result()))

William Stein's avatar
William Stein committed
4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277
    def check_types(self, env, operand1, op, operand2):
        if not self.types_okay(operand1, op, operand2):
            error(self.pos, "Invalid types for '%s' (%s, %s)" %
                (self.operator, operand1.type, operand2.type))
    
    def types_okay(self, operand1, op, operand2):
        type1 = operand1.type
        type2 = operand2.type
        if type1.is_error or type2.is_error:
            return 1
        if type1.is_pyobject: # type2 will be, too
            return 1
4278
        elif type1.is_ptr or type1.is_array:
William Stein's avatar
William Stein committed
4279
            return type1.is_null_ptr or type2.is_null_ptr \
4280 4281 4282 4283 4284
                or ((type2.is_ptr or type2.is_array)
                    and type1.base_type.same_as(type2.base_type))
        elif ((type1.is_numeric and type2.is_numeric
                    or type1.is_enum and (type1 is type2 or type2.is_int)
                    or type1.is_int and type2.is_enum)
William Stein's avatar
William Stein committed
4285 4286 4287
                and op not in ('is', 'is_not')):
            return 1
        else:
4288
            return type1.is_cfunction and type1.is_cfunction and type1 == type2
William Stein's avatar
William Stein committed
4289 4290 4291

    def generate_operation_code(self, code, result_code, 
            operand1, op , operand2):
4292 4293 4294 4295 4296 4297
        if self.type is PyrexTypes.py_object_type:
            coerce_result = "__Pyx_PyBool_FromLong"
        else:
            coerce_result = ""
        if 'not' in op: negation = "!"
        else: negation = ""
William Stein's avatar
William Stein committed
4298 4299
        if op == 'in' or op == 'not_in':
            code.putln(
4300
                "%s = %s(%sPySequence_Contains(%s, %s)); %s" % (
William Stein's avatar
William Stein committed
4301
                    result_code, 
4302 4303
                    coerce_result, 
                    negation,
William Stein's avatar
William Stein committed
4304 4305
                    operand2.py_result(), 
                    operand1.py_result(), 
Robert Bradshaw's avatar
Robert Bradshaw committed
4306
                    code.error_goto_if_neg(result_code, self.pos)))
William Stein's avatar
William Stein committed
4307 4308
        elif (operand1.type.is_pyobject
            and op not in ('is', 'is_not')):
4309 4310
                code.putln("%s = PyObject_RichCompare(%s, %s, %s); %s" % (
                        result_code, 
William Stein's avatar
William Stein committed
4311 4312
                        operand1.py_result(), 
                        operand2.py_result(), 
4313 4314
                        richcmp_constants[op],
                        code.error_goto_if_null(result_code, self.pos)))
William Stein's avatar
William Stein committed
4315
        else:
4316 4317 4318 4319 4320
            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
4321 4322
            elif type1.is_numeric:
                common_type = PyrexTypes.widest_numeric_type(type1, type2)
4323
            else:
4324 4325 4326
                common_type = type1
            code1 = operand1.result_as(common_type)
            code2 = operand2.result_as(common_type)
4327
            code.putln("%s = %s(%s %s %s);" % (
William Stein's avatar
William Stein committed
4328
                result_code, 
4329
                coerce_result, 
4330
                code1, 
William Stein's avatar
William Stein committed
4331
                self.c_operator(op), 
4332 4333
                code2))

William Stein's avatar
William Stein committed
4334 4335 4336 4337 4338 4339 4340 4341 4342
    def c_operator(self, op):
        if op == 'is':
            return "=="
        elif op == 'is_not':
            return "!="
        else:
            return op
    

4343
class PrimaryCmpNode(NewTempExprNode, CmpNode):
William Stein's avatar
William Stein committed
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356
    #  Non-cascaded comparison or first comparison of
    #  a cascaded sequence.
    #
    #  operator      string
    #  operand1      ExprNode
    #  operand2      ExprNode
    #  cascade       CascadedCmpNode
    
    #  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.
    
Robert Bradshaw's avatar
Robert Bradshaw committed
4357 4358
    child_attrs = ['operand1', 'operand2', 'cascade']
    
William Stein's avatar
William Stein committed
4359 4360
    cascade = None
    
4361
    def compile_time_value(self, denv):
4362
        operand1 = self.operand1.compile_time_value(denv)
4363 4364
        return self.cascaded_compile_time_value(operand1, denv)

William Stein's avatar
William Stein committed
4365 4366 4367 4368 4369 4370 4371 4372
    def analyse_types(self, env):
        self.operand1.analyse_types(env)
        self.operand2.analyse_types(env)
        if self.cascade:
            self.cascade.analyse_types(env, self.operand2)
        self.is_pycmp = self.is_python_comparison()
        if self.is_pycmp:
            self.coerce_operands_to_pyobjects(env)
4373 4374
        if self.has_int_operands():
            self.coerce_chars_to_ints(env)
William Stein's avatar
William Stein committed
4375 4376 4377 4378
        if self.cascade:
            self.operand2 = self.operand2.coerce_to_simple(env)
            self.cascade.coerce_cascaded_operands_to_temp(env)
        self.check_operand_types(env)
4379 4380 4381 4382 4383 4384 4385 4386
        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
4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
        if self.is_pycmp or self.cascade:
            self.is_temp = 1
    
    def check_operand_types(self, env):
        self.check_types(env, 
            self.operand1, self.operator, self.operand2)
        if self.cascade:
            self.cascade.check_operand_types(env, self.operand2)
    
    def has_python_operands(self):
        return (self.operand1.type.is_pyobject
            or self.operand2.type.is_pyobject)
4399
            
William Stein's avatar
William Stein committed
4400 4401 4402 4403 4404 4405
    def coerce_operands_to_pyobjects(self, env):
        self.operand1 = self.operand1.coerce_to_pyobject(env)
        self.operand2 = self.operand2.coerce_to_pyobject(env)
        if self.cascade:
            self.cascade.coerce_operands_to_pyobjects(env)
        
4406 4407 4408 4409 4410
    def has_int_operands(self):
        return (self.operand1.type.is_int or self.operand2.type.is_int) \
           or (self.cascade and self.cascade.has_int_operands())
    
    def coerce_chars_to_ints(self, env):
4411 4412
        # coerce literal single-char strings to c chars
        if self.operand1.type.is_string and isinstance(self.operand1, StringNode):
4413
            self.operand1 = self.operand1.coerce_to(PyrexTypes.c_uchar_type, env)
4414
        if self.operand2.type.is_string and isinstance(self.operand2, StringNode):
4415 4416 4417 4418
            self.operand2 = self.operand2.coerce_to(PyrexTypes.c_uchar_type, env)
        if self.cascade:
            self.cascade.coerce_chars_to_ints(env)
    
William Stein's avatar
William Stein committed
4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438
    def allocate_subexpr_temps(self, env):
        self.operand1.allocate_temps(env)
        self.operand2.allocate_temps(env)
        if self.cascade:
            self.cascade.allocate_subexpr_temps(env)
    
    def release_subexpr_temps(self, env):
        self.operand1.release_temp(env)
        self.operand2.release_temp(env)
        if self.cascade:
            self.cascade.release_subexpr_temps(env)
    
    def check_const(self):
        self.operand1.check_const()
        self.operand2.check_const()
        if self.cascade:
            self.not_const()

    def calculate_result_code(self):
        return "(%s %s %s)" % (
4439
            self.operand1.result(),
William Stein's avatar
William Stein committed
4440
            self.c_operator(self.operator),
4441
            self.operand2.result())
4442

William Stein's avatar
William Stein committed
4443 4444 4445 4446
    def generate_evaluation_code(self, code):
        self.operand1.generate_evaluation_code(code)
        self.operand2.generate_evaluation_code(code)
        if self.is_temp:
4447
            self.allocate_temp_result(code)
4448
            self.generate_operation_code(code, self.result(), 
William Stein's avatar
William Stein committed
4449 4450 4451
                self.operand1, self.operator, self.operand2)
            if self.cascade:
                self.cascade.generate_evaluation_code(code,
4452
                    self.result(), self.operand2)
William Stein's avatar
William Stein committed
4453 4454
            self.operand1.generate_disposal_code(code)
            self.operand2.generate_disposal_code(code)
4455 4456 4457
        self.operand1.free_temps(code)
        self.operand2.free_temps(code)

William Stein's avatar
William Stein committed
4458 4459 4460 4461 4462
    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)
4463
        
4464 4465 4466 4467 4468 4469
    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)
        
4470 4471 4472 4473 4474
    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
4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486


class CascadedCmpNode(Node, CmpNode):
    #  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 
    #  with the PrimaryCmpNode at the head of the chain.
    #
    #  operator      string
    #  operand2      ExprNode
    #  cascade       CascadedCmpNode

Robert Bradshaw's avatar
Robert Bradshaw committed
4487 4488
    child_attrs = ['operand2', 'cascade']

William Stein's avatar
William Stein committed
4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503
    cascade = None
    
    def analyse_types(self, env, operand1):
        self.operand2.analyse_types(env)
        if self.cascade:
            self.cascade.analyse_types(env, self.operand2)
    
    def check_operand_types(self, env, operand1):
        self.check_types(env, 
            operand1, self.operator, self.operand2)
        if self.cascade:
            self.cascade.check_operand_types(env, self.operand2)
    
    def has_python_operands(self):
        return self.operand2.type.is_pyobject
4504
        
William Stein's avatar
William Stein committed
4505 4506 4507 4508 4509
    def coerce_operands_to_pyobjects(self, env):
        self.operand2 = self.operand2.coerce_to_pyobject(env)
        if self.cascade:
            self.cascade.coerce_operands_to_pyobjects(env)

4510 4511 4512 4513
    def has_int_operands(self):
        return self.operand2.type.is_int
        
    def coerce_chars_to_ints(self, env):
4514
        if self.operand2.type.is_string and isinstance(self.operand2, StringNode):
4515 4516
            self.operand2 = self.operand2.coerce_to(PyrexTypes.c_uchar_type, env)

William Stein's avatar
William Stein committed
4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533
    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)
    
    def allocate_subexpr_temps(self, env):
        self.operand2.allocate_temps(env)
        if self.cascade:
            self.cascade.allocate_subexpr_temps(env)
    
    def release_subexpr_temps(self, env):
        self.operand2.release_temp(env)
        if self.cascade:
            self.cascade.release_subexpr_temps(env)
    
    def generate_evaluation_code(self, code, result, operand1):
4534 4535 4536 4537
        if self.type.is_pyobject:
            code.putln("if (__Pyx_PyObject_IsTrue(%s)) {" % result)
        else:
            code.putln("if (%s) {" % result)
William Stein's avatar
William Stein committed
4538 4539 4540 4541 4542 4543 4544 4545
        self.operand2.generate_evaluation_code(code)
        self.generate_operation_code(code, result, 
            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)
4546
        self.operand2.free_temps(code)
William Stein's avatar
William Stein committed
4547 4548
        code.putln("}")

4549 4550 4551 4552 4553
    def annotate(self, code):
        self.operand2.annotate(code)
        if self.cascade:
            self.cascade.annotate(code)

William Stein's avatar
William Stein committed
4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566

binop_node_classes = {
    "or":		BoolBinopNode,
    "and":	BoolBinopNode,
    "|":		IntBinopNode,
    "^":		IntBinopNode,
    "&":		IntBinopNode,
    "<<":		IntBinopNode,
    ">>":		IntBinopNode,
    "+":		AddNode,
    "-":		SubNode,
    "*":		MulNode,
    "/":		NumBinopNode,
Robert Bradshaw's avatar
Robert Bradshaw committed
4567
    "//":		FloorDivNode,
William Stein's avatar
William Stein committed
4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590
    "%":		ModNode,
    "**":		PowNode
}

def binop_node(pos, operator, operand1, operand2):
    # Construct binop node of appropriate class for 
    # given operator.
    return binop_node_classes[operator](pos, 
        operator = operator, 
        operand1 = operand1, 
        operand2 = operand2)

#-------------------------------------------------------------------
#
#  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.
#
#-------------------------------------------------------------------

4591
class CoercionNode(NewTempExprNode):
William Stein's avatar
William Stein committed
4592 4593 4594 4595 4596 4597 4598 4599 4600 4601
    #  Abstract base class for coercion nodes.
    #
    #  arg       ExprNode       node being coerced
    
    subexprs = ['arg']
    
    def __init__(self, arg):
        self.pos = arg.pos
        self.arg = arg
        if debug_coercion:
Stefan Behnel's avatar
Stefan Behnel committed
4602
            print("%s Coercing %s" % (self, self.arg))
4603 4604 4605 4606 4607 4608
            
    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
4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632


class CastNode(CoercionNode):
    #  Wrap a node in a C type cast.
    
    def __init__(self, arg, new_type):
        CoercionNode.__init__(self, arg)
        self.type = new_type
    
    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.

    def __init__(self, arg, dst_type, env):
        #  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
4633
        assert dst_type.is_extension_type or dst_type.is_builtin_type, "PyTypeTest on non extension type"
William Stein's avatar
William Stein committed
4634 4635
        CoercionNode.__init__(self, arg)
        self.type = dst_type
4636
        self.gil_check(env)
William Stein's avatar
William Stein committed
4637
        self.result_ctype = arg.ctype()
4638 4639

    gil_message = "Python type test"
William Stein's avatar
William Stein committed
4640
    
4641 4642 4643
    def analyse_types(self, env):
        pass
    
William Stein's avatar
William Stein committed
4644 4645 4646 4647 4648 4649 4650
    def result_in_temp(self):
        return self.arg.result_in_temp()
    
    def is_ephemeral(self):
        return self.arg.is_ephemeral()
    
    def calculate_result_code(self):
4651
        return self.arg.result()
William Stein's avatar
William Stein committed
4652 4653 4654
    
    def generate_result_code(self, code):
        if self.type.typeobj_is_available():
4655
            if not self.type.is_builtin_type:
4656
                code.globalstate.use_utility_code(type_test_utility_code)
William Stein's avatar
William Stein committed
4657
            code.putln(
Robert Bradshaw's avatar
Robert Bradshaw committed
4658 4659
                "if (!(%s)) %s" % (
                    self.type.type_test_code(self.arg.py_result()),
William Stein's avatar
William Stein committed
4660 4661 4662 4663 4664 4665 4666
                    code.error_goto(self.pos)))
        else:
            error(self.pos, "Cannot test type of extern C class "
                "without type object name specification")
                
    def generate_post_assignment_code(self, code):
        self.arg.generate_post_assignment_code(code)
4667 4668 4669

    def free_temps(self, code):
        self.arg.free_temps(code)
William Stein's avatar
William Stein committed
4670
                
4671

William Stein's avatar
William Stein committed
4672 4673 4674 4675 4676 4677 4678
class CoerceToPyTypeNode(CoercionNode):
    #  This node is used to convert a C data type
    #  to a Python object.

    def __init__(self, arg, env):
        CoercionNode.__init__(self, arg)
        self.type = py_object_type
4679
        self.gil_check(env)
William Stein's avatar
William Stein committed
4680
        self.is_temp = 1
Robert Bradshaw's avatar
Robert Bradshaw committed
4681
        if not arg.type.to_py_function or not arg.type.create_convert_utility_code(env):
William Stein's avatar
William Stein committed
4682 4683
            error(arg.pos,
                "Cannot convert '%s' to Python object" % arg.type)
Robert Bradshaw's avatar
Robert Bradshaw committed
4684
        
4685
    gil_message = "Converting to Python object"
4686 4687
    
    def coerce_to_boolean(self, env):
4688
        return self.arg.coerce_to_boolean(env).coerce_to_temp(env)
4689

4690 4691 4692 4693
    def analyse_types(self, env):
        # The arg is always already analysed
        pass

William Stein's avatar
William Stein committed
4694 4695
    def generate_result_code(self, code):
        function = self.arg.type.to_py_function
Robert Bradshaw's avatar
Robert Bradshaw committed
4696
        code.putln('%s = %s(%s); %s' % (
4697
            self.result(), 
William Stein's avatar
William Stein committed
4698
            function, 
4699 4700
            self.arg.result(), 
            code.error_goto_if_null(self.result(), self.pos)))
William Stein's avatar
William Stein committed
4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717


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
        if not result_type.from_py_function:
            error(arg.pos,
                "Cannot convert Python object to '%s'" % result_type)
        if self.type.is_string and self.arg.is_ephemeral():
            error(arg.pos,
                "Obtaining char * from temporary Python value")
    
4718 4719 4720 4721
    def analyse_types(self, env):
        # The arg is always already analysed
        pass

William Stein's avatar
William Stein committed
4722 4723
    def generate_result_code(self, code):
        function = self.type.from_py_function
4724 4725 4726 4727
        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
4728
        code.putln('%s = %s; %s' % (
4729
            self.result(), 
4730
            rhs,
4731
            code.error_goto_if(self.type.error_condition(self.result()), self.pos)))
William Stein's avatar
William Stein committed
4732 4733 4734 4735 4736 4737 4738 4739


class CoerceToBooleanNode(CoercionNode):
    #  This node is used when a result needs to be used
    #  in a boolean context.
    
    def __init__(self, arg, env):
        CoercionNode.__init__(self, arg)
4740
        self.type = PyrexTypes.c_bint_type
William Stein's avatar
William Stein committed
4741
        if arg.type.is_pyobject:
4742 4743
            if env.nogil:
                self.gil_error()
William Stein's avatar
William Stein committed
4744
            self.is_temp = 1
4745 4746

    gil_message = "Truth-testing Python object"
William Stein's avatar
William Stein committed
4747 4748 4749 4750 4751 4752 4753
    
    def check_const(self):
        if self.is_temp:
            self.not_const()
        self.arg.check_const()
    
    def calculate_result_code(self):
4754
        return "(%s != 0)" % self.arg.result()
William Stein's avatar
William Stein committed
4755 4756 4757 4758

    def generate_result_code(self, code):
        if self.arg.type.is_pyobject:
            code.putln(
4759
                "%s = __Pyx_PyObject_IsTrue(%s); %s" % (
4760
                    self.result(), 
William Stein's avatar
William Stein committed
4761
                    self.arg.py_result(), 
4762
                    code.error_goto_if_neg(self.result(), self.pos)))
William Stein's avatar
William Stein committed
4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774


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
        self.is_temp = 1
        if self.type.is_pyobject:
4775
            self.gil_check(env)
William Stein's avatar
William Stein committed
4776
            self.result_ctype = py_object_type
4777 4778 4779

    gil_message = "Creating temporary Python reference"

4780 4781 4782
    def analyse_types(self, env):
        # The arg is always already analysed
        pass
4783 4784 4785 4786 4787 4788
        
    def coerce_to_boolean(self, env):
        self.arg = self.arg.coerce_to_boolean(env)
        self.type = self.arg.type
        self.result_ctype = self.type
        return self
4789

William Stein's avatar
William Stein committed
4790 4791 4792 4793
    def generate_result_code(self, code):
        #self.arg.generate_evaluation_code(code) # Already done
        # by generic generate_subexpr_evaluation_code!
        code.putln("%s = %s;" % (
4794
            self.result(), self.arg.result_as(self.ctype())))
William Stein's avatar
William Stein committed
4795
        if self.type.is_pyobject:
4796
            code.put_incref(self.result(), self.ctype())
William Stein's avatar
William Stein committed
4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810


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
    #  disposal code for it. The original owner of the argument 
    #  node is responsible for doing those things.
    
    subexprs = [] # Arg is not considered a subexpr
    
    def __init__(self, arg):
        CoercionNode.__init__(self, arg)
4811 4812 4813 4814 4815
        if hasattr(arg, 'type'):
            self.type = arg.type
            self.result_ctype = arg.result_ctype
        if hasattr(arg, 'entry'):
            self.entry = arg.entry
William Stein's avatar
William Stein committed
4816
    
4817
    def result(self):
4818
        return self.arg.result()
Robert Bradshaw's avatar
Robert Bradshaw committed
4819 4820 4821 4822 4823
        
    def analyse_types(self, env):
        self.type = self.arg.type
        self.result_ctype = self.arg.result_ctype
        self.is_temp = 1
4824 4825
        if hasattr(self.arg, 'entry'):
            self.entry = self.arg.entry
William Stein's avatar
William Stein committed
4826 4827 4828 4829 4830 4831
    
    def generate_evaluation_code(self, code):
        pass

    def generate_result_code(self, code):
        pass
4832
        
4833
    def generate_disposal_code(self, code):
4834 4835
        pass
                
4836
    def allocate_temps(self, env):
4837
        pass
4838 4839 4840
        
    def release_temp(self, env):
        pass
4841 4842 4843 4844

    def free_temps(self, code):
        pass
    
4845
        
4846
class DISABLED_PersistentNode(ExprNode):
4847 4848 4849 4850 4851 4852 4853
    # A PersistentNode is like a CloneNode except it handles the temporary
    # allocation itself by keeping track of the number of times it has been 
    # used. 
    
    subexprs = ["arg"]
    temp_counter = 0
    generate_counter = 0
Robert Bradshaw's avatar
Robert Bradshaw committed
4854
    analyse_counter = 0
4855 4856 4857 4858 4859 4860 4861 4862
    result_code = None
    
    def __init__(self, arg, uses):
        self.pos = arg.pos
        self.arg = arg
        self.uses = uses
        
    def analyse_types(self, env):
Robert Bradshaw's avatar
Robert Bradshaw committed
4863 4864 4865 4866 4867 4868
        if self.analyse_counter == 0:
            self.arg.analyse_types(env)
            self.type = self.arg.type
            self.result_ctype = self.arg.result_ctype
            self.is_temp = 1
        self.analyse_counter += 1
4869
        
4870
    def calculate_result_code(self):
4871
        return self.result()
4872

4873 4874 4875 4876
    def generate_evaluation_code(self, code):
        if self.generate_counter == 0:
            self.arg.generate_evaluation_code(code)
            code.putln("%s = %s;" % (
4877
                self.result(), self.arg.result_as(self.ctype())))
4878
            if self.type.is_pyobject:
4879
                code.put_incref(self.result(), self.ctype())
4880 4881 4882
            self.arg.generate_disposal_code(code)
        self.generate_counter += 1
                
4883
    def generate_disposal_code(self, code):
4884
        if self.generate_counter == self.uses:
4885
            if self.type.is_pyobject:
4886
                code.put_decref_clear(self.result(), self.ctype())
4887 4888 4889 4890

    def allocate_temps(self, env, result=None):
        if self.temp_counter == 0:
            self.arg.allocate_temps(env)
Robert Bradshaw's avatar
Robert Bradshaw committed
4891
            self.allocate_temp(env, result)
4892 4893 4894
            self.arg.release_temp(env)
        self.temp_counter += 1
        
Robert Bradshaw's avatar
Robert Bradshaw committed
4895 4896 4897 4898 4899 4900
    def allocate_temp(self, env, result=None):
        if result is None:
            self.result_code = env.allocate_temp(self.type)
        else:
            self.result_code = result
        
4901 4902
    def release_temp(self, env):
        if self.temp_counter == self.uses:
4903
            env.release_temp(self.result())
William Stein's avatar
William Stein committed
4904 4905 4906 4907 4908 4909 4910
    
#------------------------------------------------------------------------------------
#
#  Runtime support code
#
#------------------------------------------------------------------------------------

4911 4912
get_name_interned_utility_code = UtilityCode(
proto = """
4913
static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name); /*proto*/
4914 4915
""",
impl = """
William Stein's avatar
William Stein committed
4916 4917 4918 4919 4920 4921 4922
static PyObject *__Pyx_GetName(PyObject *dict, PyObject *name) {
    PyObject *result;
    result = PyObject_GetAttr(dict, name);
    if (!result)
        PyErr_SetObject(PyExc_NameError, name);
    return result;
}
4923
""")
William Stein's avatar
William Stein committed
4924 4925 4926

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

4927 4928
import_utility_code = UtilityCode(
proto = """
4929
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list); /*proto*/
4930 4931
""",
impl = """
William Stein's avatar
William Stein committed
4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list) {
    PyObject *__import__ = 0;
    PyObject *empty_list = 0;
    PyObject *module = 0;
    PyObject *global_dict = 0;
    PyObject *empty_dict = 0;
    PyObject *list;
    __import__ = PyObject_GetAttrString(%(BUILTINS)s, "__import__");
    if (!__import__)
        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;
4956 4957
    module = PyObject_CallFunctionObjArgs(__import__,
        name, global_dict, empty_dict, list, NULL);
William Stein's avatar
William Stein committed
4958 4959 4960 4961 4962 4963 4964 4965 4966
bad:
    Py_XDECREF(empty_list);
    Py_XDECREF(__import__);
    Py_XDECREF(empty_dict);
    return module;
}
""" % {
    "BUILTINS": Naming.builtins_cname,
    "GLOBALS":  Naming.module_cname,
4967
})
William Stein's avatar
William Stein committed
4968 4969 4970

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

4971 4972
get_exception_utility_code = UtilityCode(
proto = """
4973
static PyObject *__Pyx_GetExcValue(void); /*proto*/
4974 4975
""",
impl = """
William Stein's avatar
William Stein committed
4976 4977
static PyObject *__Pyx_GetExcValue(void) {
    PyObject *type = 0, *value = 0, *tb = 0;
4978
    PyObject *tmp_type, *tmp_value, *tmp_tb;
William Stein's avatar
William Stein committed
4979 4980 4981 4982 4983 4984 4985 4986 4987 4988
    PyObject *result = 0;
    PyThreadState *tstate = PyThreadState_Get();
    PyErr_Fetch(&type, &value, &tb);
    PyErr_NormalizeException(&type, &value, &tb);
    if (PyErr_Occurred())
        goto bad;
    if (!value) {
        value = Py_None;
        Py_INCREF(value);
    }
4989 4990 4991
    tmp_type = tstate->exc_type;
    tmp_value = tstate->exc_value;
    tmp_tb = tstate->exc_traceback;
William Stein's avatar
William Stein committed
4992 4993 4994
    tstate->exc_type = type;
    tstate->exc_value = value;
    tstate->exc_traceback = tb;
4995 4996 4997 4998 4999
    /* Make sure tstate is in a consistent state when we XDECREF
    these objects (XDECREF may run arbitrary code). */
    Py_XDECREF(tmp_type);
    Py_XDECREF(tmp_value);
    Py_XDECREF(tmp_tb);
William Stein's avatar
William Stein committed
5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010
    result = value;
    Py_XINCREF(result);
    type = 0;
    value = 0;
    tb = 0;
bad:
    Py_XDECREF(type);
    Py_XDECREF(value);
    Py_XDECREF(tb);
    return result;
}
5011
""")
William Stein's avatar
William Stein committed
5012 5013 5014

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

5015 5016
unpacking_utility_code = UtilityCode(
proto = """
5017
static PyObject *__Pyx_UnpackItem(PyObject *, Py_ssize_t index); /*proto*/
5018
static int __Pyx_EndUnpack(PyObject *); /*proto*/
5019 5020
""",
impl = """
5021
static PyObject *__Pyx_UnpackItem(PyObject *iter, Py_ssize_t index) {
5022 5023
    PyObject *item;
    if (!(item = PyIter_Next(iter))) {
5024 5025 5026 5027 5028 5029 5030 5031
        if (!PyErr_Occurred()) {
            PyErr_Format(PyExc_ValueError,
                #if PY_VERSION_HEX < 0x02050000
                    "need more than %d values to unpack", (int)index);
                #else
                    "need more than %zd values to unpack", index);
                #endif
        }
5032 5033
    }
    return item;
5034
}
William Stein's avatar
William Stein committed
5035

5036 5037 5038 5039
static int __Pyx_EndUnpack(PyObject *iter) {
    PyObject *item;
    if ((item = PyIter_Next(iter))) {
        Py_DECREF(item);
5040
        PyErr_SetString(PyExc_ValueError, "too many values to unpack");
5041 5042 5043 5044 5045 5046
        return -1;
    }
    else if (!PyErr_Occurred())
        return 0;
    else
        return -1;
5047
}
5048
""")
William Stein's avatar
William Stein committed
5049 5050 5051

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

5052 5053
type_test_utility_code = UtilityCode(
proto = """
5054
static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/
5055 5056
""",
impl = """
William Stein's avatar
William Stein committed
5057 5058 5059 5060 5061 5062 5063 5064
static int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) {
    if (!type) {
        PyErr_Format(PyExc_SystemError, "Missing type object");
        return 0;
    }
    if (obj == Py_None || PyObject_TypeCheck(obj, type))
        return 1;
    PyErr_Format(PyExc_TypeError, "Cannot convert %s to %s",
5065
        Py_TYPE(obj)->tp_name, type->tp_name);
William Stein's avatar
William Stein committed
5066 5067
    return 0;
}
5068
""")
William Stein's avatar
William Stein committed
5069 5070 5071

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

5072 5073
create_class_utility_code = UtilityCode(
proto = """
5074
static PyObject *__Pyx_CreateClass(PyObject *bases, PyObject *dict, PyObject *name, const char *modname); /*proto*/
5075 5076
""",
impl = """
William Stein's avatar
William Stein committed
5077
static PyObject *__Pyx_CreateClass(
5078
    PyObject *bases, PyObject *dict, PyObject *name, const char *modname)
William Stein's avatar
William Stein committed
5079 5080 5081
{
    PyObject *py_modname;
    PyObject *result = 0;
5082

5083
    #if PY_MAJOR_VERSION < 3
William Stein's avatar
William Stein committed
5084
    py_modname = PyString_FromString(modname);
5085 5086 5087
    #else
    py_modname = PyUnicode_FromString(modname);
    #endif
William Stein's avatar
William Stein committed
5088 5089 5090 5091
    if (!py_modname)
        goto bad;
    if (PyDict_SetItemString(dict, "__module__", py_modname) < 0)
        goto bad;
5092
    #if PY_MAJOR_VERSION < 3
William Stein's avatar
William Stein committed
5093
    result = PyClass_New(bases, dict, name);
5094 5095 5096
    #else
    result = PyObject_CallFunctionObjArgs((PyObject *)&PyType_Type, name, bases, dict, NULL);
    #endif
William Stein's avatar
William Stein committed
5097 5098 5099 5100
bad:
    Py_XDECREF(py_modname);
    return result;
}
5101
""")
William Stein's avatar
William Stein committed
5102 5103

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

5105 5106
cpp_exception_utility_code = UtilityCode(
proto = """
5107 5108
#ifndef __Pyx_CppExn2PyErr
static void __Pyx_CppExn2PyErr() {
Robert Bradshaw's avatar
Robert Bradshaw committed
5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124
  try {
    if (PyErr_Occurred())
      ; // let the latest Python exn pass through and ignore the current one
    else
      throw;
  } catch (const std::out_of_range& exn) {
    // catch out_of_range explicitly so the proper Python exn may be raised
    PyErr_SetString(PyExc_IndexError, exn.what());
  } catch (const std::exception& exn) {
    PyErr_SetString(PyExc_RuntimeError, exn.what());
  }
  catch (...)
  {
    PyErr_SetString(PyExc_RuntimeError, "Unknown exception");
  }
}
5125
#endif
5126 5127 5128
""",
impl = ""
)
Robert Bradshaw's avatar
Robert Bradshaw committed
5129 5130

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

5132 5133
append_utility_code = UtilityCode(
proto = """
Stefan Behnel's avatar
Stefan Behnel committed
5134
static INLINE PyObject* __Pyx_PyObject_Append(PyObject* L, PyObject* x) {
Robert Bradshaw's avatar
Robert Bradshaw committed
5135 5136 5137 5138 5139 5140
    if (likely(PyList_CheckExact(L))) {
        if (PyList_Append(L, x) < 0) return NULL;
        Py_INCREF(Py_None);
        return Py_None; // this is just to have an accurate signature
    }
    else {
5141 5142 5143 5144 5145 5146
        PyObject *r, *m;
        m = PyObject_GetAttrString(L, "append");
        if (!m) return NULL;
        r = PyObject_CallFunctionObjArgs(m, x, NULL);
        Py_DECREF(m);
        return r;
Robert Bradshaw's avatar
Robert Bradshaw committed
5147 5148
    }
}
5149 5150 5151
""",
impl = ""
)
5152 5153 5154

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

Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5155 5156 5157
# If the is_unsigned flag is set, we need to do some extra work to make 
# sure the index doesn't become negative. 

5158 5159
getitem_int_utility_code = UtilityCode(
proto = """
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181
static INLINE PyObject *__Pyx_GetItemInt(PyObject *o, Py_ssize_t i, int is_unsigned) {
    PyObject *r;
    if (PyList_CheckExact(o) && 0 <= i && i < PyList_GET_SIZE(o)) {
        r = PyList_GET_ITEM(o, i);
        Py_INCREF(r);
    }
    else if (PyTuple_CheckExact(o) && 0 <= i && i < PyTuple_GET_SIZE(o)) {
        r = PyTuple_GET_ITEM(o, i);
        Py_INCREF(r);
    }
    else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_item && (likely(i >= 0) || !is_unsigned))
        r = PySequence_GetItem(o, i);
    else {
        PyObject *j = (likely(i >= 0) || !is_unsigned) ? PyInt_FromLong(i) : PyLong_FromUnsignedLongLong((sizeof(unsigned long long) > sizeof(Py_ssize_t) ? (1ULL << (sizeof(Py_ssize_t)*8)) : 0) + i);
        if (!j)
            return 0;
        r = PyObject_GetItem(o, j);
        Py_DECREF(j);
    }
    return r;
}
""",
5182 5183
impl = """
""")
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5184 5185 5186

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

5187 5188
setitem_int_utility_code = UtilityCode(
proto = """
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208
static INLINE int __Pyx_SetItemInt(PyObject *o, Py_ssize_t i, PyObject *v, int is_unsigned) {
    int r;
    if (PyList_CheckExact(o) && 0 <= i && i < PyList_GET_SIZE(o)) {
        Py_DECREF(PyList_GET_ITEM(o, i));
        Py_INCREF(v);
        PyList_SET_ITEM(o, i, v);
        return 1;
    }
    else if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0) || !is_unsigned))
        r = PySequence_SetItem(o, i, v);
    else {
        PyObject *j = (likely(i >= 0) || !is_unsigned) ? PyInt_FromLong(i) : PyLong_FromUnsignedLongLong((sizeof(unsigned long long) > sizeof(Py_ssize_t) ? (1ULL << (sizeof(Py_ssize_t)*8)) : 0) + i);
        if (!j)
            return -1;
        r = PyObject_SetItem(o, j, v);
        Py_DECREF(j);
    }
    return r;
}
""",
5209 5210 5211
impl = """
""")

5212 5213
#------------------------------------------------------------------------------------

5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234
delitem_int_utility_code = UtilityCode(
proto = """
static INLINE int __Pyx_DelItemInt(PyObject *o, Py_ssize_t i, int is_unsigned) {
    int r;
    if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_ass_item && (likely(i >= 0) || !is_unsigned))
        r = PySequence_DelItem(o, i);
    else {
        PyObject *j = (likely(i >= 0) || !is_unsigned) ? PyInt_FromLong(i) : PyLong_FromUnsignedLongLong((sizeof(unsigned long long) > sizeof(Py_ssize_t) ? (1ULL << (sizeof(Py_ssize_t)*8)) : 0) + i);
        if (!j)
            return -1;
        r = PyObject_DelItem(o, j);
        Py_DECREF(j);
    }
    return r;
}
""",
impl = """
""")

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

5235 5236
raise_noneattr_error_utility_code = UtilityCode(
proto = """
5237
static INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname);
5238 5239
""",
impl = """
5240
static INLINE void __Pyx_RaiseNoneAttributeError(const char* attrname) {
5241 5242
    PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", attrname);
}
5243
""")
5244

5245 5246
raise_noneindex_error_utility_code = UtilityCode(
proto = """
5247
static INLINE void __Pyx_RaiseNoneIndexingError();
5248 5249
""",
impl = """
5250 5251 5252
static INLINE void __Pyx_RaiseNoneIndexingError() {
    PyErr_SetString(PyExc_TypeError, "'NoneType' object is unsubscriptable");
}
5253
""")