Fix matching of methods named *_get_type()
[platform/upstream/gobject-introspection.git] / giscanner / ast.py
1 # -*- Mode: Python -*-
2 # GObject-Introspection - a framework for introspecting GObject libraries
3 # Copyright (C) 2008  Johan Dahlin
4 # Copyright (C) 2008, 2009 Red Hat, Inc.
5 #
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2 of the License, or (at your option) any later version.
10 #
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the
18 # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 # Boston, MA 02111-1307, USA.
20 #
21
22 import copy
23
24 from . import message
25
26 from .message import Position
27 from .odict import odict
28 from .utils import to_underscores
29
30 class Type(object):
31     """A Type can be either:
32 * A reference to a node (target_giname)
33 * A reference to a "fundamental" type like 'utf8'
34 * A "foreign" type - this can be any string."
35 If none are specified, then it's in an "unresolved" state.  An
36 unresolved type can have two data sources; a "ctype" which comes
37 from a C type string, or a gtype_name (from g_type_name()).
38 """ # '''
39
40     def __init__(self,
41                  ctype=None,
42                  gtype_name=None,
43                  target_fundamental=None,
44                  target_giname=None,
45                  target_foreign=None,
46                  _target_unknown=False,
47                  is_const=False,
48                  origin_symbol=None):
49         self.ctype = ctype
50         self.gtype_name = gtype_name
51         self.origin_symbol = origin_symbol
52         if _target_unknown:
53             assert isinstance(self, TypeUnknown)
54         elif target_fundamental:
55             assert target_giname is None
56             assert target_foreign is None
57         elif target_giname:
58             assert '.' in target_giname
59             assert target_fundamental is None
60             assert target_foreign is None
61         elif target_foreign:
62             assert ctype is not None
63             assert target_giname is None
64             assert target_fundamental is None
65         else:
66             assert (ctype is not None) or (gtype_name is not None)
67         self.target_fundamental = target_fundamental
68         self.target_giname = target_giname
69         self.target_foreign = target_foreign
70         self.is_const = is_const
71
72     @property
73     def resolved(self):
74         return (self.target_fundamental or
75                 self.target_giname or
76                 self.target_foreign)
77
78     @property
79     def unresolved_string(self):
80         if self.ctype:
81             return self.ctype
82         elif self.gtype_name:
83             return self.gtype_name
84         else:
85             assert False
86
87     @classmethod
88     def create_from_gtype_name(cls, gtype_name):
89         """Parse a GType name (as from g_type_name()), and return a
90 Type instance.  Note that this function performs namespace lookup,
91 in contrast to the other create_type() functions."""
92         # First, is it a fundamental?
93         fundamental = type_names.get(gtype_name)
94         if fundamental is not None:
95             return cls(target_fundamental=fundamental.target_fundamental)
96         if gtype_name == 'GHashTable':
97             return Map(TYPE_ANY, TYPE_ANY, gtype_name=gtype_name)
98         elif gtype_name in ('GArray', 'GPtrArray', 'GByteArray'):
99             return Array('GLib.' + gtype_name[1:], TYPE_ANY,
100                          gtype_name=gtype_name)
101         elif gtype_name == 'GStrv':
102             bare_utf8 = TYPE_STRING.clone()
103             bare_utf8.ctype = None
104             return Array(None, bare_utf8, ctype=None, gtype_name=gtype_name,
105                          is_const=False)
106
107         # Workaround for Gdk.Rectangle being boxed alias for
108         # cairo.RectangleInt.  G-I does not support boxing of aliases.
109         # See https://bugzilla.gnome.org/show_bug.cgi?id=655423
110         if gtype_name == 'GdkRectangle':
111             gtype_name = 'CairoRectangleInt'
112
113         return cls(gtype_name=gtype_name)
114
115     def get_giname(self):
116         assert self.target_giname is not None
117         return self.target_giname.split('.')[1]
118
119     def __cmp__(self, other):
120         if self.target_fundamental:
121             return cmp(self.target_fundamental, other.target_fundamental)
122         if self.target_giname:
123             return cmp(self.target_giname, other.target_giname)
124         if self.target_foreign:
125             return cmp(self.target_foreign, other.target_foreign)
126         return cmp(self.ctype, other.ctype)
127
128     def is_equiv(self, typeval):
129         """Return True if the specified types are compatible at
130         an introspection level, disregarding their C types.
131         A sequence may be given for typeval, in which case
132         this function returns True if the type is compatible with
133         any."""
134         if isinstance(typeval, (list, tuple)):
135             for val in typeval:
136                 if self.is_equiv(val):
137                     return True
138             return False
139         return self == typeval
140
141     def clone(self):
142         return Type(target_fundamental=self.target_fundamental,
143                     target_giname=self.target_giname,
144                     target_foreign=self.target_foreign,
145                     ctype=self.ctype,
146                     is_const=self.is_const)
147
148     def __str__(self):
149         if self.target_fundamental:
150             return self.target_fundamental
151         elif self.target_giname:
152             return self.target_giname
153         elif self.target_foreign:
154             return self.target_foreign
155
156     def __repr__(self):
157         if self.target_fundamental:
158             data = 'target_fundamental=%s, ' % (self.target_fundamental, )
159         elif self.target_giname:
160             data = 'target_giname=%s, ' % (self.target_giname, )
161         elif self.target_foreign:
162             data = 'target_foreign=%s, ' % (self.target_foreign, )
163         else:
164             data = ''
165         return '%s(%sctype=%s)' % (self.__class__.__name__, data, self.ctype)
166
167 class TypeUnknown(Type):
168     def __init__(self):
169         Type.__init__(self, _target_unknown=True)
170
171 ######
172 ## Fundamental types
173 ######
174 # Two special ones
175 TYPE_NONE = Type(target_fundamental='none', ctype='void')
176 TYPE_ANY = Type(target_fundamental='gpointer', ctype='gpointer')
177 # "Basic" types
178 TYPE_BOOLEAN = Type(target_fundamental='gboolean', ctype='gboolean')
179 TYPE_INT8 = Type(target_fundamental='gint8', ctype='gint8')
180 TYPE_UINT8 = Type(target_fundamental='guint8', ctype='guint8')
181 TYPE_INT16 = Type(target_fundamental='gint16', ctype='gint16')
182 TYPE_UINT16 = Type(target_fundamental='guint16', ctype='guint16')
183 TYPE_INT32 = Type(target_fundamental='gint32', ctype='gint32')
184 TYPE_UINT32 = Type(target_fundamental='guint32', ctype='guint32')
185 TYPE_INT64 = Type(target_fundamental='gint64', ctype='gint64')
186 TYPE_UINT64 = Type(target_fundamental='guint64', ctype='guint64')
187 TYPE_CHAR = Type(target_fundamental='gchar', ctype='gchar')
188 TYPE_SHORT = Type(target_fundamental='gshort', ctype='gshort')
189 TYPE_USHORT = Type(target_fundamental='gushort', ctype='gushort')
190 TYPE_INT = Type(target_fundamental='gint', ctype='gint')
191 TYPE_UINT = Type(target_fundamental='guint', ctype='guint')
192 TYPE_LONG = Type(target_fundamental='glong', ctype='glong')
193 TYPE_ULONG = Type(target_fundamental='gulong', ctype='gulong')
194 TYPE_SIZE = Type(target_fundamental='gsize', ctype='gsize')
195 TYPE_SSIZE = Type(target_fundamental='gssize', ctype='gssize')
196 TYPE_INTPTR = Type(target_fundamental='gintptr', ctype='gintptr')
197 TYPE_UINTPTR = Type(target_fundamental='guintptr', ctype='guintptr')
198 # C99 types
199 TYPE_LONG_LONG = Type(target_fundamental='long long', ctype='long long')
200 TYPE_LONG_ULONG = Type(target_fundamental='unsigned long long',
201                        ctype='unsigned long long')
202 TYPE_FLOAT = Type(target_fundamental='gfloat', ctype='gfloat')
203 TYPE_DOUBLE = Type(target_fundamental='gdouble', ctype='gdouble')
204 # ?
205 TYPE_LONG_DOUBLE = Type(target_fundamental='long double',
206                         ctype='long double')
207 TYPE_UNICHAR = Type(target_fundamental='gunichar', ctype='gunichar')
208
209 # C types with semantics overlaid
210 TYPE_GTYPE = Type(target_fundamental='GType', ctype='GType')
211 TYPE_STRING = Type(target_fundamental='utf8', ctype='gchar*')
212 TYPE_FILENAME = Type(target_fundamental='filename', ctype='gchar*')
213
214 TYPE_VALIST = Type(target_fundamental='va_list', ctype='va_list')
215
216 BASIC_GIR_TYPES = [TYPE_BOOLEAN, TYPE_INT8, TYPE_UINT8, TYPE_INT16,
217                    TYPE_UINT16, TYPE_INT32, TYPE_UINT32, TYPE_INT64,
218                    TYPE_UINT64, TYPE_CHAR, TYPE_SHORT, TYPE_USHORT, TYPE_INT,
219                    TYPE_UINT, TYPE_LONG, TYPE_ULONG, TYPE_SIZE, TYPE_SSIZE,
220                    TYPE_LONG_LONG, TYPE_LONG_ULONG, TYPE_INTPTR, TYPE_UINTPTR,
221                    TYPE_FLOAT, TYPE_DOUBLE,
222                    TYPE_LONG_DOUBLE, TYPE_UNICHAR, TYPE_GTYPE]
223 GIR_TYPES = [TYPE_NONE, TYPE_ANY]
224 GIR_TYPES.extend(BASIC_GIR_TYPES)
225 GIR_TYPES.extend([TYPE_STRING, TYPE_FILENAME, TYPE_VALIST])
226
227 # These are the only basic types that are guaranteed to
228 # be as big as a pointer (and thus are allowed in GPtrArray)
229 POINTER_TYPES = [TYPE_ANY, TYPE_INTPTR, TYPE_UINTPTR]
230
231 INTROSPECTABLE_BASIC = list(GIR_TYPES)
232 for v in [TYPE_NONE, TYPE_ANY,
233           TYPE_LONG_LONG, TYPE_LONG_ULONG,
234           TYPE_LONG_DOUBLE, TYPE_VALIST]:
235     INTROSPECTABLE_BASIC.remove(v)
236
237 type_names = {}
238 for typeval in GIR_TYPES:
239     type_names[typeval.target_fundamental] = typeval
240 basic_type_names = {}
241 for typeval in BASIC_GIR_TYPES:
242     basic_type_names[typeval.target_fundamental] = typeval
243
244 # C builtin
245 type_names['char'] = TYPE_CHAR
246 type_names['signed char'] = TYPE_INT8
247 type_names['unsigned char'] = TYPE_UINT8
248 type_names['short'] = TYPE_SHORT
249 type_names['signed short'] = TYPE_SHORT
250 type_names['unsigned short'] = TYPE_USHORT
251 type_names['int'] = TYPE_INT
252 type_names['signed int'] = TYPE_INT
253 type_names['unsigned short int'] = TYPE_USHORT
254 type_names['signed'] = TYPE_INT
255 type_names['unsigned int'] = TYPE_UINT
256 type_names['unsigned'] = TYPE_UINT
257 type_names['long'] = TYPE_LONG
258 type_names['signed long'] = TYPE_LONG
259 type_names['unsigned long'] = TYPE_ULONG
260 type_names['unsigned long int'] = TYPE_ULONG
261 type_names['float'] = TYPE_FLOAT
262 type_names['double'] = TYPE_DOUBLE
263 type_names['char*'] = TYPE_STRING
264 type_names['void*'] = TYPE_ANY
265 type_names['void'] = TYPE_NONE
266 # Also alias the signed one here
267 type_names['signed long long'] = TYPE_LONG_LONG
268
269 # A few additional GLib type aliases
270 type_names['guchar'] = TYPE_UINT8
271 type_names['gchararray'] = TYPE_STRING
272 type_names['gchar*'] = TYPE_STRING
273 type_names['goffset'] = TYPE_INT64
274 type_names['gunichar2'] = TYPE_UINT16
275 type_names['gsize'] = TYPE_SIZE
276 type_names['gssize'] = TYPE_SSIZE
277 type_names['gintptr'] = TYPE_INTPTR
278 type_names['guintptr'] = TYPE_UINTPTR
279 type_names['gconstpointer'] = TYPE_ANY
280
281 # We used to support these; continue to do so
282 type_names['any'] = TYPE_ANY
283 type_names['boolean'] = TYPE_BOOLEAN
284 type_names['uint'] = TYPE_UINT
285 type_names['ulong'] = TYPE_ULONG
286
287 # C stdio, used in GLib public headers; squash this for now here
288 # until we move scanning into GLib and can (skip)
289 type_names['FILE*'] = TYPE_ANY
290
291 # One off C unix type definitions; note some of these may be GNU Libc
292 # specific.  If someone is actually bitten by this, feel free to do
293 # the required configure goop to determine their size and replace
294 # here.
295 #
296 # We don't want to encourage people to use these in their APIs because
297 # they compromise the platform-independence that GLib gives you.
298 # These are here mostly to avoid blowing when random platform-specific
299 # methods are added under #ifdefs inside GLib itself.  We could just (skip)
300 # the relevant methods, but on the other hand, since these types are just
301 # integers it's easy enough to expand them.
302 type_names['size_t'] = type_names['gsize']
303 type_names['time_t'] = TYPE_LONG
304 type_names['off_t'] = type_names['gsize']
305 type_names['pid_t'] = TYPE_INT
306 type_names['uid_t'] = TYPE_UINT
307 type_names['gid_t'] = TYPE_UINT
308 type_names['dev_t'] = TYPE_INT
309 type_names['socklen_t'] = TYPE_INT32
310 type_names['size_t'] = TYPE_ULONG
311 type_names['ssize_t'] = TYPE_LONG
312
313 # Obj-C
314 type_names['id'] = TYPE_ANY
315
316 ##
317 ## Parameters
318 ##
319
320 PARAM_DIRECTION_IN = 'in'
321 PARAM_DIRECTION_OUT = 'out'
322 PARAM_DIRECTION_INOUT = 'inout'
323
324 PARAM_SCOPE_CALL = 'call'
325 PARAM_SCOPE_ASYNC = 'async'
326 PARAM_SCOPE_NOTIFIED = 'notified'
327
328 PARAM_TRANSFER_NONE = 'none'
329 PARAM_TRANSFER_CONTAINER = 'container'
330 PARAM_TRANSFER_FULL = 'full'
331
332 SIGNAL_FIRST = 'first'
333 SIGNAL_LAST = 'last'
334 SIGNAL_CLEANUP = 'cleanup'
335 SIGNAL_MUST_COLLECT = 'must-collect'
336
337
338 class Namespace(object):
339     def __init__(self, name, version,
340                  identifier_prefixes=None,
341                  symbol_prefixes=None):
342         self.name = name
343         self.version = version
344         if identifier_prefixes is not None:
345             self.identifier_prefixes = identifier_prefixes
346         else:
347             self.identifier_prefixes = [name]
348         if symbol_prefixes is not None:
349             self.symbol_prefixes = symbol_prefixes
350         else:
351             ps = self.identifier_prefixes
352             self.symbol_prefixes = [to_underscores(p).lower() for p in ps]
353         # cache upper-cased versions
354         self._ucase_symbol_prefixes = [p.upper() for p in self.symbol_prefixes]
355         self._names = odict() # Maps from GIName -> node
356         self._aliases = {} # Maps from GIName -> GIName
357         self._type_names = {} # Maps from GTName -> node
358         self._ctypes = {} # Maps from CType -> node
359         self._symbols = {} # Maps from function symbols -> Function
360
361     @property
362     def names(self):
363         return self._names
364
365     @property
366     def aliases(self):
367         return self._aliases
368
369     @property
370     def type_names(self):
371         return self._type_names
372
373     @property
374     def ctypes(self):
375         return self._ctypes
376
377     def type_from_name(self, name, ctype=None):
378         """Backwards compatibility method for older .gir files, which
379 only use the 'name' attribute.  If name refers to a fundamental type,
380 create a Type object referncing it.  If name is already a
381 fully-qualified GIName like 'Foo.Bar', returns a Type targeting it .
382 Otherwise a Type targeting name qualififed with the namespace name is
383 returned."""
384         if name in type_names:
385             return Type(target_fundamental=name, ctype=ctype)
386         if '.' in name:
387             target = name
388         else:
389             target = '%s.%s' % (self.name, name)
390         return Type(target_giname=target, ctype=ctype)
391
392     def append(self, node, replace=False):
393         previous = self._names.get(node.name)
394         if previous is not None:
395             if not replace:
396                 raise ValueError("Namespace conflict: %r" % (node, ))
397             self.remove(previous)
398         # A layering violation...but oh well.
399         if isinstance(node, Alias):
400             self._aliases[node.name] = node
401         elif isinstance(node, Registered) and node.gtype_name is not None:
402             self._type_names[node.gtype_name] = node
403         elif isinstance(node, Function):
404             self._symbols[node.symbol] = node
405         assert isinstance(node, Node)
406         assert node.namespace is None
407         node.namespace = self
408         self._names[node.name] = node
409         if hasattr(node, 'ctype'):
410             self._ctypes[node.ctype] = node
411         if hasattr(node, 'symbol'):
412             self._ctypes[node.symbol] = node
413
414     def remove(self, node):
415         if isinstance(node, Alias):
416             del self._aliases[node.name]
417         elif isinstance(node, Registered) and node.gtype_name is not None:
418             del self._type_names[node.gtype_name]
419         del self._names[node.name]
420         node.namespace = None
421         if hasattr(node, 'ctype'):
422             del self._ctypes[node.ctype]
423         if isinstance(node, Function):
424             del self._symbols[node.symbol]
425
426     def float(self, node):
427         """Like remove(), but doesn't unset the node's namespace
428 back-reference, and it's still possible to look up
429 functions via get_by_symbol()."""
430         if isinstance(node, Function):
431             symbol = node.symbol
432         self.remove(node)
433         self._symbols[symbol] = node
434         node.namespace = self
435
436     def __iter__(self):
437         return iter(self._names)
438
439     def iteritems(self):
440         return self._names.iteritems()
441
442     def itervalues(self):
443         return self._names.itervalues()
444
445     def get(self, name):
446         return self._names.get(name)
447
448     def get_by_ctype(self, ctype):
449         return self._ctypes.get(ctype)
450
451     def get_by_symbol(self, symbol):
452         return self._symbols.get(symbol)
453
454     def walk(self, callback):
455         for node in self.itervalues():
456             node.walk(callback, [])
457
458 class Include(object):
459
460     def __init__(self, name, version):
461         self.name = name
462         self.version = version
463
464     @classmethod
465     def from_string(cls, string):
466         return cls(*string.split('-', 1))
467
468     def __cmp__(self, other):
469         namecmp = cmp(self.name, other.name)
470         if namecmp != 0:
471             return namecmp
472         return cmp(self.version, other.version)
473
474     def __hash__(self):
475         return hash(str(self))
476
477     def __str__(self):
478         return '%s-%s' % (self.name, self.version)
479
480 class Annotated(object):
481     """An object which has a few generic metadata
482 properties."""
483     def __init__(self):
484         self.version = None
485         self.skip = False
486         self.introspectable = True
487         self.attributes = [] # (key, value)*
488         self.deprecated = None
489         self.deprecated_version = None
490         self.doc = None
491
492 class Node(Annotated):
493     """A node is a type of object which is uniquely identified by its
494 (namespace, name) pair.  When combined with a ., this is called a
495 GIName.  It's possible for nodes to contain or point to other nodes."""
496
497     c_name = property(lambda self: self.namespace.name + self.name)
498     gi_name = property(lambda self: '%s.%s' % (self.namespace.name, self.name))
499
500     def __init__(self, name=None):
501         Annotated.__init__(self)
502         self.namespace = None # Should be set later by Namespace.append()
503         self.name = name
504         self.foreign = False
505         self.file_positions = set()
506
507     def create_type(self):
508         """Create a Type object referencing this node."""
509         assert self.namespace is not None
510         return Type(target_giname=('%s.%s' % (self.namespace.name, self.name)))
511
512     def __cmp__(self, other):
513         nscmp = cmp(self.namespace, other.namespace)
514         if nscmp != 0:
515             return nscmp
516         return cmp(self.name, other.name)
517
518     def __repr__(self):
519         return '%s(%r)' % (self.__class__.__name__, self.name)
520
521     def inherit_file_positions(self, node):
522         self.file_positions.update(node.file_positions)
523
524     def add_file_position(self, position):
525         self.file_positions.add(position)
526
527     def add_symbol_reference(self, symbol):
528         if symbol.source_filename:
529             self.add_file_position(Position(symbol.source_filename, symbol.line))
530
531     def walk(self, callback, chain):
532         res = callback(self, chain)
533         assert res in (True, False), "Walk function must return boolean, not %r" % (res, )
534         if not res:
535             return False
536         chain.append(self)
537         self._walk(callback, chain)
538         chain.pop()
539
540     def _walk(self, callback, chain):
541         pass
542
543
544 class Registered:
545     """A node that (possibly) has gtype_name and get_type."""
546     def __init__(self, gtype_name, get_type):
547         assert (gtype_name is None and get_type is None) or \
548                (gtype_name is not None and get_type is not None)
549         self.gtype_name = gtype_name
550         self.get_type = get_type
551
552
553 class Callable(Node):
554
555     def __init__(self, name, retval, parameters, throws):
556         Node.__init__(self, name)
557         self.retval = retval
558         self.parameters = parameters
559         self.throws = not not throws
560         self.instance_parameter = None # Parameter
561         self.parent = None # A Class or Interface
562
563     def get_parameter_index(self, name):
564         for i, parameter in enumerate(self.parameters):
565             if parameter.argname == name:
566                 return i
567         raise ValueError("Unknown argument %s" % (name, ))
568
569     def get_parameter(self, name):
570         for parameter in self.parameters:
571             if parameter.argname == name:
572                 return parameter
573         raise ValueError("Unknown argument %s" % (name, ))
574
575
576 class Function(Callable):
577
578     def __init__(self, name, retval, parameters, throws, symbol):
579         Callable.__init__(self, name, retval, parameters, throws)
580         self.symbol = symbol
581         self.is_method = False
582         self.is_constructor = False
583         self.shadowed_by = None # C symbol string
584         self.shadows = None # C symbol string
585         self.moved_to = None # namespaced function name string
586
587     def clone(self):
588         clone = copy.copy(self)
589         # copy the parameters array so a change to self.parameters does not
590         # influence clone.parameters.
591         clone.parameters = self.parameters[:]
592         return clone
593
594     def is_type_meta_function(self):
595         # Named correctly
596         if not (self.name.endswith('_get_type') or
597                 self.name.endswith('_get_gtype')):
598                 return False
599
600         # Doesn't have any parameters
601         if self.parameters:
602             return False
603
604         # Returns GType
605         rettype = self.retval.type
606         if (not rettype.is_equiv(TYPE_GTYPE) and
607            rettype.target_giname != 'Gtk.Type'):
608             message.warn("function '%s' returns '%r', not a GType" %
609                          (self.name, rettype))
610             return False
611
612         return True
613
614 class ErrorQuarkFunction(Function):
615
616     def __init__(self, name, retval, parameters, throws, symbol, error_domain):
617         Function.__init__(self, name, retval, parameters, throws, symbol)
618         self.error_domain = error_domain
619
620
621 class VFunction(Callable):
622
623     def __init__(self, name, retval, parameters, throws):
624         Callable.__init__(self, name, retval, parameters, throws)
625         self.invoker = None
626
627     @classmethod
628     def from_callback(cls, cb):
629         obj = cls(cb.name, cb.retval, cb.parameters[1:],
630                   cb.throws)
631         return obj
632
633
634
635 class Varargs(Type):
636
637     def __init__(self):
638         Type.__init__(self, '<varargs>', target_fundamental='<varargs>')
639
640
641 class Array(Type):
642     C = '<c>'
643     GLIB_ARRAY = 'GLib.Array'
644     GLIB_BYTEARRAY = 'GLib.ByteArray'
645     GLIB_PTRARRAY = 'GLib.PtrArray'
646
647     def __init__(self, array_type, element_type, **kwargs):
648         Type.__init__(self, target_fundamental='<array>',
649                       **kwargs)
650         if (array_type is None or array_type == self.C):
651             self.array_type = self.C
652         else:
653             assert array_type in (self.GLIB_ARRAY,
654                                   self.GLIB_BYTEARRAY,
655                                   self.GLIB_PTRARRAY), array_type
656             self.array_type = array_type
657         assert isinstance(element_type, Type)
658         self.element_type = element_type
659         self.zeroterminated = True
660         self.length_param_name = None
661         self.size = None
662
663     def clone(self):
664         arr = Array(self.array_type, self.element_type)
665         arr.zeroterminated = self.zeroterminated
666         arr.length_param_name = self.length_param_name
667         arr.size = self.size
668         return arr
669
670 class List(Type):
671
672     def __init__(self, name, element_type, **kwargs):
673         Type.__init__(self, target_fundamental='<list>',
674                       **kwargs)
675         self.name = name
676         assert isinstance(element_type, Type)
677         self.element_type = element_type
678
679     def clone(self):
680         l = List(self.name, self.element_type)
681         l.zeroterminated = self.zeroterminated
682         l.length_param_name = self.length_param_name
683         l.size = self.size
684         return l
685
686 class Map(Type):
687
688     def __init__(self, key_type, value_type, **kwargs):
689         Type.__init__(self, target_fundamental='<map>', **kwargs)
690         assert isinstance(key_type, Type)
691         self.key_type = key_type
692         assert isinstance(value_type, Type)
693         self.value_type = value_type
694
695     def clone(self):
696         return Map(self.key_type, self.value_type)
697
698 class Alias(Node):
699
700     def __init__(self, name, target, ctype=None):
701         Node.__init__(self, name)
702         self.target = target
703         self.ctype = ctype
704
705
706 class TypeContainer(Annotated):
707     """A fundamental base class for Return and Parameter."""
708
709     def __init__(self, typenode, transfer):
710         Annotated.__init__(self)
711         self.type = typenode
712         if transfer is not None:
713             self.transfer = transfer
714         elif typenode.is_const:
715             self.transfer = PARAM_TRANSFER_NONE
716         else:
717             self.transfer = None
718
719
720 class Parameter(TypeContainer):
721     """An argument to a function."""
722
723     def __init__(self, argname, typenode, direction=None,
724                  transfer=None, allow_none=False, scope=None,
725                  caller_allocates=False):
726         TypeContainer.__init__(self, typenode, transfer)
727         self.argname = argname
728         self.direction = direction
729         self.allow_none = allow_none
730         self.scope = scope
731         self.caller_allocates = caller_allocates
732         self.closure_name = None
733         self.destroy_name = None
734
735
736 class Return(TypeContainer):
737     """A return value from a function."""
738
739     def __init__(self, rtype, transfer=None):
740         TypeContainer.__init__(self, rtype, transfer)
741         self.direction = PARAM_DIRECTION_OUT
742
743
744 class Enum(Node, Registered):
745
746     def __init__(self, name, ctype,
747                  gtype_name=None,
748                  get_type=None,
749                  c_symbol_prefix=None,
750                  members=None):
751         Node.__init__(self, name)
752         Registered.__init__(self, gtype_name, get_type)
753         self.c_symbol_prefix = c_symbol_prefix
754         self.ctype = ctype
755         self.members = members
756         # Associated error domain name
757         self.error_domain = None
758         self.static_methods = []
759
760     def _walk(self, callback, chain):
761         for meth in self.static_methods:
762             meth.walk(callback, chain)
763
764
765 class Bitfield(Node, Registered):
766
767     def __init__(self, name, ctype,
768                  gtype_name=None,
769                  c_symbol_prefix=None,
770                  get_type=None,
771                  members=None):
772         Node.__init__(self, name)
773         Registered.__init__(self, gtype_name, get_type)
774         self.ctype = ctype
775         self.c_symbol_prefix = c_symbol_prefix
776         self.members = members
777         self.static_methods = []
778
779     def _walk(self, callback, chain):
780         for meth in self.static_methods:
781             meth.walk(callback, chain)
782
783
784 class Member(Annotated):
785
786     def __init__(self, name, value, symbol, nick):
787         Annotated.__init__(self)
788         self.name = name
789         self.value = value
790         self.symbol = symbol
791         self.nick = nick
792
793     def __cmp__(self, other):
794         return cmp(self.name, other.name)
795
796
797
798 class Compound(Node, Registered):
799     def __init__(self, name,
800                  ctype=None,
801                  gtype_name=None,
802                  get_type=None,
803                  c_symbol_prefix=None,
804                  disguised=False):
805         Node.__init__(self, name)
806         Registered.__init__(self, gtype_name, get_type)
807         self.ctype = ctype
808         self.methods = []
809         self.static_methods = []
810         self.fields = []
811         self.constructors = []
812         self.disguised = disguised
813         self.gtype_name = gtype_name
814         self.get_type = get_type
815         self.c_symbol_prefix = c_symbol_prefix
816
817     def add_gtype(self, gtype_name, get_type):
818         self.gtype_name = gtype_name
819         self.get_type = get_type
820
821     def _walk(self, callback, chain):
822         for ctor in self.constructors:
823             ctor.walk(callback, chain)
824         for func in self.methods:
825             func.walk(callback, chain)
826         for func in self.static_methods:
827             func.walk(callback, chain)
828         for field in self.fields:
829             if field.anonymous_node is not None:
830                 field.anonymous_node.walk(callback, chain)
831
832 class Field(Annotated):
833
834     def __init__(self, name, typenode, readable, writable, bits=None,
835                  anonymous_node=None):
836         Annotated.__init__(self)
837         assert (typenode or anonymous_node)
838         self.name = name
839         self.type = typenode
840         self.readable = readable
841         self.writable = writable
842         self.bits = bits
843         self.anonymous_node = anonymous_node
844         self.private = False
845
846     def __cmp__(self, other):
847         return cmp(self.name, other.name)
848
849
850 class Record(Compound):
851
852     def __init__(self, name,
853                  ctype=None,
854                  gtype_name=None,
855                  get_type=None,
856                  c_symbol_prefix=None,
857                  disguised=False):
858         Compound.__init__(self, name,
859                           ctype=ctype,
860                           gtype_name=gtype_name,
861                           get_type=get_type,
862                           c_symbol_prefix=c_symbol_prefix,
863                           disguised=disguised)
864         # If non-None, this record defines the FooClass C structure
865         # for some Foo GObject (or similar for GInterface)
866         self.is_gtype_struct_for = None
867
868
869 class Union(Compound):
870
871     def __init__(self, name,
872                  ctype=None,
873                  gtype_name=None,
874                  get_type=None,
875                  c_symbol_prefix=None,
876                  disguised=False):
877         Compound.__init__(self, name,
878                           ctype=ctype,
879                           gtype_name=gtype_name,
880                           get_type=get_type,
881                           c_symbol_prefix=c_symbol_prefix,
882                           disguised=disguised)
883
884
885 class Boxed(Node, Registered):
886     """A boxed type with no known associated structure/union."""
887     def __init__(self, name,
888                  gtype_name=None,
889                  get_type=None,
890                  c_symbol_prefix=None):
891         assert gtype_name is not None
892         assert get_type is not None
893         Node.__init__(self, name)
894         Registered.__init__(self, gtype_name, get_type)
895         if get_type is not None:
896             assert c_symbol_prefix is not None
897         self.c_symbol_prefix = c_symbol_prefix
898         self.constructors = []
899         self.methods = []
900         self.static_methods = []
901
902     def _walk(self, callback, chain):
903         for ctor in self.constructors:
904             ctor.walk(callback, chain)
905         for meth in self.methods:
906             meth.walk(callback, chain)
907         for meth in self.static_methods:
908             meth.walk(callback, chain)
909
910
911 class Signal(Callable):
912
913     def __init__(self, name, retval, parameters, when=None,
914                  no_recurse=False, detailed=False, action=False,
915                  no_hooks=False):
916         Callable.__init__(self, name, retval, parameters, False)
917         self.when = when
918         self.no_recurse = no_recurse
919         self.detailed = detailed
920         self.action = action
921         self.no_hooks = no_hooks
922
923
924 class Class(Node, Registered):
925
926     def __init__(self, name, parent,
927                  ctype=None,
928                  gtype_name=None,
929                  get_type=None,
930                  c_symbol_prefix=None,
931                  is_abstract=False):
932         Node.__init__(self, name)
933         Registered.__init__(self, gtype_name, get_type)
934         self.ctype = ctype
935         self.c_symbol_prefix = c_symbol_prefix
936         self.parent = parent
937         self.fundamental = False
938         self.unref_func = None
939         self.ref_func = None
940         self.set_value_func = None
941         self.get_value_func = None
942         # When we're in the scanner, we keep around a list
943         # of parents so that we can transparently fall back
944         # if there are 'hidden' parents
945         self.parent_chain = []
946         self.glib_type_struct = None
947         self.is_abstract = is_abstract
948         self.methods = []
949         self.virtual_methods = []
950         self.static_methods = []
951         self.interfaces = []
952         self.constructors = []
953         self.properties = []
954         self.fields = []
955         self.signals = []
956
957     def _walk(self, callback, chain):
958         for meth in self.methods:
959             meth.walk(callback, chain)
960         for meth in self.virtual_methods:
961             meth.walk(callback, chain)
962         for meth in self.static_methods:
963             meth.walk(callback, chain)
964         for ctor in self.constructors:
965             ctor.walk(callback, chain)
966         for field in self.fields:
967             if field.anonymous_node:
968                 field.anonymous_node.walk(callback, chain)
969         for sig in self.signals:
970             sig.walk(callback, chain)
971
972
973 class Interface(Node, Registered):
974
975     def __init__(self, name, parent,
976                  ctype=None,
977                  gtype_name=None,
978                  get_type=None,
979                  c_symbol_prefix=None):
980         Node.__init__(self, name)
981         Registered.__init__(self, gtype_name, get_type)
982         self.ctype = ctype
983         self.c_symbol_prefix = c_symbol_prefix
984         self.parent = parent
985         self.parent_chain = []
986         self.methods = []
987         self.signals = []
988         self.static_methods = []
989         self.virtual_methods = []
990         self.glib_type_struct = None
991         self.properties = []
992         self.fields = []
993         self.prerequisites = []
994
995     def _walk(self, callback, chain):
996         for meth in self.methods:
997             meth.walk(callback, chain)
998         for meth in self.static_methods:
999             meth.walk(callback, chain)
1000         for meth in self.virtual_methods:
1001             meth.walk(callback, chain)
1002         for field in self.fields:
1003             if field.anonymous_node:
1004                 field.anonymous_node.walk(callback, chain)
1005         for sig in self.signals:
1006             sig.walk(callback, chain)
1007
1008
1009 class Constant(Node):
1010
1011     def __init__(self, name, value_type, value, ctype):
1012         Node.__init__(self, name)
1013         self.value_type = value_type
1014         self.value = value
1015         self.ctype = ctype
1016
1017
1018 class Property(Node):
1019
1020     def __init__(self, name, typeobj, readable, writable,
1021                  construct, construct_only, transfer=None):
1022         Node.__init__(self, name)
1023         self.type = typeobj
1024         self.readable = readable
1025         self.writable = writable
1026         self.construct = construct
1027         self.construct_only = construct_only
1028         if transfer is None:
1029             self.transfer = PARAM_TRANSFER_NONE
1030         else:
1031             self.transfer = transfer
1032         self.parent = None # A Class or Interface
1033
1034
1035 class Callback(Callable):
1036
1037     def __init__(self, name, retval, parameters, throws, ctype=None):
1038         Callable.__init__(self, name, retval, parameters, throws)
1039         self.ctype = ctype