Cython has moved to github.

cython-devel

view Cython/Compiler/Symtab.py @ 2497:87e556fc4e33

Fix #418 (wrong error message)
author Dag Sverre Seljebotn <dagss@student.matnat.uio.no>
date Fri Oct 16 13:14:22 2009 +0200 (2 years ago)
parents ed3063364434
children d5b4a406cdf2
line source
1 #
2 # Symbol Table
3 #
5 import re
6 from Cython import Utils
7 from Errors import warning, error, InternalError
8 from StringEncoding import EncodedString
9 import Options, Naming
10 import PyrexTypes
11 from PyrexTypes import py_object_type, unspecified_type
12 import TypeSlots
13 from TypeSlots import \
14 pyfunction_signature, pymethod_signature, \
15 get_special_method_signature, get_property_accessor_signature
16 import ControlFlow
17 import Code
18 import __builtin__ as builtins
19 try:
20 set
21 except NameError:
22 from sets import Set as set
24 possible_identifier = re.compile(ur"(?![0-9])\w+$", re.U).match
25 nice_identifier = re.compile('^[a-zA-Z0-0_]+$').match
27 iso_c99_keywords = set(
28 ['auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
29 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if',
30 'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof',
31 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void',
32 'volatile', 'while',
33 '_Bool', '_Complex'', _Imaginary', 'inline', 'restrict'])
35 def c_safe_identifier(cname):
36 # There are some C limitations on struct entry names.
37 if ((cname[:2] == '__'
38 and not (cname.startswith(Naming.pyrex_prefix)
39 or cname == '__weakref__'))
40 or cname in iso_c99_keywords):
41 cname = Naming.pyrex_prefix + cname
42 return cname
44 class BufferAux(object):
45 writable_needed = False
47 def __init__(self, buffer_info_var, stridevars, shapevars,
48 suboffsetvars):
49 self.buffer_info_var = buffer_info_var
50 self.stridevars = stridevars
51 self.shapevars = shapevars
52 self.suboffsetvars = suboffsetvars
54 def __repr__(self):
55 return "<BufferAux %r>" % self.__dict__
57 class Entry(object):
58 # A symbol table entry in a Scope or ModuleNamespace.
59 #
60 # name string Python name of entity
61 # cname string C name of entity
62 # type PyrexType Type of entity
63 # doc string Doc string
64 # init string Initial value
65 # visibility 'private' or 'public' or 'extern'
66 # is_builtin boolean Is an entry in the Python builtins dict
67 # is_cglobal boolean Is a C global variable
68 # is_pyglobal boolean Is a Python module-level variable
69 # or class attribute during
70 # class construction
71 # is_member boolean Is an assigned class member
72 # is_variable boolean Is a variable
73 # is_cfunction boolean Is a C function
74 # is_cmethod boolean Is a C method of an extension type
75 # is_unbound_cmethod boolean Is an unbound C method of an extension type
76 # is_type boolean Is a type definition
77 # is_cclass boolean Is an extension class
78 # is_const boolean Is a constant
79 # is_property boolean Is a property of an extension type:
80 # doc_cname string or None C const holding the docstring
81 # getter_cname string C func for getting property
82 # setter_cname string C func for setting or deleting property
83 # is_self_arg boolean Is the "self" arg of an exttype method
84 # is_arg boolean Is the arg of a method
85 # is_local boolean Is a local variable
86 # in_closure boolean Is referenced in an inner scope
87 # is_readonly boolean Can't be assigned to
88 # func_cname string C func implementing Python func
89 # func_modifiers [string] C function modifiers ('inline')
90 # pos position Source position where declared
91 # namespace_cname string If is_pyglobal, the C variable
92 # holding its home namespace
93 # pymethdef_cname string PyMethodDef structure
94 # signature Signature Arg & return types for Python func
95 # init_to_none boolean True if initial value should be None
96 # as_variable Entry Alternative interpretation of extension
97 # type name or builtin C function as a variable
98 # xdecref_cleanup boolean Use Py_XDECREF for error cleanup
99 # in_cinclude boolean Suppress C declaration code
100 # enum_values [Entry] For enum types, list of values
101 # qualified_name string "modname.funcname" or "modname.classname"
102 # or "modname.classname.funcname"
103 # is_declared_generic boolean Is declared as PyObject * even though its
104 # type is an extension type
105 # as_module None Module scope, if a cimported module
106 # is_inherited boolean Is an inherited attribute of an extension type
107 # pystring_cname string C name of Python version of string literal
108 # is_interned boolean For string const entries, value is interned
109 # is_identifier boolean For string const entries, value is an identifier
110 # used boolean
111 # is_special boolean Is a special method or property accessor
112 # of an extension type
113 # defined_in_pxd boolean Is defined in a .pxd file (not just declared)
114 # api boolean Generate C API for C class or function
115 # utility_code string Utility code needed when this entry is used
116 #
117 # buffer_aux BufferAux or None Extra information needed for buffer variables
118 # inline_func_in_pxd boolean Hacky special case for inline function in pxd file.
119 # Ideally this should not be necesarry.
120 # assignments [ExprNode] List of expressions that get assigned to this entry.
122 inline_func_in_pxd = False
123 borrowed = 0
124 init = ""
125 visibility = 'private'
126 is_builtin = 0
127 is_cglobal = 0
128 is_pyglobal = 0
129 is_member = 0
130 is_variable = 0
131 is_cfunction = 0
132 is_cmethod = 0
133 is_unbound_cmethod = 0
134 is_type = 0
135 is_cclass = 0
136 is_const = 0
137 is_property = 0
138 doc_cname = None
139 getter_cname = None
140 setter_cname = None
141 is_self_arg = 0
142 is_arg = 0
143 is_local = 0
144 in_closure = 0
145 is_declared_generic = 0
146 is_readonly = 0
147 func_cname = None
148 func_modifiers = []
149 doc = None
150 init_to_none = 0
151 as_variable = None
152 xdecref_cleanup = 0
153 in_cinclude = 0
154 as_module = None
155 is_inherited = 0
156 pystring_cname = None
157 is_identifier = 0
158 is_interned = 0
159 used = 0
160 is_special = 0
161 defined_in_pxd = 0
162 is_implemented = 0
163 api = 0
164 utility_code = None
165 is_overridable = 0
166 buffer_aux = None
167 prev_entry = None
169 def __init__(self, name, cname, type, pos = None, init = None):
170 self.name = name
171 self.cname = cname
172 self.type = type
173 self.pos = pos
174 self.init = init
175 self.assignments = []
177 def __repr__(self):
178 return "Entry(name=%s, type=%s)" % (self.name, self.type)
180 def redeclared(self, pos):
181 error(pos, "'%s' does not match previous declaration" % self.name)
182 error(self.pos, "Previous declaration is here")
184 class Scope(object):
185 # name string Unqualified name
186 # outer_scope Scope or None Enclosing scope
187 # entries {string : Entry} Python name to entry, non-types
188 # const_entries [Entry] Constant entries
189 # type_entries [Entry] Struct/union/enum/typedef/exttype entries
190 # sue_entries [Entry] Struct/union/enum entries
191 # arg_entries [Entry] Function argument entries
192 # var_entries [Entry] User-defined variable entries
193 # pyfunc_entries [Entry] Python function entries
194 # cfunc_entries [Entry] C function entries
195 # c_class_entries [Entry] All extension type entries
196 # cname_to_entry {string : Entry} Temp cname to entry mapping
197 # int_to_entry {int : Entry} Temp cname to entry mapping
198 # return_type PyrexType or None Return type of function owning scope
199 # is_py_class_scope boolean Is a Python class scope
200 # is_c_class_scope boolean Is an extension type scope
201 # scope_prefix string Disambiguator for C names
202 # in_cinclude boolean Suppress C declaration code
203 # qualified_name string "modname" or "modname.classname"
204 # pystring_entries [Entry] String const entries newly used as
205 # Python strings in this scope
206 # control_flow ControlFlow Used for keeping track of environment state
207 # nogil boolean In a nogil section
208 # directives dict Helper variable for the recursive
209 # analysis, contains directive values.
211 is_py_class_scope = 0
212 is_c_class_scope = 0
213 is_module_scope = 0
214 scope_prefix = ""
215 in_cinclude = 0
216 nogil = 0
218 def __init__(self, name, outer_scope, parent_scope):
219 # The outer_scope is the next scope in the lookup chain.
220 # The parent_scope is used to derive the qualified name of this scope.
221 self.name = name
222 self.outer_scope = outer_scope
223 self.parent_scope = parent_scope
224 mangled_name = "%d%s_" % (len(name), name)
225 qual_scope = self.qualifying_scope()
226 if qual_scope:
227 self.qualified_name = qual_scope.qualify_name(name)
228 self.scope_prefix = qual_scope.scope_prefix + mangled_name
229 else:
230 self.qualified_name = name
231 self.scope_prefix = mangled_name
232 self.entries = {}
233 self.const_entries = []
234 self.type_entries = []
235 self.sue_entries = []
236 self.arg_entries = []
237 self.var_entries = []
238 self.pyfunc_entries = []
239 self.cfunc_entries = []
240 self.c_class_entries = []
241 self.defined_c_classes = []
242 self.imported_c_classes = {}
243 self.cname_to_entry = {}
244 self.string_to_entry = {}
245 self.identifier_to_entry = {}
246 self.num_to_entry = {}
247 self.obj_to_entry = {}
248 self.pystring_entries = []
249 self.buffer_entries = []
250 self.control_flow = ControlFlow.LinearControlFlow()
251 self.return_type = None
253 def start_branching(self, pos):
254 self.control_flow = self.control_flow.start_branch(pos)
256 def next_branch(self, pos):
257 self.control_flow = self.control_flow.next_branch(pos)
259 def finish_branching(self, pos):
260 self.control_flow = self.control_flow.finish_branch(pos)
262 def __str__(self):
263 return "<%s %s>" % (self.__class__.__name__, self.qualified_name)
265 def qualifying_scope(self):
266 return self.parent_scope
268 def mangle(self, prefix, name = None):
269 if name:
270 return "%s%s%s" % (prefix, self.scope_prefix, name)
271 else:
272 return self.parent_scope.mangle(prefix, self.name)
274 def mangle_internal(self, name):
275 # Mangle an internal name so as not to clash with any
276 # user-defined name in this scope.
277 prefix = "%s%s_" % (Naming.pyrex_prefix, name)
278 return self.mangle(prefix)
279 #return self.parent_scope.mangle(prefix, self.name)
281 def global_scope(self):
282 # Return the module-level scope containing this scope.
283 return self.outer_scope.global_scope()
285 def builtin_scope(self):
286 # Return the module-level scope containing this scope.
287 return self.outer_scope.builtin_scope()
289 def declare(self, name, cname, type, pos, visibility):
290 # Create new entry, and add to dictionary if
291 # name is not None. Reports a warning if already
292 # declared.
293 if not self.in_cinclude and cname and re.match("^_[_A-Z]+$", cname):
294 # See http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html#Reserved-Names
295 warning(pos, "'%s' is a reserved name in C." % cname, -1)
296 entries = self.entries
297 if name and name in entries:
298 if visibility == 'extern':
299 warning(pos, "'%s' redeclared " % name, 0)
300 elif visibility != 'ignore':
301 error(pos, "'%s' redeclared " % name)
302 entry = Entry(name, cname, type, pos = pos)
303 entry.in_cinclude = self.in_cinclude
304 if name:
305 entry.qualified_name = self.qualify_name(name)
306 entries[name] = entry
307 entry.scope = self
308 entry.visibility = visibility
309 return entry
311 def qualify_name(self, name):
312 return "%s.%s" % (self.qualified_name, name)
314 def declare_const(self, name, type, value, pos, cname = None, visibility = 'private'):
315 # Add an entry for a named constant.
316 if not cname:
317 if self.in_cinclude or visibility == 'public':
318 cname = name
319 else:
320 cname = self.mangle(Naming.enum_prefix, name)
321 entry = self.declare(name, cname, type, pos, visibility)
322 entry.is_const = 1
323 entry.value_node = value
324 return entry
326 def declare_type(self, name, type, pos,
327 cname = None, visibility = 'private', defining = 1):
328 # Add an entry for a type definition.
329 if not cname:
330 cname = name
331 entry = self.declare(name, cname, type, pos, visibility)
332 entry.is_type = 1
333 if defining:
334 self.type_entries.append(entry)
335 # here we would set as_variable to an object representing this type
336 return entry
338 def declare_typedef(self, name, base_type, pos, cname = None,
339 visibility = 'private'):
340 if not cname:
341 if self.in_cinclude or visibility == 'public':
342 cname = name
343 else:
344 cname = self.mangle(Naming.type_prefix, name)
345 type = PyrexTypes.CTypedefType(cname, base_type, (visibility == 'extern'))
346 entry = self.declare_type(name, type, pos, cname, visibility)
347 type.qualified_name = entry.qualified_name
348 return entry
350 def declare_struct_or_union(self, name, kind, scope,
351 typedef_flag, pos, cname = None, visibility = 'private',
352 packed = False):
353 # Add an entry for a struct or union definition.
354 if not cname:
355 if self.in_cinclude or visibility == 'public':
356 cname = name
357 else:
358 cname = self.mangle(Naming.type_prefix, name)
359 entry = self.lookup_here(name)
360 if not entry:
361 type = PyrexTypes.CStructOrUnionType(
362 name, kind, scope, typedef_flag, cname, packed)
363 entry = self.declare_type(name, type, pos, cname,
364 visibility = visibility, defining = scope is not None)
365 self.sue_entries.append(entry)
366 type.entry = entry
367 else:
368 if not (entry.is_type and entry.type.is_struct_or_union
369 and entry.type.kind == kind):
370 warning(pos, "'%s' redeclared " % name, 0)
371 elif scope and entry.type.scope:
372 warning(pos, "'%s' already defined (ignoring second definition)" % name, 0)
373 else:
374 self.check_previous_typedef_flag(entry, typedef_flag, pos)
375 self.check_previous_visibility(entry, visibility, pos)
376 if scope:
377 entry.type.scope = scope
378 self.type_entries.append(entry)
379 if not scope and not entry.type.scope:
380 self.check_for_illegal_incomplete_ctypedef(typedef_flag, pos)
381 return entry
383 def check_previous_typedef_flag(self, entry, typedef_flag, pos):
384 if typedef_flag != entry.type.typedef_flag:
385 error(pos, "'%s' previously declared using '%s'" % (
386 entry.name, ("cdef", "ctypedef")[entry.type.typedef_flag]))
388 def check_previous_visibility(self, entry, visibility, pos):
389 if entry.visibility != visibility:
390 error(pos, "'%s' previously declared as '%s'" % (
391 entry.name, entry.visibility))
393 def declare_enum(self, name, pos, cname, typedef_flag,
394 visibility = 'private'):
395 if name:
396 if not cname:
397 if self.in_cinclude or visibility == 'public':
398 cname = name
399 else:
400 cname = self.mangle(Naming.type_prefix, name)
401 type = PyrexTypes.CEnumType(name, cname, typedef_flag)
402 else:
403 type = PyrexTypes.c_anon_enum_type
404 entry = self.declare_type(name, type, pos, cname = cname,
405 visibility = visibility)
406 entry.enum_values = []
407 self.sue_entries.append(entry)
408 return entry
410 def declare_var(self, name, type, pos,
411 cname = None, visibility = 'private', is_cdef = 0):
412 # Add an entry for a variable.
413 if not cname:
414 if visibility != 'private':
415 cname = name
416 else:
417 cname = self.mangle(Naming.var_prefix, name)
418 entry = self.declare(name, cname, type, pos, visibility)
419 entry.is_variable = 1
420 self.control_flow.set_state((), (name, 'initalized'), False)
421 return entry
423 def declare_builtin(self, name, pos):
424 return self.outer_scope.declare_builtin(name, pos)
426 def declare_pyfunction(self, name, pos):
427 # Add an entry for a Python function.
428 entry = self.lookup_here(name)
429 if entry and not entry.type.is_cfunction:
430 # This is legal Python, but for now will produce invalid C.
431 error(pos, "'%s' already declared" % name)
432 entry = self.declare_var(name, py_object_type, pos, visibility='extern')
433 entry.signature = pyfunction_signature
434 self.pyfunc_entries.append(entry)
435 return entry
437 def register_pyfunction(self, entry):
438 self.pyfunc_entries.append(entry)
440 def declare_cfunction(self, name, type, pos,
441 cname = None, visibility = 'private', defining = 0,
442 api = 0, in_pxd = 0, modifiers = ()):
443 # Add an entry for a C function.
444 entry = self.lookup_here(name)
445 if entry:
446 if visibility != 'private' and visibility != entry.visibility:
447 warning(pos, "Function '%s' previously declared as '%s'" % (name, entry.visibility), 1)
448 if not entry.type.same_as(type):
449 if visibility == 'extern' and entry.visibility == 'extern':
450 warning(pos, "Function signature does not match previous declaration", 1)
451 entry.type = type
452 else:
453 error(pos, "Function signature does not match previous declaration")
454 else:
455 if not cname:
456 if api or visibility != 'private':
457 cname = name
458 else:
459 cname = self.mangle(Naming.func_prefix, name)
460 entry = self.add_cfunction(name, type, pos, cname, visibility, modifiers)
461 entry.func_cname = cname
462 if in_pxd and visibility != 'extern':
463 entry.defined_in_pxd = 1
464 if api:
465 entry.api = 1
466 if not defining and not in_pxd and visibility != 'extern':
467 error(pos, "Non-extern C function '%s' declared but not defined" % name)
468 if defining:
469 entry.is_implemented = True
470 if modifiers:
471 entry.func_modifiers = modifiers
472 return entry
474 def add_cfunction(self, name, type, pos, cname, visibility, modifiers):
475 # Add a C function entry without giving it a func_cname.
476 entry = self.declare(name, cname, type, pos, visibility)
477 entry.is_cfunction = 1
478 if modifiers:
479 entry.func_modifiers = modifiers
480 self.cfunc_entries.append(entry)
481 return entry
483 def find(self, name, pos):
484 # Look up name, report error if not found.
485 entry = self.lookup(name)
486 if entry:
487 return entry
488 else:
489 error(pos, "'%s' is not declared" % name)
491 def find_imported_module(self, path, pos):
492 # Look up qualified name, must be a module, report error if not found.
493 # Path is a list of names.
494 scope = self
495 for name in path:
496 entry = scope.find(name, pos)
497 if not entry:
498 return None
499 if entry.as_module:
500 scope = entry.as_module
501 else:
502 error(pos, "'%s' is not a cimported module" % '.'.join(path))
503 return None
504 return scope
506 def lookup(self, name):
507 # Look up name in this scope or an enclosing one.
508 # Return None if not found.
509 return (self.lookup_here(name)
510 or (self.outer_scope and self.outer_scope.lookup_from_inner(name))
511 or None)
513 def lookup_from_inner(self, name):
514 # Look up name in this scope or an enclosing one.
515 # This is only called from enclosing scopes.
516 return (self.lookup_here(name)
517 or (self.outer_scope and self.outer_scope.lookup_from_inner(name))
518 or None)
520 def lookup_here(self, name):
521 # Look up in this scope only, return None if not found.
522 return self.entries.get(name, None)
524 def lookup_target(self, name):
525 # Look up name in this scope only. Declare as Python
526 # variable if not found.
527 entry = self.lookup_here(name)
528 if not entry:
529 entry = self.declare_var(name, py_object_type, None)
530 return entry
532 def lookup_type(self, name):
533 entry = self.lookup(name)
534 if entry and entry.is_type:
535 return entry.type
537 def use_utility_code(self, new_code):
538 self.global_scope().use_utility_code(new_code)
540 def generate_library_function_declarations(self, code):
541 # Generate extern decls for C library funcs used.
542 pass
544 def defines_any(self, names):
545 # Test whether any of the given names are
546 # defined in this scope.
547 for name in names:
548 if name in self.entries:
549 return 1
550 return 0
552 def infer_types(self):
553 from TypeInference import get_type_inferer
554 get_type_inferer().infer_types(self)
556 class PreImportScope(Scope):
558 namespace_cname = Naming.preimport_cname
560 def __init__(self):
561 Scope.__init__(self, Options.pre_import, None, None)
563 def declare_builtin(self, name, pos):
564 entry = self.declare(name, name, py_object_type, pos, 'private')
565 entry.is_variable = True
566 entry.is_pyglobal = True
567 return entry
570 class BuiltinScope(Scope):
571 # The builtin namespace.
573 def __init__(self):
574 if Options.pre_import is None:
575 Scope.__init__(self, "__builtin__", None, None)
576 else:
577 Scope.__init__(self, "__builtin__", PreImportScope(), None)
578 self.type_names = {}
580 for name, definition in self.builtin_entries.iteritems():
581 cname, type = definition
582 self.declare_var(name, type, None, cname)
584 def declare_builtin(self, name, pos):
585 if not hasattr(builtins, name):
586 if self.outer_scope is not None:
587 return self.outer_scope.declare_builtin(name, pos)
588 else:
589 error(pos, "undeclared name not builtin: %s"%name)
591 def declare_builtin_cfunction(self, name, type, cname, python_equiv = None,
592 utility_code = None):
593 # If python_equiv == "*", the Python equivalent has the same name
594 # as the entry, otherwise it has the name specified by python_equiv.
595 name = EncodedString(name)
596 entry = self.declare_cfunction(name, type, None, cname, visibility='extern')
597 entry.utility_code = utility_code
598 if python_equiv:
599 if python_equiv == "*":
600 python_equiv = name
601 else:
602 python_equiv = EncodedString(python_equiv)
603 var_entry = Entry(python_equiv, python_equiv, py_object_type)
604 var_entry.is_variable = 1
605 var_entry.is_builtin = 1
606 entry.as_variable = var_entry
607 return entry
609 def declare_builtin_type(self, name, cname, utility_code = None):
610 name = EncodedString(name)
611 type = PyrexTypes.BuiltinObjectType(name, cname)
612 type.set_scope(CClassScope(name, outer_scope=None, visibility='extern'))
613 self.type_names[name] = 1
614 entry = self.declare_type(name, type, None, visibility='extern')
616 var_entry = Entry(name = entry.name,
617 type = self.lookup('type').type, # make sure "type" is the first type declared...
618 pos = entry.pos,
619 cname = "((PyObject*)%s)" % entry.type.typeptr_cname)
620 var_entry.is_variable = 1
621 var_entry.is_cglobal = 1
622 var_entry.is_readonly = 1
623 var_entry.utility_code = utility_code
624 entry.as_variable = var_entry
626 return type
628 def builtin_scope(self):
629 return self
631 builtin_entries = {
633 "type": ["((PyObject*)&PyType_Type)", py_object_type],
635 "bool": ["((PyObject*)&PyBool_Type)", py_object_type],
636 "int": ["((PyObject*)&PyInt_Type)", py_object_type],
637 "long": ["((PyObject*)&PyLong_Type)", py_object_type],
638 "float": ["((PyObject*)&PyFloat_Type)", py_object_type],
639 "complex":["((PyObject*)&PyComplex_Type)", py_object_type],
641 "bytes": ["((PyObject*)&PyBytes_Type)", py_object_type],
642 "str": ["((PyObject*)&PyString_Type)", py_object_type],
643 "unicode":["((PyObject*)&PyUnicode_Type)", py_object_type],
645 "tuple": ["((PyObject*)&PyTuple_Type)", py_object_type],
646 "list": ["((PyObject*)&PyList_Type)", py_object_type],
647 "dict": ["((PyObject*)&PyDict_Type)", py_object_type],
648 "set": ["((PyObject*)&PySet_Type)", py_object_type],
649 "frozenset": ["((PyObject*)&PyFrozenSet_Type)", py_object_type],
651 "slice": ["((PyObject*)&PySlice_Type)", py_object_type],
652 "file": ["((PyObject*)&PyFile_Type)", py_object_type],
654 "None": ["Py_None", py_object_type],
655 "False": ["Py_False", py_object_type],
656 "True": ["Py_True", py_object_type],
657 }
659 const_counter = 1 # As a temporary solution for compiling code in pxds
661 class ModuleScope(Scope):
662 # module_name string Python name of the module
663 # module_cname string C name of Python module object
664 # #module_dict_cname string C name of module dict object
665 # method_table_cname string C name of method table
666 # doc string Module doc string
667 # doc_cname string C name of module doc string
668 # utility_code_list [UtilityCode] Queuing utility codes for forwarding to Code.py
669 # python_include_files [string] Standard Python headers to be included
670 # include_files [string] Other C headers to be included
671 # string_to_entry {string : Entry} Map string const to entry
672 # identifier_to_entry {string : Entry} Map identifier string const to entry
673 # context Context
674 # parent_module Scope Parent in the import namespace
675 # module_entries {string : Entry} For cimport statements
676 # type_names {string : 1} Set of type names (used during parsing)
677 # included_files [string] Cython sources included with 'include'
678 # pxd_file_loaded boolean Corresponding .pxd file has been processed
679 # cimported_modules [ModuleScope] Modules imported with cimport
680 # types_imported {PyrexType : 1} Set of types for which import code generated
681 # has_import_star boolean Module contains import *
683 is_module_scope = 1
684 has_import_star = 0
686 def __init__(self, name, parent_module, context):
687 self.parent_module = parent_module
688 outer_scope = context.find_submodule("__builtin__")
689 Scope.__init__(self, name, outer_scope, parent_module)
690 if name != "__init__":
691 self.module_name = name
692 else:
693 # Treat Spam/__init__.pyx specially, so that when Python loads
694 # Spam/__init__.so, initSpam() is defined.
695 self.module_name = parent_module.module_name
696 self.context = context
697 self.module_cname = Naming.module_cname
698 self.module_dict_cname = Naming.moddict_cname
699 self.method_table_cname = Naming.methtable_cname
700 self.doc = ""
701 self.doc_cname = Naming.moddoc_cname
702 self.utility_code_list = []
703 self.module_entries = {}
704 self.python_include_files = ["Python.h", "structmember.h"]
705 self.include_files = []
706 self.type_names = dict(outer_scope.type_names)
707 self.pxd_file_loaded = 0
708 self.cimported_modules = []
709 self.types_imported = {}
710 self.included_files = []
711 self.has_extern_class = 0
712 self.cached_builtins = []
713 self.undeclared_cached_builtins = []
714 self.namespace_cname = self.module_cname
715 for name in ['__builtins__', '__name__', '__file__', '__doc__']:
716 self.declare_var(EncodedString(name), py_object_type, None)
718 def qualifying_scope(self):
719 return self.parent_module
721 def global_scope(self):
722 return self
724 def declare_builtin(self, name, pos):
725 if not hasattr(builtins, name):
726 if self.has_import_star:
727 entry = self.declare_var(name, py_object_type, pos)
728 return entry
729 elif self.outer_scope is not None:
730 return self.outer_scope.declare_builtin(name, pos)
731 else:
732 error(pos, "undeclared name not builtin: %s"%name)
733 if Options.cache_builtins:
734 for entry in self.cached_builtins:
735 if entry.name == name:
736 return entry
737 entry = self.declare(None, None, py_object_type, pos, 'private')
738 if Options.cache_builtins:
739 entry.is_builtin = 1
740 entry.is_const = 1
741 entry.name = name
742 entry.cname = Naming.builtin_prefix + name
743 self.cached_builtins.append(entry)
744 self.undeclared_cached_builtins.append(entry)
745 else:
746 entry.is_builtin = 1
747 return entry
749 def find_module(self, module_name, pos):
750 # Find a module in the import namespace, interpreting
751 # relative imports relative to this module's parent.
752 # Finds and parses the module's .pxd file if the module
753 # has not been referenced before.
754 return self.global_scope().context.find_module(
755 module_name, relative_to = self.parent_module, pos = pos)
757 def find_submodule(self, name):
758 # Find and return scope for a submodule of this module,
759 # creating a new empty one if necessary. Doesn't parse .pxd.
760 scope = self.lookup_submodule(name)
761 if not scope:
762 scope = ModuleScope(name,
763 parent_module = self, context = self.context)
764 self.module_entries[name] = scope
765 return scope
767 def lookup_submodule(self, name):
768 # Return scope for submodule of this module, or None.
769 return self.module_entries.get(name, None)
771 def add_include_file(self, filename):
772 if filename not in self.python_include_files \
773 and filename not in self.include_files:
774 self.include_files.append(filename)
776 def add_imported_module(self, scope):
777 if scope not in self.cimported_modules:
778 for filename in scope.include_files:
779 self.add_include_file(filename)
780 self.cimported_modules.append(scope)
781 for m in scope.cimported_modules:
782 self.add_imported_module(m)
784 def add_imported_entry(self, name, entry, pos):
785 if entry not in self.entries:
786 self.entries[name] = entry
787 else:
788 warning(pos, "'%s' redeclared " % name, 0)
790 def declare_module(self, name, scope, pos):
791 # Declare a cimported module. This is represented as a
792 # Python module-level variable entry with a module
793 # scope attached to it. Reports an error and returns
794 # None if previously declared as something else.
795 entry = self.lookup_here(name)
796 if entry:
797 if entry.is_pyglobal and entry.as_module is scope:
798 return entry # Already declared as the same module
799 if not (entry.is_pyglobal and not entry.as_module):
800 # SAGE -- I put this here so Pyrex
801 # cimport's work across directories.
802 # Currently it tries to multiply define
803 # every module appearing in an import list.
804 # It shouldn't be an error for a module
805 # name to appear again, and indeed the generated
806 # code compiles fine.
807 return entry
808 warning(pos, "'%s' redeclared " % name, 0)
809 return None
810 else:
811 entry = self.declare_var(name, py_object_type, pos)
812 entry.as_module = scope
813 self.add_imported_module(scope)
814 return entry
816 def declare_var(self, name, type, pos,
817 cname = None, visibility = 'private', is_cdef = 0):
818 # Add an entry for a global variable. If it is a Python
819 # object type, and not declared with cdef, it will live
820 # in the module dictionary, otherwise it will be a C
821 # global variable.
822 entry = Scope.declare_var(self, name, type, pos,
823 cname, visibility, is_cdef)
824 if not visibility in ('private', 'public', 'extern'):
825 error(pos, "Module-level variable cannot be declared %s" % visibility)
826 if not is_cdef:
827 if type is unspecified_type:
828 type = py_object_type
829 if not (type.is_pyobject and not type.is_extension_type):
830 raise InternalError(
831 "Non-cdef global variable is not a generic Python object")
832 entry.is_pyglobal = 1
833 else:
834 entry.is_cglobal = 1
835 if entry.type.is_pyobject:
836 entry.init = 0
837 self.var_entries.append(entry)
838 return entry
840 def declare_global(self, name, pos):
841 entry = self.lookup_here(name)
842 if not entry:
843 self.declare_var(name, py_object_type, pos)
845 def use_utility_code(self, new_code):
846 if new_code is not None:
847 self.utility_code_list.append(new_code)
849 def declare_c_class(self, name, pos, defining = 0, implementing = 0,
850 module_name = None, base_type = None, objstruct_cname = None,
851 typeobj_cname = None, visibility = 'private', typedef_flag = 0, api = 0,
852 buffer_defaults = None):
853 # If this is a non-extern typedef class, expose the typedef, but use
854 # the non-typedef struct internally to avoid needing forward
855 # declarations for anonymous structs.
856 if typedef_flag and visibility != 'extern':
857 if visibility != 'public':
858 warning(pos, "ctypedef only valid for public and extern classes", 2)
859 objtypedef_cname = objstruct_cname
860 objstruct_cname = None
861 typedef_flag = 0
862 else:
863 objtypedef_cname = None
864 #
865 # Look for previous declaration as a type
866 #
867 entry = self.lookup_here(name)
868 if entry:
869 type = entry.type
870 if not (entry.is_type and type.is_extension_type):
871 entry = None # Will cause redeclaration and produce an error
872 else:
873 scope = type.scope
874 if typedef_flag and (not scope or scope.defined):
875 self.check_previous_typedef_flag(entry, typedef_flag, pos)
876 if (scope and scope.defined) or (base_type and type.base_type):
877 if base_type and base_type is not type.base_type:
878 error(pos, "Base type does not match previous declaration")
879 if base_type and not type.base_type:
880 type.base_type = base_type
881 #
882 # Make a new entry if needed
883 #
884 if not entry:
885 type = PyrexTypes.PyExtensionType(name, typedef_flag, base_type)
886 type.pos = pos
887 type.buffer_defaults = buffer_defaults
888 if objtypedef_cname is not None:
889 type.objtypedef_cname = objtypedef_cname
890 if visibility == 'extern':
891 type.module_name = module_name
892 else:
893 type.module_name = self.qualified_name
894 type.typeptr_cname = self.mangle(Naming.typeptr_prefix, name)
895 entry = self.declare_type(name, type, pos, visibility = visibility,
896 defining = 0)
897 entry.is_cclass = True
898 if objstruct_cname:
899 type.objstruct_cname = objstruct_cname
900 elif not entry.in_cinclude:
901 type.objstruct_cname = self.mangle(Naming.objstruct_prefix, name)
902 else:
903 error(entry.pos,
904 "Object name required for 'public' or 'extern' C class")
905 self.attach_var_entry_to_c_class(entry)
906 self.c_class_entries.append(entry)
907 #
908 # Check for re-definition and create scope if needed
909 #
910 if not type.scope:
911 if defining or implementing:
912 scope = CClassScope(name = name, outer_scope = self,
913 visibility = visibility)
914 if base_type and base_type.scope:
915 scope.declare_inherited_c_attributes(base_type.scope)
916 type.set_scope(scope)
917 self.type_entries.append(entry)
918 else:
919 self.check_for_illegal_incomplete_ctypedef(typedef_flag, pos)
920 else:
921 if defining and type.scope.defined:
922 error(pos, "C class '%s' already defined" % name)
923 elif implementing and type.scope.implemented:
924 error(pos, "C class '%s' already implemented" % name)
925 #
926 # Fill in options, checking for compatibility with any previous declaration
927 #
928 if defining:
929 entry.defined_in_pxd = 1
930 if implementing: # So that filenames in runtime exceptions refer to
931 entry.pos = pos # the .pyx file and not the .pxd file
932 if visibility != 'private' and entry.visibility != visibility:
933 error(pos, "Class '%s' previously declared as '%s'"
934 % (name, entry.visibility))
935 if api:
936 entry.api = 1
937 if objstruct_cname:
938 if type.objstruct_cname and type.objstruct_cname != objstruct_cname:
939 error(pos, "Object struct name differs from previous declaration")
940 type.objstruct_cname = objstruct_cname
941 if typeobj_cname:
942 if type.typeobj_cname and type.typeobj_cname != typeobj_cname:
943 error(pos, "Type object name differs from previous declaration")
944 type.typeobj_cname = typeobj_cname
945 #
946 # Return new or existing entry
947 #
948 return entry
950 def check_for_illegal_incomplete_ctypedef(self, typedef_flag, pos):
951 if typedef_flag and not self.in_cinclude:
952 error(pos, "Forward-referenced type must use 'cdef', not 'ctypedef'")
954 def allocate_vtable_names(self, entry):
955 # If extension type has a vtable, allocate vtable struct and
956 # slot names for it.
957 type = entry.type
958 if type.base_type and type.base_type.vtabslot_cname:
959 #print "...allocating vtabslot_cname because base type has one" ###
960 type.vtabslot_cname = "%s.%s" % (
961 Naming.obj_base_cname, type.base_type.vtabslot_cname)
962 elif type.scope and type.scope.cfunc_entries:
963 #print "...allocating vtabslot_cname because there are C methods" ###
964 type.vtabslot_cname = Naming.vtabslot_cname
965 if type.vtabslot_cname:
966 #print "...allocating other vtable related cnames" ###
967 type.vtabstruct_cname = self.mangle(Naming.vtabstruct_prefix, entry.name)
968 type.vtabptr_cname = self.mangle(Naming.vtabptr_prefix, entry.name)
970 def check_c_classes_pxd(self):
971 # Performs post-analysis checking and finishing up of extension types
972 # being implemented in this module. This is called only for the .pxd.
973 #
974 # Checks all extension types declared in this scope to
975 # make sure that:
976 #
977 # * The extension type is fully declared
978 #
979 # Also allocates a name for the vtable if needed.
980 #
981 for entry in self.c_class_entries:
982 # Check defined
983 if not entry.type.scope:
984 error(entry.pos, "C class '%s' is declared but not defined" % entry.name)
986 def check_c_classes(self):
987 # Performs post-analysis checking and finishing up of extension types
988 # being implemented in this module. This is called only for the main
989 # .pyx file scope, not for cimported .pxd scopes.
990 #
991 # Checks all extension types declared in this scope to
992 # make sure that:
993 #
994 # * The extension type is implemented
995 # * All required object and type names have been specified or generated
996 # * All non-inherited C methods are implemented
997 #
998 # Also allocates a name for the vtable if needed.
999 #
1000 debug_check_c_classes = 0
1001 if debug_check_c_classes:
1002 print("Scope.check_c_classes: checking scope " + self.qualified_name)
1003 for entry in self.c_class_entries:
1004 if debug_check_c_classes:
1005 print("...entry %s %s" % (entry.name, entry))
1006 print("......type = ", entry.type)
1007 print("......visibility = ", entry.visibility)
1008 type = entry.type
1009 name = entry.name
1010 visibility = entry.visibility
1011 # Check defined
1012 if not type.scope:
1013 error(entry.pos, "C class '%s' is declared but not defined" % name)
1014 # Generate typeobj_cname
1015 if visibility != 'extern' and not type.typeobj_cname:
1016 type.typeobj_cname = self.mangle(Naming.typeobj_prefix, name)
1017 ## Generate typeptr_cname
1018 #type.typeptr_cname = self.mangle(Naming.typeptr_prefix, name)
1019 # Check C methods defined
1020 if type.scope:
1021 for method_entry in type.scope.cfunc_entries:
1022 if not method_entry.is_inherited and not method_entry.func_cname:
1023 error(method_entry.pos, "C method '%s' is declared but not defined" %
1024 method_entry.name)
1025 # Allocate vtable name if necessary
1026 if type.vtabslot_cname:
1027 #print "ModuleScope.check_c_classes: allocating vtable cname for", self ###
1028 type.vtable_cname = self.mangle(Naming.vtable_prefix, entry.name)
1030 def check_c_functions(self):
1031 # Performs post-analysis checking making sure all
1032 # defined c functions are actually implemented.
1033 for name, entry in self.entries.items():
1034 if entry.is_cfunction:
1035 if (entry.defined_in_pxd
1036 and entry.scope is self
1037 and entry.visibility != 'extern'
1038 and not entry.in_cinclude
1039 and not entry.is_implemented):
1040 error(entry.pos, "Non-extern C function '%s' declared but not defined" % name)
1042 def attach_var_entry_to_c_class(self, entry):
1043 # The name of an extension class has to serve as both a type
1044 # name and a variable name holding the type object. It is
1045 # represented in the symbol table by a type entry with a
1046 # variable entry attached to it. For the variable entry,
1047 # we use a read-only C global variable whose name is an
1048 # expression that refers to the type object.
1049 import Builtin
1050 var_entry = Entry(name = entry.name,
1051 type = Builtin.type_type,
1052 pos = entry.pos,
1053 cname = "((PyObject*)%s)" % entry.type.typeptr_cname)
1054 var_entry.is_variable = 1
1055 var_entry.is_cglobal = 1
1056 var_entry.is_readonly = 1
1057 entry.as_variable = var_entry
1059 def infer_types(self):
1060 from TypeInference import PyObjectTypeInferer
1061 PyObjectTypeInferer().infer_types(self)
1063 class LocalScope(Scope):
1065 def __init__(self, name, outer_scope):
1066 Scope.__init__(self, name, outer_scope, outer_scope)
1068 def mangle(self, prefix, name):
1069 return prefix + name
1071 def declare_arg(self, name, type, pos):
1072 # Add an entry for an argument of a function.
1073 cname = self.mangle(Naming.var_prefix, name)
1074 entry = self.declare(name, cname, type, pos, 'private')
1075 entry.is_variable = 1
1076 if type.is_pyobject:
1077 entry.init = "0"
1078 entry.is_arg = 1
1079 #entry.borrowed = 1 # Not using borrowed arg refs for now
1080 self.arg_entries.append(entry)
1081 self.control_flow.set_state((), (name, 'source'), 'arg')
1082 return entry
1084 def declare_var(self, name, type, pos,
1085 cname = None, visibility = 'private', is_cdef = 0):
1086 # Add an entry for a local variable.
1087 if visibility in ('public', 'readonly'):
1088 error(pos, "Local variable cannot be declared %s" % visibility)
1089 entry = Scope.declare_var(self, name, type, pos,
1090 cname, visibility, is_cdef)
1091 if type.is_pyobject and not Options.init_local_none:
1092 entry.init = "0"
1093 entry.init_to_none = (type.is_pyobject or type.is_unspecified) and Options.init_local_none
1094 entry.is_local = 1
1095 self.var_entries.append(entry)
1096 return entry
1098 def declare_global(self, name, pos):
1099 # Pull entry from global scope into local scope.
1100 if self.lookup_here(name):
1101 warning(pos, "'%s' redeclared ", 0)
1102 else:
1103 entry = self.global_scope().lookup_target(name)
1104 self.entries[name] = entry
1106 def lookup_from_inner(self, name):
1107 entry = self.lookup_here(name)
1108 if entry:
1109 entry.in_closure = 1
1110 return entry
1111 else:
1112 return (self.outer_scope and self.outer_scope.lookup_from_inner(name)) or None
1114 def mangle_closure_cnames(self, scope_var):
1115 for entry in self.entries.values():
1116 if entry.in_closure:
1117 if not hasattr(entry, 'orig_cname'):
1118 entry.orig_cname = entry.cname
1119 entry.cname = scope_var + "->" + entry.cname
1122 class GeneratorLocalScope(LocalScope):
1124 def mangle_closure_cnames(self, scope_var):
1125 # for entry in self.entries.values() + self.temp_entries:
1126 # entry.in_closure = 1
1127 LocalScope.mangle_closure_cnames(self, scope_var)
1129 # def mangle(self, prefix, name):
1130 # return "%s->%s" % (Naming.scope_obj_cname, name)
1132 class StructOrUnionScope(Scope):
1133 # Namespace of a C struct or union.
1135 def __init__(self, name="?"):
1136 Scope.__init__(self, name, None, None)
1138 def declare_var(self, name, type, pos,
1139 cname = None, visibility = 'private', is_cdef = 0, allow_pyobject = 0):
1140 # Add an entry for an attribute.
1141 if not cname:
1142 cname = name
1143 if visibility == 'private':
1144 cname = c_safe_identifier(cname)
1145 if type.is_cfunction:
1146 type = PyrexTypes.CPtrType(type)
1147 entry = self.declare(name, cname, type, pos, visibility)
1148 entry.is_variable = 1
1149 self.var_entries.append(entry)
1150 if type.is_pyobject and not allow_pyobject:
1151 error(pos,
1152 "C struct/union member cannot be a Python object")
1153 if visibility != 'private':
1154 error(pos,
1155 "C struct/union member cannot be declared %s" % visibility)
1156 return entry
1158 def declare_cfunction(self, name, type, pos,
1159 cname = None, visibility = 'private', defining = 0,
1160 api = 0, in_pxd = 0, modifiers = ()):
1161 return self.declare_var(name, type, pos, cname, visibility)
1163 class ClassScope(Scope):
1164 # Abstract base class for namespace of
1165 # Python class or extension type.
1167 # class_name string Pyrex name of the class
1168 # scope_prefix string Additional prefix for names
1169 # declared in the class
1170 # doc string or None Doc string
1172 def __init__(self, name, outer_scope):
1173 Scope.__init__(self, name, outer_scope, outer_scope)
1174 self.class_name = name
1175 self.doc = None
1177 def add_string_const(self, value, identifier = False):
1178 return self.outer_scope.add_string_const(value, identifier)
1180 def lookup(self, name):
1181 if name == "classmethod":
1182 # We don't want to use the builtin classmethod here 'cause it won't do the
1183 # right thing in this scope (as the class memebers aren't still functions).
1184 # Don't want to add a cfunction to this scope 'cause that would mess with
1185 # the type definition, so we just return the right entry.
1186 self.use_utility_code(classmethod_utility_code)
1187 entry = Entry(
1188 "classmethod",
1189 "__Pyx_Method_ClassMethod",
1190 PyrexTypes.CFuncType(
1191 py_object_type,
1192 [PyrexTypes.CFuncTypeArg("", py_object_type, None)], 0, 0))
1193 entry.is_cfunction = 1
1194 return entry
1195 else:
1196 return Scope.lookup(self, name)
1199 class PyClassScope(ClassScope):
1200 # Namespace of a Python class.
1202 # class_obj_cname string C variable holding class object
1204 is_py_class_scope = 1
1206 def declare_var(self, name, type, pos,
1207 cname = None, visibility = 'private', is_cdef = 0):
1208 if type is unspecified_type:
1209 type = py_object_type
1210 # Add an entry for a class attribute.
1211 entry = Scope.declare_var(self, name, type, pos,
1212 cname, visibility, is_cdef)
1213 entry.is_pyglobal = 1
1214 return entry
1216 def add_default_value(self, type):
1217 return self.outer_scope.add_default_value(type)
1220 class CClassScope(ClassScope):
1221 # Namespace of an extension type.
1223 # parent_type CClassType
1224 # #typeobj_cname string or None
1225 # #objstruct_cname string
1226 # method_table_cname string
1227 # member_table_cname string
1228 # getset_table_cname string
1229 # has_pyobject_attrs boolean Any PyObject attributes?
1230 # public_attr_entries boolean public/readonly attrs
1231 # property_entries [Entry]
1232 # defined boolean Defined in .pxd file
1233 # implemented boolean Defined in .pyx file
1234 # inherited_var_entries [Entry] Adapted var entries from base class
1236 is_c_class_scope = 1
1238 def __init__(self, name, outer_scope, visibility):
1239 ClassScope.__init__(self, name, outer_scope)
1240 if visibility != 'extern':
1241 self.method_table_cname = outer_scope.mangle(Naming.methtab_prefix, name)
1242 self.member_table_cname = outer_scope.mangle(Naming.memtab_prefix, name)
1243 self.getset_table_cname = outer_scope.mangle(Naming.gstab_prefix, name)
1244 self.has_pyobject_attrs = 0
1245 self.public_attr_entries = []
1246 self.property_entries = []
1247 self.inherited_var_entries = []
1248 self.defined = 0
1249 self.implemented = 0
1251 def needs_gc(self):
1252 # If the type or any of its base types have Python-valued
1253 # C attributes, then it needs to participate in GC.
1254 return self.has_pyobject_attrs or \
1255 (self.parent_type.base_type and
1256 self.parent_type.base_type.scope is not None and
1257 self.parent_type.base_type.scope.needs_gc())
1259 def declare_var(self, name, type, pos,
1260 cname = None, visibility = 'private', is_cdef = 0):
1261 if is_cdef:
1262 # Add an entry for an attribute.
1263 if self.defined:
1264 error(pos,
1265 "C attributes cannot be added in implementation part of"
1266 " extension type defined in a pxd")
1267 if get_special_method_signature(name):
1268 error(pos,
1269 "The name '%s' is reserved for a special method."
1270 % name)
1271 if not cname:
1272 cname = name
1273 if visibility == 'private':
1274 cname = c_safe_identifier(cname)
1275 entry = self.declare(name, cname, type, pos, visibility)
1276 entry.is_variable = 1
1277 self.var_entries.append(entry)
1278 if type.is_pyobject:
1279 self.has_pyobject_attrs = 1
1280 if visibility not in ('private', 'public', 'readonly'):
1281 error(pos,
1282 "Attribute of extension type cannot be declared %s" % visibility)
1283 if visibility in ('public', 'readonly'):
1284 if type.pymemberdef_typecode:
1285 self.public_attr_entries.append(entry)
1286 if name == "__weakref__":
1287 error(pos, "Special attribute __weakref__ cannot be exposed to Python")
1288 else:
1289 error(pos,
1290 "C attribute of type '%s' cannot be accessed from Python" % type)
1291 if visibility == 'public' and type.is_extension_type:
1292 error(pos,
1293 "Non-generic Python attribute cannot be exposed for writing from Python")
1294 return entry
1295 else:
1296 if type is unspecified_type:
1297 type = py_object_type
1298 # Add an entry for a class attribute.
1299 entry = Scope.declare_var(self, name, type, pos,
1300 cname, visibility, is_cdef)
1301 entry.is_member = 1
1302 entry.is_pyglobal = 1 # xxx: is_pyglobal changes behaviour in so many places that
1303 # I keep it in for now. is_member should be enough
1304 # later on
1305 self.namespace_cname = "(PyObject *)%s" % self.parent_type.typeptr_cname
1306 return entry
1309 def declare_pyfunction(self, name, pos):
1310 # Add an entry for a method.
1311 if name in ('__eq__', '__ne__', '__lt__', '__gt__', '__le__', '__ge__'):
1312 error(pos, "Special method %s must be implemented via __richcmp__" % name)
1313 if name == "__new__":
1314 warning(pos, "__new__ method of extension type will change semantics "
1315 "in a future version of Pyrex and Cython. Use __cinit__ instead.")
1316 name = EncodedString("__cinit__")
1317 entry = self.declare_var(name, py_object_type, pos, visibility='extern')
1318 special_sig = get_special_method_signature(name)
1319 if special_sig:
1320 # Special methods get put in the method table with a particular
1321 # signature declared in advance.
1322 entry.signature = special_sig
1323 entry.is_special = 1
1324 else:
1325 entry.signature = pymethod_signature
1326 entry.is_special = 0
1328 self.pyfunc_entries.append(entry)
1329 return entry
1331 def lookup_here(self, name):
1332 if name == "__new__":
1333 name = EncodedString("__cinit__")
1334 return ClassScope.lookup_here(self, name)
1336 def declare_cfunction(self, name, type, pos,
1337 cname = None, visibility = 'private',
1338 defining = 0, api = 0, in_pxd = 0, modifiers = ()):
1339 if get_special_method_signature(name):
1340 error(pos, "Special methods must be declared with 'def', not 'cdef'")
1341 args = type.args
1342 if not args:
1343 error(pos, "C method has no self argument")
1344 elif not args[0].type.same_as(self.parent_type):
1345 error(pos, "Self argument (%s) of C method '%s' does not match parent type (%s)" %
1346 (args[0].type, name, self.parent_type))
1347 entry = self.lookup_here(name)
1348 if entry:
1349 if not entry.is_cfunction:
1350 warning(pos, "'%s' redeclared " % name, 0)
1351 else:
1352 if defining and entry.func_cname:
1353 error(pos, "'%s' already defined" % name)
1354 #print "CClassScope.declare_cfunction: checking signature" ###
1355 if type.same_c_signature_as(entry.type, as_cmethod = 1) and type.nogil == entry.type.nogil:
1356 pass
1357 elif type.compatible_signature_with(entry.type, as_cmethod = 1) and type.nogil == entry.type.nogil:
1358 entry = self.add_cfunction(name, type, pos, cname or name, visibility='ignore', modifiers=modifiers)
1359 defining = 1
1360 else:
1361 error(pos, "Signature not compatible with previous declaration")
1362 error(entry.pos, "Previous declaration is here")
1363 else:
1364 if self.defined:
1365 error(pos,
1366 "C method '%s' not previously declared in definition part of"
1367 " extension type" % name)
1368 entry = self.add_cfunction(name, type, pos, cname or name,
1369 visibility, modifiers)
1370 if defining:
1371 entry.func_cname = self.mangle(Naming.func_prefix, name)
1372 return entry
1374 def add_cfunction(self, name, type, pos, cname, visibility, modifiers):
1375 # Add a cfunction entry without giving it a func_cname.
1376 prev_entry = self.lookup_here(name)
1377 entry = ClassScope.add_cfunction(self, name, type, pos, cname,
1378 visibility, modifiers)
1379 entry.is_cmethod = 1
1380 entry.prev_entry = prev_entry
1381 return entry
1383 def declare_property(self, name, doc, pos):
1384 entry = self.lookup_here(name)
1385 if entry is None:
1386 entry = self.declare(name, name, py_object_type, pos, 'private')
1387 entry.is_property = 1
1388 entry.doc = doc
1389 entry.scope = PropertyScope(name,
1390 outer_scope = self.global_scope(), parent_scope = self)
1391 entry.scope.parent_type = self.parent_type
1392 self.property_entries.append(entry)
1393 return entry
1395 def declare_inherited_c_attributes(self, base_scope):
1396 # Declare entries for all the C attributes of an
1397 # inherited type, with cnames modified appropriately
1398 # to work with this type.
1399 def adapt(cname):
1400 return "%s.%s" % (Naming.obj_base_cname, base_entry.cname)
1401 for base_entry in \
1402 base_scope.inherited_var_entries + base_scope.var_entries:
1403 entry = self.declare(base_entry.name, adapt(base_entry.cname),
1404 base_entry.type, None, 'private')
1405 entry.is_variable = 1
1406 self.inherited_var_entries.append(entry)
1407 for base_entry in base_scope.cfunc_entries:
1408 entry = self.add_cfunction(base_entry.name, base_entry.type,
1409 base_entry.pos, adapt(base_entry.cname),
1410 base_entry.visibility, base_entry.func_modifiers)
1411 entry.is_inherited = 1
1414 class PropertyScope(Scope):
1415 # Scope holding the __get__, __set__ and __del__ methods for
1416 # a property of an extension type.
1418 # parent_type PyExtensionType The type to which the property belongs
1420 def declare_pyfunction(self, name, pos):
1421 # Add an entry for a method.
1422 signature = get_property_accessor_signature(name)
1423 if signature:
1424 entry = self.declare(name, name, py_object_type, pos, 'private')
1425 entry.is_special = 1
1426 entry.signature = signature
1427 return entry
1428 else:
1429 error(pos, "Only __get__, __set__ and __del__ methods allowed "
1430 "in a property declaration")
1431 return None
1434 # Should this go elsewhere (and then get imported)?
1435 #------------------------------------------------------------------------------------
1437 classmethod_utility_code = Code.UtilityCode(
1438 proto = """
1439 #include "descrobject.h"
1440 static PyObject* __Pyx_Method_ClassMethod(PyObject *method); /*proto*/
1441 """,
1442 impl = """
1443 static PyObject* __Pyx_Method_ClassMethod(PyObject *method) {
1444 /* It appears that PyMethodDescr_Type is not anywhere exposed in the Python/C API */
1445 static PyTypeObject *methoddescr_type = NULL;
1446 if (methoddescr_type == NULL) {
1447 PyObject *meth = __Pyx_GetAttrString((PyObject*)&PyList_Type, "append");
1448 if (!meth) return NULL;
1449 methoddescr_type = Py_TYPE(meth);
1450 Py_DECREF(meth);
1452 if (PyObject_TypeCheck(method, methoddescr_type)) { /* cdef classes */
1453 PyMethodDescrObject *descr = (PyMethodDescrObject *)method;
1454 #if PY_VERSION_HEX < 0x03020000
1455 PyTypeObject *d_type = descr->d_type;
1456 #else
1457 PyTypeObject *d_type = descr->d_common.d_type;
1458 #endif
1459 return PyDescr_NewClassMethod(d_type, descr->d_method);
1461 else if (PyMethod_Check(method)) { /* python classes */
1462 return PyClassMethod_New(PyMethod_GET_FUNCTION(method));
1464 else if (PyCFunction_Check(method)) {
1465 return PyClassMethod_New(method);
1467 PyErr_Format(PyExc_TypeError,
1468 "Class-level classmethod() can only be called on"
1469 "a method_descriptor or instance method.");
1470 return NULL;
1472 """)