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