6 from Cython import Utils
7 from Errors import warning, error, InternalError
8 from StringEncoding import EncodedString
11 from PyrexTypes import py_object_type, unspecified_type
13 from TypeSlots import \
14 pyfunction_signature, pymethod_signature, \
15 get_special_method_signature, get_property_accessor_signature
18 import __builtin__ as builtins
22 from sets import Set as set
25 possible_identifier = re.compile(ur"(?![0-9])\w+$", re.U).match
26 nice_identifier = re.compile('^[a-zA-Z0-0_]+$').match
28 iso_c99_keywords = set(
29 ['auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
30 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if',
31 'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof',
32 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void',
34 '_Bool', '_Complex'', _Imaginary', 'inline', 'restrict'])
36 def c_safe_identifier(cname):
37 # There are some C limitations on struct entry names.
38 if ((cname[:2] == '__'
39 and not (cname.startswith(Naming.pyrex_prefix)
40 or cname == '__weakref__'))
41 or cname in iso_c99_keywords):
42 cname = Naming.pyrex_prefix + cname
45 class BufferAux(object):
46 writable_needed = False
48 def __init__(self, buffer_info_var, stridevars, shapevars,
50 self.buffer_info_var = buffer_info_var
51 self.stridevars = stridevars
52 self.shapevars = shapevars
53 self.suboffsetvars = suboffsetvars
56 return "<BufferAux %r>" % self.__dict__
59 # A symbol table entry in a Scope or ModuleNamespace.
61 # name string Python name of entity
62 # cname string C name of entity
63 # type PyrexType Type of entity
64 # doc string Doc string
65 # init string Initial value
66 # visibility 'private' or 'public' or 'extern'
67 # is_builtin boolean Is an entry in the Python builtins dict
68 # is_cglobal boolean Is a C global variable
69 # is_pyglobal boolean Is a Python module-level variable
70 # or class attribute during
72 # is_member boolean Is an assigned class member
73 # is_pyclass_attr boolean Is a name in a Python class namespace
74 # is_variable boolean Is a variable
75 # is_cfunction boolean Is a C function
76 # is_cmethod boolean Is a C method of an extension type
77 # is_unbound_cmethod boolean Is an unbound C method of an extension type
78 # is_anonymous boolean Is a anonymous pyfunction entry
79 # is_type boolean Is a type definition
80 # is_cclass boolean Is an extension class
81 # is_cpp_class boolean Is a C++ class
82 # is_const boolean Is a constant
83 # is_property boolean Is a property of an extension type:
84 # doc_cname string or None C const holding the docstring
85 # getter_cname string C func for getting property
86 # setter_cname string C func for setting or deleting property
87 # is_self_arg boolean Is the "self" arg of an exttype method
88 # is_arg boolean Is the arg of a method
89 # is_local boolean Is a local variable
90 # in_closure boolean Is referenced in an inner scope
91 # is_readonly boolean Can't be assigned to
92 # func_cname string C func implementing Python func
93 # func_modifiers [string] C function modifiers ('inline')
94 # pos position Source position where declared
95 # namespace_cname string If is_pyglobal, the C variable
96 # holding its home namespace
97 # pymethdef_cname string PyMethodDef structure
98 # signature Signature Arg & return types for Python func
99 # init_to_none boolean True if initial value should be None
100 # as_variable Entry Alternative interpretation of extension
101 # type name or builtin C function as a variable
102 # xdecref_cleanup boolean Use Py_XDECREF for error cleanup
103 # in_cinclude boolean Suppress C declaration code
104 # enum_values [Entry] For enum types, list of values
105 # qualified_name string "modname.funcname" or "modname.classname"
106 # or "modname.classname.funcname"
107 # is_declared_generic boolean Is declared as PyObject * even though its
108 # type is an extension type
109 # as_module None Module scope, if a cimported module
110 # is_inherited boolean Is an inherited attribute of an extension type
111 # pystring_cname string C name of Python version of string literal
112 # is_interned boolean For string const entries, value is interned
113 # is_identifier boolean For string const entries, value is an identifier
115 # is_special boolean Is a special method or property accessor
116 # of an extension type
117 # defined_in_pxd boolean Is defined in a .pxd file (not just declared)
118 # api boolean Generate C API for C class or function
119 # utility_code string Utility code needed when this entry is used
121 # buffer_aux BufferAux or None Extra information needed for buffer variables
122 # inline_func_in_pxd boolean Hacky special case for inline function in pxd file.
123 # Ideally this should not be necesarry.
124 # assignments [ExprNode] List of expressions that get assigned to this entry.
125 # might_overflow boolean In an arithmetic expression that could cause
126 # overflow (used for type inference).
128 inline_func_in_pxd = False
131 visibility = 'private'
140 is_unbound_cmethod = 0
155 is_declared_generic = 0
166 pystring_cname = None
180 def __init__(self, name, cname, type, pos = None, init = None):
186 self.overloaded_alternatives = []
187 self.assignments = []
190 return "Entry(name=%s, type=%s)" % (self.name, self.type)
192 def redeclared(self, pos):
193 error(pos, "'%s' does not match previous declaration" % self.name)
194 error(self.pos, "Previous declaration is here")
196 def all_alternatives(self):
197 return [self] + self.overloaded_alternatives
200 # name string Unqualified name
201 # outer_scope Scope or None Enclosing scope
202 # entries {string : Entry} Python name to entry, non-types
203 # const_entries [Entry] Constant entries
204 # type_entries [Entry] Struct/union/enum/typedef/exttype entries
205 # sue_entries [Entry] Struct/union/enum entries
206 # arg_entries [Entry] Function argument entries
207 # var_entries [Entry] User-defined variable entries
208 # pyfunc_entries [Entry] Python function entries
209 # cfunc_entries [Entry] C function entries
210 # c_class_entries [Entry] All extension type entries
211 # cname_to_entry {string : Entry} Temp cname to entry mapping
212 # int_to_entry {int : Entry} Temp cname to entry mapping
213 # return_type PyrexType or None Return type of function owning scope
214 # is_py_class_scope boolean Is a Python class scope
215 # is_c_class_scope boolean Is an extension type scope
216 # is_closure_scope boolean Is a closure scope
217 # is_passthrough boolean Outer scope is passed directly
218 # is_cpp_class_scope boolean Is a C++ class scope
219 # is_property_scope boolean Is a extension type property scope
220 # scope_prefix string Disambiguator for C names
221 # in_cinclude boolean Suppress C declaration code
222 # qualified_name string "modname" or "modname.classname"
223 # pystring_entries [Entry] String const entries newly used as
224 # Python strings in this scope
225 # control_flow ControlFlow Used for keeping track of environment state
226 # nogil boolean In a nogil section
227 # directives dict Helper variable for the recursive
228 # analysis, contains directive values.
229 # is_internal boolean Is only used internally (simpler setup)
231 is_py_class_scope = 0
235 is_cpp_class_scope = 0
236 is_property_scope = 0
243 def __init__(self, name, outer_scope, parent_scope):
244 # The outer_scope is the next scope in the lookup chain.
245 # The parent_scope is used to derive the qualified name of this scope.
247 self.outer_scope = outer_scope
248 self.parent_scope = parent_scope
249 mangled_name = "%d%s_" % (len(name), name)
250 qual_scope = self.qualifying_scope()
252 self.qualified_name = qual_scope.qualify_name(name)
253 self.scope_prefix = qual_scope.scope_prefix + mangled_name
255 self.qualified_name = EncodedString(name)
256 self.scope_prefix = mangled_name
258 self.const_entries = []
259 self.type_entries = []
260 self.sue_entries = []
261 self.arg_entries = []
262 self.var_entries = []
263 self.pyfunc_entries = []
264 self.cfunc_entries = []
265 self.c_class_entries = []
266 self.defined_c_classes = []
267 self.imported_c_classes = {}
268 self.cname_to_entry = {}
269 self.string_to_entry = {}
270 self.identifier_to_entry = {}
271 self.num_to_entry = {}
272 self.obj_to_entry = {}
273 self.pystring_entries = []
274 self.buffer_entries = []
275 self.lambda_defs = []
276 self.control_flow = ControlFlow.LinearControlFlow()
277 self.return_type = None
278 self.id_counters = {}
280 def start_branching(self, pos):
281 self.control_flow = self.control_flow.start_branch(pos)
283 def next_branch(self, pos):
284 self.control_flow = self.control_flow.next_branch(pos)
286 def finish_branching(self, pos):
287 self.control_flow = self.control_flow.finish_branch(pos)
290 return "<%s %s>" % (self.__class__.__name__, self.qualified_name)
292 def qualifying_scope(self):
293 return self.parent_scope
295 def mangle(self, prefix, name = None):
297 return "%s%s%s" % (prefix, self.scope_prefix, name)
299 return self.parent_scope.mangle(prefix, self.name)
301 def mangle_internal(self, name):
302 # Mangle an internal name so as not to clash with any
303 # user-defined name in this scope.
304 prefix = "%s%s_" % (Naming.pyrex_prefix, name)
305 return self.mangle(prefix)
306 #return self.parent_scope.mangle(prefix, self.name)
308 def next_id(self, name=None):
309 # Return a cname fragment that is unique for this module
310 counters = self.global_scope().id_counters
312 count = counters[name] + 1
315 counters[name] = count
318 # unique names don't need a suffix, reoccurrences will get one
320 return '%s%d' % (name, count)
324 def global_scope(self):
325 # Return the module-level scope containing this scope.
326 return self.outer_scope.global_scope()
328 def builtin_scope(self):
329 # Return the module-level scope containing this scope.
330 return self.outer_scope.builtin_scope()
332 def declare(self, name, cname, type, pos, visibility):
333 # Create new entry, and add to dictionary if
334 # name is not None. Reports a warning if already
336 if type.is_buffer and not isinstance(self, LocalScope):
337 error(pos, ERR_BUF_LOCALONLY)
338 if not self.in_cinclude and cname and re.match("^_[_A-Z]+$", cname):
339 # See http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html#Reserved-Names
340 warning(pos, "'%s' is a reserved name in C." % cname, -1)
341 entries = self.entries
342 if name and name in entries:
343 if visibility == 'extern':
344 warning(pos, "'%s' redeclared " % name, 0)
345 elif visibility != 'ignore':
346 error(pos, "'%s' redeclared " % name)
347 entry = Entry(name, cname, type, pos = pos)
348 entry.in_cinclude = self.in_cinclude
350 entry.qualified_name = self.qualify_name(name)
351 # if name in entries and self.is_cpp():
352 # entries[name].overloaded_alternatives.append(entry)
354 # entries[name] = entry
355 entries[name] = entry
357 entry.visibility = visibility
360 def qualify_name(self, name):
361 return EncodedString("%s.%s" % (self.qualified_name, name))
363 def declare_const(self, name, type, value, pos, cname = None, visibility = 'private'):
364 # Add an entry for a named constant.
366 if self.in_cinclude or visibility == 'public':
369 cname = self.mangle(Naming.enum_prefix, name)
370 entry = self.declare(name, cname, type, pos, visibility)
372 entry.value_node = value
375 def declare_type(self, name, type, pos,
376 cname = None, visibility = 'private', defining = 1):
377 # Add an entry for a type definition.
380 entry = self.declare(name, cname, type, pos, visibility)
383 self.type_entries.append(entry)
384 # here we would set as_variable to an object representing this type
387 def declare_typedef(self, name, base_type, pos, cname = None,
388 visibility = 'private'):
390 if self.in_cinclude or visibility == 'public':
393 cname = self.mangle(Naming.type_prefix, name)
395 type = PyrexTypes.create_typedef_type(name, base_type, cname,
396 (visibility == 'extern'))
397 except ValueError, e:
398 error(pos, e.args[0])
399 type = PyrexTypes.error_type
400 entry = self.declare_type(name, type, pos, cname, visibility)
401 type.qualified_name = entry.qualified_name
404 def declare_struct_or_union(self, name, kind, scope,
405 typedef_flag, pos, cname = None, visibility = 'private',
407 # Add an entry for a struct or union definition.
409 if self.in_cinclude or visibility == 'public':
412 cname = self.mangle(Naming.type_prefix, name)
413 entry = self.lookup_here(name)
415 type = PyrexTypes.CStructOrUnionType(
416 name, kind, scope, typedef_flag, cname, packed)
417 entry = self.declare_type(name, type, pos, cname,
418 visibility = visibility, defining = scope is not None)
419 self.sue_entries.append(entry)
422 if not (entry.is_type and entry.type.is_struct_or_union
423 and entry.type.kind == kind):
424 warning(pos, "'%s' redeclared " % name, 0)
425 elif scope and entry.type.scope:
426 warning(pos, "'%s' already defined (ignoring second definition)" % name, 0)
428 self.check_previous_typedef_flag(entry, typedef_flag, pos)
429 self.check_previous_visibility(entry, visibility, pos)
431 entry.type.scope = scope
432 self.type_entries.append(entry)
433 if not scope and not entry.type.scope:
434 self.check_for_illegal_incomplete_ctypedef(typedef_flag, pos)
437 def declare_cpp_class(self, name, scope,
438 pos, cname = None, base_classes = [],
439 visibility = 'extern', templates = None):
440 if visibility != 'extern':
441 error(pos, "C++ classes may only be extern")
444 entry = self.lookup_here(name)
446 type = PyrexTypes.CppClassType(
447 name, scope, cname, base_classes, templates = templates)
448 entry = self.declare_type(name, type, pos, cname,
449 visibility = visibility, defining = scope is not None)
451 if not (entry.is_type and entry.type.is_cpp_class):
452 warning(pos, "'%s' redeclared " % name, 0)
453 elif scope and entry.type.scope:
454 warning(pos, "'%s' already defined (ignoring second definition)" % name, 0)
457 entry.type.scope = scope
458 self.type_entries.append(entry)
459 if templates is not None:
461 template_entry = entry.type.scope.declare(T.name, T.name, T, None, 'extern')
462 template_entry.is_type = 1
464 def declare_inherited_attributes(entry, base_classes):
465 for base_class in base_classes:
466 declare_inherited_attributes(entry, base_class.base_classes)
467 entry.type.scope.declare_inherited_cpp_attributes(base_class.scope)
469 declare_inherited_attributes(entry, base_classes)
470 if self.is_cpp_class_scope:
471 entry.type.namespace = self.outer_scope.lookup(self.name).type
474 def check_previous_typedef_flag(self, entry, typedef_flag, pos):
475 if typedef_flag != entry.type.typedef_flag:
476 error(pos, "'%s' previously declared using '%s'" % (
477 entry.name, ("cdef", "ctypedef")[entry.type.typedef_flag]))
479 def check_previous_visibility(self, entry, visibility, pos):
480 if entry.visibility != visibility:
481 error(pos, "'%s' previously declared as '%s'" % (
482 entry.name, entry.visibility))
484 def declare_enum(self, name, pos, cname, typedef_flag,
485 visibility = 'private'):
488 if self.in_cinclude or visibility == 'public':
491 cname = self.mangle(Naming.type_prefix, name)
492 type = PyrexTypes.CEnumType(name, cname, typedef_flag)
494 type = PyrexTypes.c_anon_enum_type
495 entry = self.declare_type(name, type, pos, cname = cname,
496 visibility = visibility)
497 entry.enum_values = []
498 self.sue_entries.append(entry)
501 def declare_var(self, name, type, pos,
502 cname = None, visibility = 'private', is_cdef = 0):
503 # Add an entry for a variable.
505 if visibility != 'private':
508 cname = self.mangle(Naming.var_prefix, name)
509 if type.is_cpp_class and visibility != 'extern':
510 constructor = type.scope.lookup(u'<init>')
511 if constructor is not None and PyrexTypes.best_match([], constructor.all_alternatives()) is None:
512 error(pos, "C++ class must have a default constructor to be stack allocated")
513 entry = self.declare(name, cname, type, pos, visibility)
514 entry.is_variable = 1
515 self.control_flow.set_state((), (name, 'initialized'), False)
518 def declare_builtin(self, name, pos):
519 return self.outer_scope.declare_builtin(name, pos)
521 def _declare_pyfunction(self, name, pos, visibility='extern', entry=None):
522 if entry and not entry.type.is_cfunction:
523 error(pos, "'%s' already declared" % name)
524 error(entry.pos, "Previous declaration is here")
525 entry = self.declare_var(name, py_object_type, pos, visibility=visibility)
526 entry.signature = pyfunction_signature
527 self.pyfunc_entries.append(entry)
530 def declare_pyfunction(self, name, pos, allow_redefine=False, visibility='extern'):
531 # Add an entry for a Python function.
532 entry = self.lookup_here(name)
533 if not allow_redefine or Options.disable_function_redefinition:
534 return self._declare_pyfunction(name, pos, visibility=visibility, entry=entry)
536 if entry.type.is_unspecified:
537 entry.type = py_object_type
538 elif entry.type is not py_object_type:
539 return self._declare_pyfunction(name, pos, visibility=visibility, entry=entry)
540 else: # declare entry stub
541 self.declare_var(name, py_object_type, pos, visibility=visibility)
542 entry = self.declare_var(None, py_object_type, pos,
543 cname=name, visibility='private')
544 entry.name = EncodedString(name)
545 entry.qualified_name = self.qualify_name(name)
546 entry.signature = pyfunction_signature
547 entry.is_anonymous = True
550 def declare_lambda_function(self, func_cname, pos):
551 # Add an entry for an anonymous Python function.
552 entry = self.declare_var(None, py_object_type, pos,
553 cname=func_cname, visibility='private')
554 entry.name = EncodedString(func_cname)
555 entry.func_cname = func_cname
556 entry.signature = pyfunction_signature
557 entry.is_anonymous = True
560 def add_lambda_def(self, def_node):
561 self.lambda_defs.append(def_node)
563 def register_pyfunction(self, entry):
564 self.pyfunc_entries.append(entry)
566 def declare_cfunction(self, name, type, pos,
567 cname = None, visibility = 'private', defining = 0,
568 api = 0, in_pxd = 0, modifiers = (), utility_code = None):
569 # Add an entry for a C function.
571 if api or visibility != 'private':
574 cname = self.mangle(Naming.func_prefix, name)
575 entry = self.lookup_here(name)
577 if visibility != 'private' and visibility != entry.visibility:
578 warning(pos, "Function '%s' previously declared as '%s'" % (name, entry.visibility), 1)
579 if not entry.type.same_as(type):
580 if visibility == 'extern' and entry.visibility == 'extern':
585 # if all alternatives have different cnames,
586 # it's safe to allow signature overrides
587 for alt_entry in entry.all_alternatives():
588 if not alt_entry.cname or cname == alt_entry.cname:
589 break # cname not unique!
593 temp = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
594 temp.overloaded_alternatives = entry.all_alternatives()
597 warning(pos, "Function signature does not match previous declaration", 1)
600 error(pos, "Function signature does not match previous declaration")
602 entry = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
603 entry.func_cname = cname
604 if in_pxd and visibility != 'extern':
605 entry.defined_in_pxd = 1
608 if not defining and not in_pxd and visibility != 'extern':
609 error(pos, "Non-extern C function '%s' declared but not defined" % name)
611 entry.is_implemented = True
613 entry.func_modifiers = modifiers
614 entry.utility_code = utility_code
617 def add_cfunction(self, name, type, pos, cname, visibility, modifiers):
618 # Add a C function entry without giving it a func_cname.
619 entry = self.declare(name, cname, type, pos, visibility)
620 entry.is_cfunction = 1
622 entry.func_modifiers = modifiers
623 self.cfunc_entries.append(entry)
626 def find(self, name, pos):
627 # Look up name, report error if not found.
628 entry = self.lookup(name)
632 error(pos, "'%s' is not declared" % name)
634 def find_imported_module(self, path, pos):
635 # Look up qualified name, must be a module, report error if not found.
636 # Path is a list of names.
639 entry = scope.find(name, pos)
643 scope = entry.as_module
645 error(pos, "'%s' is not a cimported module" % '.'.join(path))
649 def lookup(self, name):
650 # Look up name in this scope or an enclosing one.
651 # Return None if not found.
652 return (self.lookup_here(name)
653 or (self.outer_scope and self.outer_scope.lookup(name))
656 def lookup_here(self, name):
657 # Look up in this scope only, return None if not found.
658 return self.entries.get(name, None)
660 def lookup_target(self, name):
661 # Look up name in this scope only. Declare as Python
662 # variable if not found.
663 entry = self.lookup_here(name)
665 entry = self.declare_var(name, py_object_type, None)
668 def lookup_type(self, name):
669 entry = self.lookup(name)
670 if entry and entry.is_type:
673 def lookup_operator(self, operator, operands):
674 if operands[0].type.is_cpp_class:
675 obj_type = operands[0].type
676 method = obj_type.scope.lookup("operator%s" % operator)
677 if method is not None:
678 res = PyrexTypes.best_match(operands[1:], method.all_alternatives())
681 function = self.lookup("operator%s" % operator)
684 return PyrexTypes.best_match(operands, function.all_alternatives())
686 def use_utility_code(self, new_code):
687 self.global_scope().use_utility_code(new_code)
689 def generate_library_function_declarations(self, code):
690 # Generate extern decls for C library funcs used.
693 def defines_any(self, names):
694 # Test whether any of the given names are
695 # defined in this scope.
697 if name in self.entries:
701 def infer_types(self):
702 from TypeInference import get_type_inferer
703 get_type_inferer().infer_types(self)
706 outer = self.outer_scope
710 return outer.is_cpp()
712 class PreImportScope(Scope):
714 namespace_cname = Naming.preimport_cname
717 Scope.__init__(self, Options.pre_import, None, None)
719 def declare_builtin(self, name, pos):
720 entry = self.declare(name, name, py_object_type, pos, 'private')
721 entry.is_variable = True
722 entry.is_pyglobal = True
726 class BuiltinScope(Scope):
727 # The builtin namespace.
730 if Options.pre_import is None:
731 Scope.__init__(self, "__builtin__", None, None)
733 Scope.__init__(self, "__builtin__", PreImportScope(), None)
736 for name, definition in self.builtin_entries.iteritems():
737 cname, type = definition
738 self.declare_var(name, type, None, cname)
740 def lookup(self, name, language_level=None):
741 # 'language_level' is passed by ModuleScope
742 if language_level == 3:
745 return Scope.lookup(self, name)
747 def declare_builtin(self, name, pos):
748 if not hasattr(builtins, name):
749 if self.outer_scope is not None:
750 return self.outer_scope.declare_builtin(name, pos)
752 error(pos, "undeclared name not builtin: %s"%name)
754 def declare_builtin_cfunction(self, name, type, cname, python_equiv = None,
755 utility_code = None):
756 # If python_equiv == "*", the Python equivalent has the same name
757 # as the entry, otherwise it has the name specified by python_equiv.
758 name = EncodedString(name)
759 entry = self.declare_cfunction(name, type, None, cname, visibility='extern',
760 utility_code = utility_code)
762 if python_equiv == "*":
765 python_equiv = EncodedString(python_equiv)
766 var_entry = Entry(python_equiv, python_equiv, py_object_type)
767 var_entry.is_variable = 1
768 var_entry.is_builtin = 1
769 var_entry.utility_code = utility_code
770 entry.as_variable = var_entry
773 def declare_builtin_type(self, name, cname, utility_code = None, objstruct_cname = None):
774 name = EncodedString(name)
775 type = PyrexTypes.BuiltinObjectType(name, cname, objstruct_cname)
776 scope = CClassScope(name, outer_scope=None, visibility='extern')
777 scope.directives = {}
779 scope.directives['final'] = True
780 type.set_scope(scope)
781 self.type_names[name] = 1
782 entry = self.declare_type(name, type, None, visibility='extern')
783 entry.utility_code = utility_code
785 var_entry = Entry(name = entry.name,
786 type = self.lookup('type').type, # make sure "type" is the first type declared...
788 cname = "((PyObject*)%s)" % entry.type.typeptr_cname)
789 var_entry.is_variable = 1
790 var_entry.is_cglobal = 1
791 var_entry.is_readonly = 1
792 var_entry.is_builtin = 1
793 var_entry.utility_code = utility_code
794 entry.as_variable = var_entry
798 def builtin_scope(self):
803 "type": ["((PyObject*)&PyType_Type)", py_object_type],
805 "bool": ["((PyObject*)&PyBool_Type)", py_object_type],
806 "int": ["((PyObject*)&PyInt_Type)", py_object_type],
807 "long": ["((PyObject*)&PyLong_Type)", py_object_type],
808 "float": ["((PyObject*)&PyFloat_Type)", py_object_type],
809 "complex":["((PyObject*)&PyComplex_Type)", py_object_type],
811 "bytes": ["((PyObject*)&PyBytes_Type)", py_object_type],
812 "str": ["((PyObject*)&PyString_Type)", py_object_type],
813 "unicode":["((PyObject*)&PyUnicode_Type)", py_object_type],
815 "tuple": ["((PyObject*)&PyTuple_Type)", py_object_type],
816 "list": ["((PyObject*)&PyList_Type)", py_object_type],
817 "dict": ["((PyObject*)&PyDict_Type)", py_object_type],
818 "set": ["((PyObject*)&PySet_Type)", py_object_type],
819 "frozenset": ["((PyObject*)&PyFrozenSet_Type)", py_object_type],
821 "slice": ["((PyObject*)&PySlice_Type)", py_object_type],
822 # "file": ["((PyObject*)&PyFile_Type)", py_object_type], # not in Py3
824 "None": ["Py_None", py_object_type],
825 "False": ["Py_False", py_object_type],
826 "True": ["Py_True", py_object_type],
829 const_counter = 1 # As a temporary solution for compiling code in pxds
831 class ModuleScope(Scope):
832 # module_name string Python name of the module
833 # module_cname string C name of Python module object
834 # #module_dict_cname string C name of module dict object
835 # method_table_cname string C name of method table
836 # doc string Module doc string
837 # doc_cname string C name of module doc string
838 # utility_code_list [UtilityCode] Queuing utility codes for forwarding to Code.py
839 # python_include_files [string] Standard Python headers to be included
840 # include_files [string] Other C headers to be included
841 # string_to_entry {string : Entry} Map string const to entry
842 # identifier_to_entry {string : Entry} Map identifier string const to entry
844 # parent_module Scope Parent in the import namespace
845 # module_entries {string : Entry} For cimport statements
846 # type_names {string : 1} Set of type names (used during parsing)
847 # included_files [string] Cython sources included with 'include'
848 # pxd_file_loaded boolean Corresponding .pxd file has been processed
849 # cimported_modules [ModuleScope] Modules imported with cimport
850 # types_imported {PyrexType : 1} Set of types for which import code generated
851 # has_import_star boolean Module contains import *
852 # cpp boolean Compiling a C++ file
857 def __init__(self, name, parent_module, context):
858 self.parent_module = parent_module
859 outer_scope = context.find_submodule("__builtin__")
860 Scope.__init__(self, name, outer_scope, parent_module)
861 if name != "__init__":
862 self.module_name = name
864 # Treat Spam/__init__.pyx specially, so that when Python loads
865 # Spam/__init__.so, initSpam() is defined.
866 self.module_name = parent_module.module_name
867 self.module_name = EncodedString(self.module_name)
868 self.context = context
869 self.module_cname = Naming.module_cname
870 self.module_dict_cname = Naming.moddict_cname
871 self.method_table_cname = Naming.methtable_cname
873 self.doc_cname = Naming.moddoc_cname
874 self.utility_code_list = []
875 self.module_entries = {}
876 self.python_include_files = ["Python.h"]
877 self.include_files = []
878 self.type_names = dict(outer_scope.type_names)
879 self.pxd_file_loaded = 0
880 self.cimported_modules = []
881 self.types_imported = {}
882 self.included_files = []
883 self.has_extern_class = 0
884 self.cached_builtins = []
885 self.undeclared_cached_builtins = []
886 self.namespace_cname = self.module_cname
887 for name in ['__builtins__', '__name__', '__file__', '__doc__']:
888 self.declare_var(EncodedString(name), py_object_type, None)
890 def qualifying_scope(self):
891 return self.parent_module
893 def global_scope(self):
896 def lookup(self, name):
897 entry = self.lookup_here(name)
898 if entry is not None:
900 return self.outer_scope.lookup(name, language_level = self.context.language_level)
902 def declare_builtin(self, name, pos):
903 if not hasattr(builtins, name) and name != 'xrange':
904 # 'xrange' is special cased in Code.py
905 if self.has_import_star:
906 entry = self.declare_var(name, py_object_type, pos)
908 elif self.outer_scope is not None:
909 return self.outer_scope.declare_builtin(name, pos)
911 error(pos, "undeclared name not builtin: %s"%name)
912 if Options.cache_builtins:
913 for entry in self.cached_builtins:
914 if entry.name == name:
916 entry = self.declare(None, None, py_object_type, pos, 'private')
917 if Options.cache_builtins:
921 entry.cname = Naming.builtin_prefix + name
922 self.cached_builtins.append(entry)
923 self.undeclared_cached_builtins.append(entry)
928 def find_module(self, module_name, pos):
929 # Find a module in the import namespace, interpreting
930 # relative imports relative to this module's parent.
931 # Finds and parses the module's .pxd file if the module
932 # has not been referenced before.
933 return self.global_scope().context.find_module(
934 module_name, relative_to = self.parent_module, pos = pos)
936 def find_submodule(self, name):
937 # Find and return scope for a submodule of this module,
938 # creating a new empty one if necessary. Doesn't parse .pxd.
939 scope = self.lookup_submodule(name)
941 scope = ModuleScope(name,
942 parent_module = self, context = self.context)
943 self.module_entries[name] = scope
946 def lookup_submodule(self, name):
947 # Return scope for submodule of this module, or None.
948 return self.module_entries.get(name, None)
950 def add_include_file(self, filename):
951 if filename not in self.python_include_files \
952 and filename not in self.include_files:
953 self.include_files.append(filename)
955 def add_imported_module(self, scope):
956 if scope not in self.cimported_modules:
957 for filename in scope.include_files:
958 self.add_include_file(filename)
959 self.cimported_modules.append(scope)
960 for m in scope.cimported_modules:
961 self.add_imported_module(m)
963 def add_imported_entry(self, name, entry, pos):
964 if entry not in self.entries:
965 self.entries[name] = entry
967 warning(pos, "'%s' redeclared " % name, 0)
969 def declare_module(self, name, scope, pos):
970 # Declare a cimported module. This is represented as a
971 # Python module-level variable entry with a module
972 # scope attached to it. Reports an error and returns
973 # None if previously declared as something else.
974 entry = self.lookup_here(name)
976 if entry.is_pyglobal and entry.as_module is scope:
977 return entry # Already declared as the same module
978 if not (entry.is_pyglobal and not entry.as_module):
979 # SAGE -- I put this here so Pyrex
980 # cimport's work across directories.
981 # Currently it tries to multiply define
982 # every module appearing in an import list.
983 # It shouldn't be an error for a module
984 # name to appear again, and indeed the generated
985 # code compiles fine.
987 warning(pos, "'%s' redeclared " % name, 0)
990 entry = self.declare_var(name, py_object_type, pos)
991 entry.as_module = scope
992 self.add_imported_module(scope)
995 def declare_var(self, name, type, pos,
996 cname = None, visibility = 'private', is_cdef = 0):
997 # Add an entry for a global variable. If it is a Python
998 # object type, and not declared with cdef, it will live
999 # in the module dictionary, otherwise it will be a C
1001 entry = Scope.declare_var(self, name, type, pos,
1002 cname, visibility, is_cdef)
1003 if not visibility in ('private', 'public', 'extern'):
1004 error(pos, "Module-level variable cannot be declared %s" % visibility)
1006 if type is unspecified_type:
1007 type = py_object_type
1008 if not (type.is_pyobject and not type.is_extension_type):
1009 raise InternalError(
1010 "Non-cdef global variable is not a generic Python object")
1011 entry.is_pyglobal = 1
1013 entry.is_cglobal = 1
1014 if entry.type.is_pyobject:
1016 self.var_entries.append(entry)
1019 def declare_global(self, name, pos):
1020 entry = self.lookup_here(name)
1022 self.declare_var(name, py_object_type, pos)
1024 def use_utility_code(self, new_code):
1025 if new_code is not None:
1026 self.utility_code_list.append(new_code)
1028 def declare_c_class(self, name, pos, defining = 0, implementing = 0,
1029 module_name = None, base_type = None, objstruct_cname = None,
1030 typeobj_cname = None, visibility = 'private', typedef_flag = 0, api = 0,
1031 buffer_defaults = None):
1032 # If this is a non-extern typedef class, expose the typedef, but use
1033 # the non-typedef struct internally to avoid needing forward
1034 # declarations for anonymous structs.
1035 if typedef_flag and visibility != 'extern':
1036 if visibility != 'public':
1037 warning(pos, "ctypedef only valid for public and extern classes", 2)
1038 objtypedef_cname = objstruct_cname
1041 objtypedef_cname = None
1043 # Look for previous declaration as a type
1045 entry = self.lookup_here(name)
1048 if not (entry.is_type and type.is_extension_type):
1049 entry = None # Will cause redeclaration and produce an error
1052 if typedef_flag and (not scope or scope.defined):
1053 self.check_previous_typedef_flag(entry, typedef_flag, pos)
1054 if (scope and scope.defined) or (base_type and type.base_type):
1055 if base_type and base_type is not type.base_type:
1056 error(pos, "Base type does not match previous declaration")
1057 if base_type and not type.base_type:
1058 type.base_type = base_type
1060 # Make a new entry if needed
1063 type = PyrexTypes.PyExtensionType(name, typedef_flag, base_type, visibility == 'extern')
1065 type.buffer_defaults = buffer_defaults
1066 if objtypedef_cname is not None:
1067 type.objtypedef_cname = objtypedef_cname
1068 if visibility == 'extern':
1069 type.module_name = module_name
1071 type.module_name = self.qualified_name
1072 type.typeptr_cname = self.mangle(Naming.typeptr_prefix, name)
1073 entry = self.declare_type(name, type, pos, visibility = visibility,
1075 entry.is_cclass = True
1077 type.objstruct_cname = objstruct_cname
1078 elif not entry.in_cinclude:
1079 type.objstruct_cname = self.mangle(Naming.objstruct_prefix, name)
1082 "Object name required for 'public' or 'extern' C class")
1083 self.attach_var_entry_to_c_class(entry)
1084 self.c_class_entries.append(entry)
1086 # Check for re-definition and create scope if needed
1089 if defining or implementing:
1090 scope = CClassScope(name = name, outer_scope = self,
1091 visibility = visibility)
1092 if base_type and base_type.scope:
1093 scope.declare_inherited_c_attributes(base_type.scope)
1094 type.set_scope(scope)
1095 self.type_entries.append(entry)
1097 self.check_for_illegal_incomplete_ctypedef(typedef_flag, pos)
1099 if defining and type.scope.defined:
1100 error(pos, "C class '%s' already defined" % name)
1101 elif implementing and type.scope.implemented:
1102 error(pos, "C class '%s' already implemented" % name)
1104 # Fill in options, checking for compatibility with any previous declaration
1107 entry.defined_in_pxd = 1
1108 if implementing: # So that filenames in runtime exceptions refer to
1109 entry.pos = pos # the .pyx file and not the .pxd file
1110 if visibility != 'private' and entry.visibility != visibility:
1111 error(pos, "Class '%s' previously declared as '%s'"
1112 % (name, entry.visibility))
1116 if type.objstruct_cname and type.objstruct_cname != objstruct_cname:
1117 error(pos, "Object struct name differs from previous declaration")
1118 type.objstruct_cname = objstruct_cname
1120 if type.typeobj_cname and type.typeobj_cname != typeobj_cname:
1121 error(pos, "Type object name differs from previous declaration")
1122 type.typeobj_cname = typeobj_cname
1124 # Return new or existing entry
1128 def check_for_illegal_incomplete_ctypedef(self, typedef_flag, pos):
1129 if typedef_flag and not self.in_cinclude:
1130 error(pos, "Forward-referenced type must use 'cdef', not 'ctypedef'")
1132 def allocate_vtable_names(self, entry):
1133 # If extension type has a vtable, allocate vtable struct and
1134 # slot names for it.
1136 if type.base_type and type.base_type.vtabslot_cname:
1137 #print "...allocating vtabslot_cname because base type has one" ###
1138 type.vtabslot_cname = "%s.%s" % (
1139 Naming.obj_base_cname, type.base_type.vtabslot_cname)
1140 elif type.scope and type.scope.cfunc_entries:
1141 # one special case here: when inheriting from builtin
1142 # types, the methods may also be built-in, in which
1143 # case they won't need a vtable
1144 entry_count = len(type.scope.cfunc_entries)
1145 base_type = type.base_type
1147 # FIXME: this will break if we ever get non-inherited C methods
1148 if not base_type.scope or entry_count > len(base_type.scope.cfunc_entries):
1150 if base_type.is_builtin_type:
1151 # builtin base type defines all methods => no vtable needed
1153 base_type = base_type.base_type
1154 #print "...allocating vtabslot_cname because there are C methods" ###
1155 type.vtabslot_cname = Naming.vtabslot_cname
1156 if type.vtabslot_cname:
1157 #print "...allocating other vtable related cnames" ###
1158 type.vtabstruct_cname = self.mangle(Naming.vtabstruct_prefix, entry.name)
1159 type.vtabptr_cname = self.mangle(Naming.vtabptr_prefix, entry.name)
1161 def check_c_classes_pxd(self):
1162 # Performs post-analysis checking and finishing up of extension types
1163 # being implemented in this module. This is called only for the .pxd.
1165 # Checks all extension types declared in this scope to
1168 # * The extension type is fully declared
1170 # Also allocates a name for the vtable if needed.
1172 for entry in self.c_class_entries:
1174 if not entry.type.scope:
1175 error(entry.pos, "C class '%s' is declared but not defined" % entry.name)
1177 def check_c_class(self, entry):
1180 visibility = entry.visibility
1183 error(entry.pos, "C class '%s' is declared but not defined" % name)
1184 # Generate typeobj_cname
1185 if visibility != 'extern' and not type.typeobj_cname:
1186 type.typeobj_cname = self.mangle(Naming.typeobj_prefix, name)
1187 ## Generate typeptr_cname
1188 #type.typeptr_cname = self.mangle(Naming.typeptr_prefix, name)
1189 # Check C methods defined
1191 for method_entry in type.scope.cfunc_entries:
1192 if not method_entry.is_inherited and not method_entry.func_cname:
1193 error(method_entry.pos, "C method '%s' is declared but not defined" %
1195 # Allocate vtable name if necessary
1196 if type.vtabslot_cname:
1197 #print "ModuleScope.check_c_classes: allocating vtable cname for", self ###
1198 type.vtable_cname = self.mangle(Naming.vtable_prefix, entry.name)
1200 def check_c_classes(self):
1201 # Performs post-analysis checking and finishing up of extension types
1202 # being implemented in this module. This is called only for the main
1203 # .pyx file scope, not for cimported .pxd scopes.
1205 # Checks all extension types declared in this scope to
1208 # * The extension type is implemented
1209 # * All required object and type names have been specified or generated
1210 # * All non-inherited C methods are implemented
1212 # Also allocates a name for the vtable if needed.
1214 debug_check_c_classes = 0
1215 if debug_check_c_classes:
1216 print("Scope.check_c_classes: checking scope " + self.qualified_name)
1217 for entry in self.c_class_entries:
1218 if debug_check_c_classes:
1219 print("...entry %s %s" % (entry.name, entry))
1220 print("......type = ", entry.type)
1221 print("......visibility = ", entry.visibility)
1222 self.check_c_class(entry)
1224 def check_c_functions(self):
1225 # Performs post-analysis checking making sure all
1226 # defined c functions are actually implemented.
1227 for name, entry in self.entries.items():
1228 if entry.is_cfunction:
1229 if (entry.defined_in_pxd
1230 and entry.scope is self
1231 and entry.visibility != 'extern'
1232 and not entry.in_cinclude
1233 and not entry.is_implemented):
1234 error(entry.pos, "Non-extern C function '%s' declared but not defined" % name)
1236 def attach_var_entry_to_c_class(self, entry):
1237 # The name of an extension class has to serve as both a type
1238 # name and a variable name holding the type object. It is
1239 # represented in the symbol table by a type entry with a
1240 # variable entry attached to it. For the variable entry,
1241 # we use a read-only C global variable whose name is an
1242 # expression that refers to the type object.
1244 var_entry = Entry(name = entry.name,
1245 type = Builtin.type_type,
1247 cname = "((PyObject*)%s)" % entry.type.typeptr_cname)
1248 var_entry.is_variable = 1
1249 var_entry.is_cglobal = 1
1250 var_entry.is_readonly = 1
1251 entry.as_variable = var_entry
1256 def infer_types(self):
1257 from TypeInference import PyObjectTypeInferer
1258 PyObjectTypeInferer().infer_types(self)
1260 class LocalScope(Scope):
1262 def __init__(self, name, outer_scope, parent_scope = None):
1263 if parent_scope is None:
1264 parent_scope = outer_scope
1265 Scope.__init__(self, name, outer_scope, parent_scope)
1267 def mangle(self, prefix, name):
1268 return prefix + name
1270 def declare_arg(self, name, type, pos):
1271 # Add an entry for an argument of a function.
1272 cname = self.mangle(Naming.var_prefix, name)
1273 entry = self.declare(name, cname, type, pos, 'private')
1274 entry.is_variable = 1
1275 if type.is_pyobject:
1278 #entry.borrowed = 1 # Not using borrowed arg refs for now
1279 self.arg_entries.append(entry)
1280 self.control_flow.set_state((), (name, 'source'), 'arg')
1283 def declare_var(self, name, type, pos,
1284 cname = None, visibility = 'private', is_cdef = 0):
1285 # Add an entry for a local variable.
1286 if visibility in ('public', 'readonly'):
1287 error(pos, "Local variable cannot be declared %s" % visibility)
1288 entry = Scope.declare_var(self, name, type, pos,
1289 cname, visibility, is_cdef)
1290 if type.is_pyobject and not Options.init_local_none:
1292 entry.init_to_none = (type.is_pyobject or type.is_unspecified) and Options.init_local_none
1294 self.var_entries.append(entry)
1297 def declare_global(self, name, pos):
1298 # Pull entry from global scope into local scope.
1299 if self.lookup_here(name):
1300 warning(pos, "'%s' redeclared ", 0)
1302 entry = self.global_scope().lookup_target(name)
1303 self.entries[name] = entry
1305 def declare_nonlocal(self, name, pos):
1306 # Pull entry from outer scope into local scope
1307 orig_entry = self.lookup_here(name)
1308 if orig_entry and orig_entry.scope is self and not orig_entry.from_closure:
1309 error(pos, "'%s' redeclared as nonlocal" % name)
1311 entry = self.lookup(name)
1312 if entry is None or not entry.from_closure:
1313 error(pos, "no binding for nonlocal '%s' found" % name)
1315 def lookup(self, name):
1316 # Look up name in this scope or an enclosing one.
1317 # Return None if not found.
1318 entry = Scope.lookup(self, name)
1319 if entry is not None:
1320 if entry.scope is not self and entry.scope.is_closure_scope:
1321 if hasattr(entry.scope, "scope_class"):
1322 raise InternalError, "lookup() after scope class created."
1323 # The actual c fragment for the different scopes differs
1324 # on the outside and inside, so we make a new entry
1325 entry.in_closure = True
1326 # Would it be better to declare_var here?
1327 inner_entry = Entry(entry.name, entry.cname, entry.type, entry.pos)
1328 inner_entry.scope = self
1329 inner_entry.is_variable = True
1330 inner_entry.outer_entry = entry
1331 inner_entry.from_closure = True
1332 self.entries[name] = inner_entry
1336 def mangle_closure_cnames(self, outer_scope_cname):
1337 for entry in self.entries.values():
1338 if entry.from_closure:
1339 cname = entry.outer_entry.cname
1340 if self.is_passthrough:
1343 if cname.startswith(Naming.cur_scope_cname):
1344 cname = cname[len(Naming.cur_scope_cname)+2:]
1345 entry.cname = "%s->%s" % (outer_scope_cname, cname)
1346 elif entry.in_closure:
1347 entry.original_cname = entry.cname
1348 entry.cname = "%s->%s" % (Naming.cur_scope_cname, entry.cname)
1350 class GeneratorExpressionScope(Scope):
1351 """Scope for generator expressions and comprehensions. As opposed
1352 to generators, these can be easily inlined in some cases, so all
1353 we really need is a scope that holds the loop variable(s).
1355 def __init__(self, outer_scope):
1356 name = outer_scope.global_scope().next_id(Naming.genexpr_id_ref)
1357 Scope.__init__(self, name, outer_scope, outer_scope)
1358 self.directives = outer_scope.directives
1359 self.genexp_prefix = "%s%d%s" % (Naming.pyrex_prefix, len(name), name)
1361 def mangle(self, prefix, name):
1362 return '%s%s' % (self.genexp_prefix, self.parent_scope.mangle(self, prefix, name))
1364 def declare_var(self, name, type, pos,
1365 cname = None, visibility = 'private', is_cdef = True):
1366 if type is unspecified_type:
1367 # if the outer scope defines a type for this variable, inherit it
1368 outer_entry = self.outer_scope.lookup(name)
1369 if outer_entry and outer_entry.is_variable:
1370 type = outer_entry.type # may still be 'unspecified_type' !
1371 # the parent scope needs to generate code for the variable, but
1372 # this scope must hold its name exclusively
1373 cname = '%s%s' % (self.genexp_prefix, self.parent_scope.mangle(Naming.var_prefix, name))
1374 entry = self.declare(name, cname, type, pos, visibility)
1375 entry.is_variable = 1
1376 self.var_entries.append(entry)
1377 self.entries[name] = entry
1381 class ClosureScope(LocalScope):
1383 is_closure_scope = True
1385 def __init__(self, name, scope_name, outer_scope):
1386 LocalScope.__init__(self, name, outer_scope)
1387 self.closure_cname = "%s%s" % (Naming.closure_scope_prefix, scope_name)
1389 # def mangle_closure_cnames(self, scope_var):
1390 # for entry in self.entries.values() + self.temp_entries:
1391 # entry.in_closure = 1
1392 # LocalScope.mangle_closure_cnames(self, scope_var)
1394 # def mangle(self, prefix, name):
1395 # return "%s->%s" % (self.cur_scope_cname, name)
1396 # return "%s->%s" % (self.closure_cname, name)
1398 def declare_pyfunction(self, name, pos, allow_redefine=False):
1399 return LocalScope.declare_pyfunction(self, name, pos, allow_redefine, visibility='private')
1401 class StructOrUnionScope(Scope):
1402 # Namespace of a C struct or union.
1404 def __init__(self, name="?"):
1405 Scope.__init__(self, name, None, None)
1407 def declare_var(self, name, type, pos,
1408 cname = None, visibility = 'private', is_cdef = 0, allow_pyobject = 0):
1409 # Add an entry for an attribute.
1412 if visibility == 'private':
1413 cname = c_safe_identifier(cname)
1414 if type.is_cfunction:
1415 type = PyrexTypes.CPtrType(type)
1416 entry = self.declare(name, cname, type, pos, visibility)
1417 entry.is_variable = 1
1418 self.var_entries.append(entry)
1419 if type.is_pyobject and not allow_pyobject:
1421 "C struct/union member cannot be a Python object")
1422 if visibility != 'private':
1424 "C struct/union member cannot be declared %s" % visibility)
1427 def declare_cfunction(self, name, type, pos,
1428 cname = None, visibility = 'private', defining = 0,
1429 api = 0, in_pxd = 0, modifiers = ()): # currently no utility code ...
1430 return self.declare_var(name, type, pos, cname, visibility)
1432 class ClassScope(Scope):
1433 # Abstract base class for namespace of
1434 # Python class or extension type.
1436 # class_name string Pyrex name of the class
1437 # scope_prefix string Additional prefix for names
1438 # declared in the class
1439 # doc string or None Doc string
1441 def __init__(self, name, outer_scope):
1442 Scope.__init__(self, name, outer_scope, outer_scope)
1443 self.class_name = name
1446 def lookup(self, name):
1447 entry = Scope.lookup(self, name)
1450 if name == "classmethod":
1451 # We don't want to use the builtin classmethod here 'cause it won't do the
1452 # right thing in this scope (as the class memebers aren't still functions).
1453 # Don't want to add a cfunction to this scope 'cause that would mess with
1454 # the type definition, so we just return the right entry.
1455 self.use_utility_code(classmethod_utility_code)
1458 "__Pyx_Method_ClassMethod",
1459 PyrexTypes.CFuncType(
1461 [PyrexTypes.CFuncTypeArg("", py_object_type, None)], 0, 0))
1462 entry.is_cfunction = 1
1466 class PyClassScope(ClassScope):
1467 # Namespace of a Python class.
1469 # class_obj_cname string C variable holding class object
1471 is_py_class_scope = 1
1473 def declare_var(self, name, type, pos,
1474 cname = None, visibility = 'private', is_cdef = 0):
1475 if type is unspecified_type:
1476 type = py_object_type
1477 # Add an entry for a class attribute.
1478 entry = Scope.declare_var(self, name, type, pos,
1479 cname, visibility, is_cdef)
1480 entry.is_pyglobal = 1
1481 entry.is_pyclass_attr = 1
1484 def declare_nonlocal(self, name, pos):
1485 # Pull entry from outer scope into local scope
1486 orig_entry = self.lookup_here(name)
1487 if orig_entry and orig_entry.scope is self and not orig_entry.from_closure:
1488 error(pos, "'%s' redeclared as nonlocal" % name)
1490 entry = self.lookup(name)
1492 error(pos, "no binding for nonlocal '%s' found" % name)
1494 self.entries[name] = entry
1496 def add_default_value(self, type):
1497 return self.outer_scope.add_default_value(type)
1500 class CClassScope(ClassScope):
1501 # Namespace of an extension type.
1503 # parent_type CClassType
1504 # #typeobj_cname string or None
1505 # #objstruct_cname string
1506 # method_table_cname string
1507 # getset_table_cname string
1508 # has_pyobject_attrs boolean Any PyObject attributes?
1509 # property_entries [Entry]
1510 # defined boolean Defined in .pxd file
1511 # implemented boolean Defined in .pyx file
1512 # inherited_var_entries [Entry] Adapted var entries from base class
1514 is_c_class_scope = 1
1516 def __init__(self, name, outer_scope, visibility):
1517 ClassScope.__init__(self, name, outer_scope)
1518 if visibility != 'extern':
1519 self.method_table_cname = outer_scope.mangle(Naming.methtab_prefix, name)
1520 self.getset_table_cname = outer_scope.mangle(Naming.gstab_prefix, name)
1521 self.has_pyobject_attrs = 0
1522 self.property_entries = []
1523 self.inherited_var_entries = []
1525 self.implemented = 0
1528 # If the type or any of its base types have Python-valued
1529 # C attributes, then it needs to participate in GC.
1530 return self.has_pyobject_attrs or \
1531 (self.parent_type.base_type and
1532 self.parent_type.base_type.scope is not None and
1533 self.parent_type.base_type.scope.needs_gc())
1535 def declare_var(self, name, type, pos,
1536 cname = None, visibility = 'private', is_cdef = 0):
1538 # Add an entry for an attribute.
1541 "C attributes cannot be added in implementation part of"
1542 " extension type defined in a pxd")
1543 if get_special_method_signature(name):
1545 "The name '%s' is reserved for a special method."
1549 if visibility == 'private':
1550 cname = c_safe_identifier(cname)
1551 if type.is_cpp_class and visibility != 'extern':
1552 error(pos, "C++ classes not allowed as members of an extension type, use a pointer or reference instead")
1553 entry = self.declare(name, cname, type, pos, visibility)
1554 entry.is_variable = 1
1555 self.var_entries.append(entry)
1556 if type.is_pyobject:
1557 self.has_pyobject_attrs = 1
1558 if visibility not in ('private', 'public', 'readonly'):
1560 "Attribute of extension type cannot be declared %s" % visibility)
1561 if visibility in ('public', 'readonly'):
1562 if name == "__weakref__":
1563 error(pos, "Special attribute __weakref__ cannot be exposed to Python")
1564 if not type.is_pyobject:
1565 if (not type.create_to_py_utility_code(self) or
1566 (visibility=='public' and not
1567 type.create_from_py_utility_code(self))):
1569 "C attribute of type '%s' cannot be accessed from Python" % type)
1572 if type is unspecified_type:
1573 type = py_object_type
1574 # Add an entry for a class attribute.
1575 entry = Scope.declare_var(self, name, type, pos,
1576 cname, visibility, is_cdef)
1578 entry.is_pyglobal = 1 # xxx: is_pyglobal changes behaviour in so many places that
1579 # I keep it in for now. is_member should be enough
1581 self.namespace_cname = "(PyObject *)%s" % self.parent_type.typeptr_cname
1585 def declare_pyfunction(self, name, pos, allow_redefine=False):
1586 # Add an entry for a method.
1587 if name in ('__eq__', '__ne__', '__lt__', '__gt__', '__le__', '__ge__'):
1588 error(pos, "Special method %s must be implemented via __richcmp__" % name)
1589 if name == "__new__":
1590 error(pos, "__new__ method of extension type will change semantics "
1591 "in a future version of Pyrex and Cython. Use __cinit__ instead.")
1592 entry = self.declare_var(name, py_object_type, pos, visibility='extern')
1593 special_sig = get_special_method_signature(name)
1595 # Special methods get put in the method table with a particular
1596 # signature declared in advance.
1597 entry.signature = special_sig
1598 entry.is_special = 1
1600 entry.signature = pymethod_signature
1601 entry.is_special = 0
1603 self.pyfunc_entries.append(entry)
1606 def lookup_here(self, name):
1607 if name == "__new__":
1608 name = EncodedString("__cinit__")
1609 return ClassScope.lookup_here(self, name)
1611 def declare_cfunction(self, name, type, pos,
1612 cname = None, visibility = 'private',
1613 defining = 0, api = 0, in_pxd = 0, modifiers = (),
1614 utility_code = None):
1615 if get_special_method_signature(name):
1616 error(pos, "Special methods must be declared with 'def', not 'cdef'")
1619 error(pos, "C method has no self argument")
1620 elif not self.parent_type.assignable_from(args[0].type):
1621 error(pos, "Self argument (%s) of C method '%s' does not match parent type (%s)" %
1622 (args[0].type, name, self.parent_type))
1623 entry = self.lookup_here(name)
1625 if not entry.is_cfunction:
1626 warning(pos, "'%s' redeclared " % name, 0)
1628 if defining and entry.func_cname:
1629 error(pos, "'%s' already defined" % name)
1630 #print "CClassScope.declare_cfunction: checking signature" ###
1631 if type.same_c_signature_as(entry.type, as_cmethod = 1) and type.nogil == entry.type.nogil:
1633 elif type.compatible_signature_with(entry.type, as_cmethod = 1) and type.nogil == entry.type.nogil:
1634 entry = self.add_cfunction(name, type, pos, cname or name, visibility='ignore', modifiers=modifiers)
1637 error(pos, "Signature not compatible with previous declaration")
1638 error(entry.pos, "Previous declaration is here")
1642 "C method '%s' not previously declared in definition part of"
1643 " extension type" % name)
1644 entry = self.add_cfunction(name, type, pos, cname or name,
1645 visibility, modifiers)
1647 entry.func_cname = self.mangle(Naming.func_prefix, name)
1648 entry.utility_code = utility_code
1651 def add_cfunction(self, name, type, pos, cname, visibility, modifiers):
1652 # Add a cfunction entry without giving it a func_cname.
1653 prev_entry = self.lookup_here(name)
1654 entry = ClassScope.add_cfunction(self, name, type, pos, cname,
1655 visibility, modifiers)
1656 entry.is_cmethod = 1
1657 entry.prev_entry = prev_entry
1660 def declare_builtin_cfunction(self, name, type, cname, utility_code = None):
1661 # overridden methods of builtin types still have their Python
1662 # equivalent that must be accessible to support bound methods
1663 name = EncodedString(name)
1664 entry = self.declare_cfunction(name, type, None, cname, visibility='extern',
1665 utility_code = utility_code)
1666 var_entry = Entry(name, name, py_object_type)
1667 var_entry.is_variable = 1
1668 var_entry.is_builtin = 1
1669 var_entry.utility_code = utility_code
1670 entry.as_variable = var_entry
1673 def declare_property(self, name, doc, pos):
1674 entry = self.lookup_here(name)
1676 entry = self.declare(name, name, py_object_type, pos, 'private')
1677 entry.is_property = 1
1679 entry.scope = PropertyScope(name,
1680 outer_scope = self.global_scope(), parent_scope = self)
1681 entry.scope.parent_type = self.parent_type
1682 self.property_entries.append(entry)
1685 def declare_inherited_c_attributes(self, base_scope):
1686 # Declare entries for all the C attributes of an
1687 # inherited type, with cnames modified appropriately
1688 # to work with this type.
1690 return "%s.%s" % (Naming.obj_base_cname, base_entry.cname)
1692 base_scope.inherited_var_entries + base_scope.var_entries:
1693 entry = self.declare(base_entry.name, adapt(base_entry.cname),
1694 base_entry.type, None, 'private')
1695 entry.is_variable = 1
1696 self.inherited_var_entries.append(entry)
1697 for base_entry in base_scope.cfunc_entries:
1698 entry = self.add_cfunction(base_entry.name, base_entry.type,
1699 base_entry.pos, adapt(base_entry.cname),
1700 base_entry.visibility, base_entry.func_modifiers)
1701 entry.is_inherited = 1
1704 class CppClassScope(Scope):
1705 # Namespace of a C++ class.
1707 is_cpp_class_scope = 1
1709 default_constructor = None
1711 def __init__(self, name, outer_scope):
1712 Scope.__init__(self, name, outer_scope, None)
1713 self.directives = outer_scope.directives
1714 self.inherited_var_entries = []
1716 def declare_var(self, name, type, pos,
1717 cname = None, visibility = 'extern', is_cdef = 0, allow_pyobject = 0):
1718 # Add an entry for an attribute.
1721 if type.is_cfunction:
1722 type = PyrexTypes.CPtrType(type)
1723 entry = self.declare(name, cname, type, pos, visibility)
1724 entry.is_variable = 1
1725 self.var_entries.append(entry)
1726 if type.is_pyobject and not allow_pyobject:
1728 "C++ class member cannot be a Python object")
1731 def check_base_default_constructor(self, pos):
1732 # Look for default constructors in all base classes.
1733 if self.default_constructor is None:
1734 entry = self.lookup(self.name)
1735 if len(entry.type.base_classes) == 0:
1736 self.default_constructor = True
1738 for base_class in entry.type.base_classes:
1739 temp_entry = base_class.scope.lookup_here("<init>")
1741 if temp_entry is None:
1743 for alternative in temp_entry.all_alternatives():
1744 type = alternative.type
1746 type = type.base_type
1747 if len(type.args) == 0:
1751 self.default_constructor = temp_entry.scope.name
1752 error(pos, "no matching function for call to " \
1753 "%s::%s()" % (temp_entry.scope.name, temp_entry.scope.name))
1754 elif not self.default_constructor:
1755 error(pos, "no matching function for call to %s::%s()" %
1756 (self.default_constructor, self.default_constructor))
1758 def declare_cfunction(self, name, type, pos,
1759 cname = None, visibility = 'extern', defining = 0,
1760 api = 0, in_pxd = 0, modifiers = (), utility_code = None):
1761 if name == self.name.split('::')[-1] and cname is None:
1762 self.check_base_default_constructor(pos)
1764 type.return_type = self.lookup(self.name).type
1765 prev_entry = self.lookup_here(name)
1766 entry = self.declare_var(name, type, pos, cname, visibility)
1768 entry.overloaded_alternatives = prev_entry.all_alternatives()
1769 entry.utility_code = utility_code
1772 def declare_inherited_cpp_attributes(self, base_scope):
1773 # Declare entries for all the C++ attributes of an
1774 # inherited type, with cnames modified appropriately
1775 # to work with this type.
1777 base_scope.inherited_var_entries + base_scope.var_entries:
1778 #contructor is not inherited
1779 if base_entry.name == "<init>":
1781 #print base_entry.name, self.entries
1782 if base_entry.name in self.entries:
1784 entry = self.declare(base_entry.name, base_entry.cname,
1785 base_entry.type, None, 'extern')
1786 entry.is_variable = 1
1787 self.inherited_var_entries.append(entry)
1788 for base_entry in base_scope.cfunc_entries:
1789 entry = self.declare_cfunction(base_entry.name, base_entry.type,
1790 base_entry.pos, base_entry.cname,
1791 base_entry.visibility, base_entry.func_modifiers,
1792 utility_code = base_entry.utility_code)
1793 entry.is_inherited = 1
1795 def specialize(self, values):
1796 scope = CppClassScope(self.name, self.outer_scope)
1797 for entry in self.entries.values():
1799 scope.declare_type(entry.name,
1800 entry.type.specialize(values),
1804 # scope.declare_var(entry.name,
1805 # entry.type.specialize(values),
1809 for e in entry.all_alternatives():
1810 scope.declare_cfunction(e.name,
1811 e.type.specialize(values),
1814 utility_code = e.utility_code)
1817 def add_include_file(self, filename):
1818 self.outer_scope.add_include_file(filename)
1820 class PropertyScope(Scope):
1821 # Scope holding the __get__, __set__ and __del__ methods for
1822 # a property of an extension type.
1824 # parent_type PyExtensionType The type to which the property belongs
1826 is_property_scope = 1
1828 def declare_pyfunction(self, name, pos, allow_redefine=False):
1829 # Add an entry for a method.
1830 signature = get_property_accessor_signature(name)
1832 entry = self.declare(name, name, py_object_type, pos, 'private')
1833 entry.is_special = 1
1834 entry.signature = signature
1837 error(pos, "Only __get__, __set__ and __del__ methods allowed "
1838 "in a property declaration")
1842 # Should this go elsewhere (and then get imported)?
1843 #------------------------------------------------------------------------------------
1845 classmethod_utility_code = Code.UtilityCode(
1847 #include "descrobject.h"
1848 static PyObject* __Pyx_Method_ClassMethod(PyObject *method); /*proto*/
1851 static PyObject* __Pyx_Method_ClassMethod(PyObject *method) {
1852 /* It appears that PyMethodDescr_Type is not anywhere exposed in the Python/C API */
1853 static PyTypeObject *methoddescr_type = NULL;
1854 if (methoddescr_type == NULL) {
1855 PyObject *meth = __Pyx_GetAttrString((PyObject*)&PyList_Type, "append");
1856 if (!meth) return NULL;
1857 methoddescr_type = Py_TYPE(meth);
1860 if (PyObject_TypeCheck(method, methoddescr_type)) { /* cdef classes */
1861 PyMethodDescrObject *descr = (PyMethodDescrObject *)method;
1862 #if PY_VERSION_HEX < 0x03020000
1863 PyTypeObject *d_type = descr->d_type;
1865 PyTypeObject *d_type = descr->d_common.d_type;
1867 return PyDescr_NewClassMethod(d_type, descr->d_method);
1869 else if (PyMethod_Check(method)) { /* python classes */
1870 return PyClassMethod_New(PyMethod_GET_FUNCTION(method));
1872 else if (PyCFunction_Check(method)) {
1873 return PyClassMethod_New(method);
1875 #ifdef __pyx_binding_PyCFunctionType_USED
1876 else if (PyObject_TypeCheck(method, __pyx_binding_PyCFunctionType)) { /* binded CFunction */
1877 return PyClassMethod_New(method);
1880 PyErr_Format(PyExc_TypeError,
1881 "Class-level classmethod() can only be called on "
1882 "a method_descriptor or instance method.");
1887 #------------------------------------------------------------------------------------
1889 ERR_BUF_LOCALONLY = 'Buffer types only allowed as function local variables'