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