Remove dbeug print
[gnome.gobject-introspection] / giscanner / glibtransformer.py
1 # -*- Mode: Python -*-
2 # GObject-Introspection - a framework for introspecting GObject libraries
3 # Copyright (C) 2008  Johan Dahlin
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 # 02110-1301, USA.
19 #
20
21 import os
22 import re
23 import ctypes
24 from ctypes.util import find_library
25
26 from . import cgobject
27 from .ast import (Callback, Enum, Function, Member, Namespace, Parameter,
28                   Sequence, Property, Return, Struct, Type, Alias,
29                   Union, type_name_from_ctype)
30 from .transformer import Names
31 from .glibast import (GLibBoxed, GLibEnum, GLibEnumMember, GLibFlags,
32                       GLibInterface, GLibObject, GLibSignal, GLibBoxedStruct,
33                       GLibBoxedUnion, GLibBoxedOther, type_names)
34 from .utils import extract_libtool, to_underscores, to_underscores_noprefix
35
36
37 SYMBOL_BLACKLIST = [
38     # These ones break GError conventions
39     'g_simple_async_result_new_from_error',
40     'g_simple_async_result_set_from_error',
41     'g_simple_async_result_propagate_error',
42     'g_simple_async_result_report_error_in_idle',
43     'gtk_print_operation_get_error',
44 ]
45
46 SYMBOL_BLACKLIST_RE = [re.compile(x) for x in \
47                            [r'\w+_marshal_[A-Z]+__', ]]
48
49
50 class Unresolved(object):
51
52     def __init__(self, target):
53         self.target = target
54
55
56 class UnknownTypeError(Exception):
57     pass
58
59
60 class GLibTransformer(object):
61
62     def __init__(self, transformer, noclosure=False):
63         self._transformer = transformer
64         self._namespace_name = None
65         self._names = Names()
66         self._uscore_type_names = {}
67         self._libraries = []
68         self._failed_types = {}
69         self._boxed_types = {}
70         self._private_internal_types = {}
71         self._noclosure = noclosure
72         self._validating = False
73
74     # Public API
75
76     def add_library(self, libname):
77         # For testing mainly.
78         libtool_libname = 'lib' + libname + '.la'
79         if os.path.exists(libtool_libname):
80             found_libname = extract_libtool(libtool_libname)
81         elif libname.endswith('.la'):
82             found_libname = extract_libtool(libname)
83         else:
84             found_libname = find_library(libname)
85         if not found_libname:
86             raise ValueError("Failed to find library: %r" % (libname, ))
87         self._libraries.append(ctypes.cdll.LoadLibrary(found_libname))
88
89     def _print_statistics(self):
90         nodes = list(self._names.names.itervalues())
91
92         def count_type(otype):
93             return len([x for x in nodes
94                         if isinstance(x[1], otype)])
95         objectcount = count_type(GLibObject)
96         ifacecount = count_type(GLibInterface)
97         enumcount = count_type(GLibEnum)
98         print " %d nodes; %d objects, %d interfaces, %d enumsr" \
99             % (len(nodes), objectcount, ifacecount, enumcount)
100
101     def parse(self):
102         namespace = self._transformer.parse()
103         self._namespace_name = namespace.name
104
105         # First pass: parsing
106         for node in namespace.nodes:
107             self._parse_node(node)
108
109         # Introspection is done from within parsing
110
111         # Second pass: pair boxed structures
112         for boxed in self._boxed_types.itervalues():
113             self._pair_boxed_type(boxed)
114         # Third pass: delete class structures, resolve
115         # all types we now know about
116         nodes = list(self._names.names.itervalues())
117         for (ns, node) in nodes:
118             try:
119                 self._resolve_node(node)
120             except KeyError, e:
121                 print "WARNING: DELETING node %s: %s" % (node.name, e)
122                 self._remove_attribute(node.name)
123             # associate GtkButtonClass with GtkButton
124             if isinstance(node, Struct):
125                 self._pair_class_struct(node)
126         for (ns, alias) in self._names.aliases.itervalues():
127             self._resolve_alias(alias)
128
129         self._print_statistics()
130         # Fourth pass: ensure all types are known
131         if not self._noclosure:
132             self._validate(nodes)
133
134         # Create a new namespace with what we found
135         namespace = Namespace(namespace.name)
136         namespace.nodes = map(lambda x: x[1], self._names.aliases.itervalues())
137         for (ns, x) in self._names.names.itervalues():
138             namespace.nodes.append(x)
139         return namespace
140
141     # Private
142
143     def _add_attribute(self, node, replace=False):
144         node_name = node.name
145         if (not replace) and node_name in self._names.names:
146             return
147         self._names.names[node_name] = (None, node)
148
149     def _remove_attribute(self, name):
150         del self._names.names[name]
151
152     def _get_attribute(self, name):
153         node = self._names.names.get(name)
154         if node:
155             return node[1]
156         return None
157
158     def _register_internal_type(self, type_name, node):
159         self._names.type_names[type_name] = (None, node)
160         uscored = to_underscores(type_name).lower()
161         self._uscore_type_names[uscored] = node
162         # Besides the straight underscore conversion, we also try
163         # removing the underscores from the namespace as a possible C
164         # mapping; e.g. it's webkit_web_view, not web_kit_web_view
165         suffix = self._transformer.strip_namespace_object(type_name)
166         prefix = type_name[:-len(suffix)]
167         no_uscore_prefixed = (prefix + '_' + to_underscores(suffix)).lower()
168         self._uscore_type_names[no_uscore_prefixed] = node
169
170     # Helper functions
171
172     def _create_type(self, type_id):
173         ctype = cgobject.type_name(type_id)
174         type_name = type_name_from_ctype(ctype)
175         type_name = type_name.replace('*', '')
176         type_name = self._resolve_type_name(type_name)
177         return Type(type_name, ctype)
178
179     def _resolve_gtypename(self, gtype_name):
180         try:
181             return self._transformer.gtypename_to_giname(gtype_name,
182                                                          self._names)
183         except KeyError, e:
184             return Unresolved(gtype_name)
185
186     def _create_gobject(self, node):
187         type_name = 'G' + node.name
188         if type_name == 'GObject':
189             parent_gitype = None
190             symbol = 'intern'
191         else:
192             type_id = cgobject.type_from_name(type_name)
193             parent_type_name = cgobject.type_name(
194                 cgobject.type_parent(type_id))
195             parent_gitype = self._resolve_gtypename(parent_type_name)
196             symbol = to_underscores(type_name).lower() + '_get_type'
197         node = GLibObject(node.name, parent_gitype, type_name, symbol)
198         type_id = cgobject.TYPE_OBJECT
199         self._introspect_properties(node, type_id)
200         self._introspect_signals(node, type_id)
201         self._add_attribute(node)
202         self._register_internal_type(type_name, node)
203
204     # Parser
205
206     def _parse_node(self, node):
207         if isinstance(node, Enum):
208             self._parse_enum(node)
209         elif isinstance(node, Function):
210             self._parse_function(node)
211         elif isinstance(node, Struct):
212             self._parse_struct(node)
213         elif isinstance(node, Callback):
214             self._parse_callback(node)
215         elif isinstance(node, Alias):
216             self._parse_alias(node)
217         elif isinstance(node, Member):
218             # FIXME: atk_misc_instance singletons
219             pass
220         elif isinstance(node, Union):
221             self._parse_union(node)
222         else:
223             print 'GLIB Transformer: Unhandled node:', node
224
225     def _parse_alias(self, alias):
226         self._names.aliases[alias.name] = (None, alias)
227
228     def _parse_enum(self, enum):
229         self._add_attribute(enum)
230
231     def _parse_function(self, func):
232         if func.symbol in SYMBOL_BLACKLIST:
233             return
234         if func.symbol.startswith('_'):
235             return
236         for regexp in SYMBOL_BLACKLIST_RE:
237             if regexp.match(func.symbol):
238                 return
239         if self._parse_get_type_function(func):
240             return
241
242         self._add_attribute(func)
243
244     def _parse_get_type_function(self, func):
245         symbol = func.symbol
246         if not symbol.endswith('_get_type'):
247             return False
248         if self._namespace_name == 'GLib':
249             # No GObjects in GLib
250             return False
251         # GType *_get_type(void)
252         # This is a bit fishy, why do we need all these aliases?
253         if func.retval.type.name not in ['Type',
254                                          'GType',
255                                          'Object.Type',
256                                          'GObject.Type',
257                                          'Gtk.Type',
258                                          'GObject.GType']:
259             print ("Warning: *_get_type function returns '%r'"
260                    ", not GObject.Type") % (func.retval.type.name, )
261             return False
262         if func.parameters:
263             return False
264
265         if not self._libraries:
266             print "Warning: No libraries loaded, cannot call %s" % (symbol, )
267             return False
268
269         for library in self._libraries:
270             try:
271                 func = getattr(library, symbol)
272                 break
273             except AttributeError:
274                 continue
275         else:
276             print 'Warning: could not find symbol: %s' % symbol
277             name = symbol.replace('_get_type', '')
278             self._failed_types[name] = True
279             return False
280
281         func.restype = cgobject.GType
282         func.argtypes = []
283         type_id = func()
284         self._introspect_type(type_id, symbol)
285         return True
286
287     def _name_is_internal_gtype(self, giname):
288         try:
289             node = self._get_attribute(giname)
290             return isinstance(node, (GLibObject, GLibInterface,
291                                      GLibEnum, GLibFlags))
292         except KeyError, e:
293             return False
294
295     def _parse_method(self, func):
296         if not func.parameters:
297             return False
298         return self._parse_method_common(func, True)
299
300     def _parse_constructor(self, func):
301         return self._parse_method_common(func, False)
302
303     def _parse_method_common(self, func, is_method):
304         # Skip _get_type functions, we processed them
305         # already
306         if func.symbol.endswith('_get_type'):
307             return None
308         if self._namespace_name == 'GLib':
309             # No GObjects in GLib
310             return None
311
312         if not is_method:
313             target_arg = func.retval
314         else:
315             target_arg = func.parameters[0]
316         target_arg.type = self._resolve_param_type(target_arg.type)
317
318         if is_method:
319             # Methods require their first arg to be a known class
320             # Look at the original C type (before namespace stripping), without
321             # pointers: GtkButton -> gtk_button_, so we can figure out the
322             # method name
323             argtype = target_arg.type.ctype.replace('*', '')
324             name = self._transformer.strip_namespace_object(argtype)
325             name_uscore = to_underscores_noprefix(name).lower()
326             name_offset = func.symbol.find(name_uscore)
327             if name_offset < 0:
328                 return None
329             prefix = func.symbol[:name_offset+len(name_uscore)]
330         else:
331             # Constructors must have _new
332             # Take everything before that as class name
333             new_idx = func.symbol.find('_new')
334             if new_idx < 0:
335                 return None
336             # Constructors don't return basic types
337             derefed = self._transformer.follow_aliases(target_arg.type.name,
338                                                        self._names)
339             if derefed in type_names:
340                 #print "NOTE: Rejecting constructor returning basic: %r" \
341                 #    % (func.symbol, )
342                 return None
343             prefix = func.symbol[:new_idx]
344
345         klass = None
346
347         def valid_matching_klass(tclass):
348             if tclass is None:
349                 return False
350             elif isinstance(klass, (GLibEnum, GLibFlags)):
351                 return False
352             elif not isinstance(tclass, (GLibObject, GLibBoxed,
353                                           GLibInterface)):
354                 return False
355             else:
356                 return True
357
358         klass = self._uscore_type_names.get(prefix)
359         if klass is None:
360             #print "NOTE: No valid matching class for likely "+\
361             #    "method or constructor: %r" % (func.symbol, )
362             return None
363         # Enums can't have ctors or methods
364         if isinstance(klass, (GLibEnum, GLibFlags)):
365             return None
366
367         # The _uscore_type_names member holds the plain GLibBoxed
368         # object; we want to actually use the struct/record associated
369         if isinstance(klass, GLibBoxed):
370             name = self._transformer.strip_namespace_object(klass.type_name)
371             klass = self._get_attribute(name)
372
373         if not is_method:
374             # Interfaces can't have constructors, punt to global scope
375             if isinstance(klass, (GLibInterface, GLibBoxed)):
376                 #print "NOTE: Rejecting constructor for"+\
377                 #    " interface type: %r" % (func.symbol, )
378                 return None
379             # TODO - check that the return type is a subclass of the
380             # class from the prefix
381
382         self._remove_attribute(func.name)
383         # Strip namespace and object prefix: gtk_window_new -> new
384         func.name = func.symbol[len(prefix)+1:]
385         if is_method:
386             klass.methods.append(func)
387         else:
388             klass.constructors.append(func)
389         return func
390
391     def _parse_struct(self, struct):
392         # This is a hack, but GObject is a rather fundamental piece so.
393         internal_names = ["Object", 'InitiallyUnowned']
394         g_internal_names = ["G" + x for x in internal_names]
395         if (self._namespace_name == 'GObject' and
396             struct.name in internal_names):
397             self._create_gobject(struct)
398             return
399         elif struct.name in g_internal_names:
400             # Avoid duplicates
401             return
402         node = self._names.names.get(struct.name)
403         if node is None:
404             self._add_attribute(struct, replace=True)
405             return
406         (ns, node) = node
407         node.fields = struct.fields[:]
408
409     def _parse_union(self, union):
410         node = self._names.names.get(union.name)
411         if node is None:
412             self._add_attribute(union, replace=True)
413             return
414         (ns, node) = node
415         node.fields = union.fields[:]
416
417     def _parse_callback(self, callback):
418         self._add_attribute(callback)
419
420     def _strip_class_suffix(self, name):
421         if (name.endswith('Class') or
422             name.endswith('Iface')):
423             return name[:-5]
424         elif name.endswith('Interface'):
425             return name[:-9]
426         else:
427             return name
428
429     def _arg_is_failed(self, param):
430         ctype = self._transformer.ctype_of(param).replace('*', '')
431         uscored = to_underscores(self._strip_class_suffix(ctype)).lower()
432         if uscored in self._failed_types:
433             print "Warning: failed type: %r" % (param, )
434             return True
435         return False
436
437     def _pair_class_struct(self, maybe_class):
438         name = self._strip_class_suffix(maybe_class.name)
439         if name == maybe_class.name:
440             return
441
442         if self._arg_is_failed(maybe_class):
443             print "WARNING: deleting no-type %r" % (maybe_class.name, )
444             del self._names.names[maybe_class.name]
445             return
446
447         name = self._resolve_type_name(name)
448         resolved = self._transformer.strip_namespace_object(name)
449         pair_class = self._get_attribute(resolved)
450         if pair_class and isinstance(pair_class,
451                                      (GLibObject, GLibInterface)):
452             for field in maybe_class.fields[1:]:
453                 pair_class.fields.append(field)
454             return
455         name = self._transformer.strip_namespace_object(maybe_class.name)
456         pair_class = self._get_attribute(name)
457         if pair_class and isinstance(pair_class,
458                                      (GLibObject, GLibInterface)):
459
460             del self._names.names[maybe_class.name]
461
462     # Introspection
463
464     def _introspect_type(self, type_id, symbol):
465         fundamental_type_id = cgobject.type_fundamental(type_id)
466         if (fundamental_type_id == cgobject.TYPE_ENUM or
467             fundamental_type_id == cgobject.TYPE_FLAGS):
468             self._introspect_enum(fundamental_type_id, type_id, symbol)
469         elif fundamental_type_id == cgobject.TYPE_OBJECT:
470             self._introspect_object(type_id, symbol)
471         elif fundamental_type_id == cgobject.TYPE_INTERFACE:
472             self._introspect_interface(type_id, symbol)
473         elif fundamental_type_id == cgobject.TYPE_BOXED:
474             self._introspect_boxed(type_id, symbol)
475         elif fundamental_type_id == cgobject.TYPE_BOXED:
476             self._introspect_boxed(type_id, symbol)
477         elif fundamental_type_id == cgobject.TYPE_POINTER:
478             # FIXME: Should we do something about these?
479             #        GHashTable, GValue and a few other fundamentals are
480             #        covered here
481             return
482         else:
483             print 'unhandled GType: %s(%d)' % (cgobject.type_name(type_id),
484                                                type_id)
485
486     def _introspect_enum(self, ftype_id, type_id, symbol):
487         type_class = cgobject.type_class_ref(type_id)
488         if type_class is None:
489             return
490
491         members = []
492         for enum_value in type_class.get_values():
493             members.append(GLibEnumMember(enum_value.value_nick,
494                                           enum_value.value,
495                                           enum_value.value_name,
496                                           enum_value.value_nick))
497
498         klass = (GLibFlags if ftype_id == cgobject.TYPE_FLAGS else GLibEnum)
499         type_name = cgobject.type_name(type_id)
500         enum_name = self._transformer.strip_namespace_object(type_name)
501         node = klass(enum_name, type_name, members, symbol)
502         self._add_attribute(node, replace=True)
503         self._register_internal_type(type_name, node)
504
505     def _introspect_object(self, type_id, symbol):
506         type_name = cgobject.type_name(type_id)
507         # We handle this specially above; in 2.16 and below there
508         # was no g_object_get_type, for later versions we need
509         # to skip it
510         if type_name == 'GObject':
511             return
512         parent_type_name = cgobject.type_name(cgobject.type_parent(type_id))
513         parent_gitype = self._resolve_gtypename(parent_type_name)
514         node = GLibObject(
515             self._transformer.strip_namespace_object(type_name),
516             parent_gitype,
517             type_name, symbol)
518         self._introspect_properties(node, type_id)
519         self._introspect_signals(node, type_id)
520         self._introspect_implemented_interfaces(node, type_id)
521         self._add_attribute(node, replace=True)
522         self._register_internal_type(type_name, node)
523
524     def _introspect_interface(self, type_id, symbol):
525         type_name = cgobject.type_name(type_id)
526         parent_type_name = cgobject.type_name(cgobject.type_parent(type_id))
527         if parent_type_name == 'GInterface':
528             parent_gitype = None
529         else:
530             parent_gitype = self._resolve_gtypename(parent_type_name)
531         node = GLibInterface(
532             self._transformer.strip_namespace_object(type_name),
533             parent_gitype,
534             type_name, symbol)
535         self._introspect_properties(node, type_id)
536         self._introspect_signals(node, type_id)
537         # GtkFileChooserEmbed is an example of a private interface, we
538         # just filter them out
539         if symbol.startswith('_'):
540             print "NOTICE: Marking %s as internal type" % (type_name, )
541             self._private_internal_types[type_name] = node
542         else:
543             self._add_attribute(node, replace=True)
544             self._register_internal_type(type_name, node)
545
546     def _introspect_boxed(self, type_id, symbol):
547         type_name = cgobject.type_name(type_id)
548         # This one doesn't go in the main namespace; we associate it with
549         # the struct or union
550         node = GLibBoxed(type_name, symbol)
551         self._boxed_types[node.type_name] = node
552         self._register_internal_type(type_name, node)
553
554     def _introspect_implemented_interfaces(self, node, type_id):
555         fundamental_type_id = cgobject.type_fundamental(type_id)
556         if fundamental_type_id != cgobject.TYPE_OBJECT:
557             raise AssertionError
558         interfaces = cgobject.type_interfaces(type_id)
559         gt_interfaces = []
560         for interface_typeid in interfaces:
561             iname = cgobject.type_name(interface_typeid)
562             gitype = self._resolve_gtypename(iname)
563             gt_interfaces.append(gitype)
564         node.interfaces = gt_interfaces
565
566     def _introspect_properties(self, node, type_id):
567         fundamental_type_id = cgobject.type_fundamental(type_id)
568         if fundamental_type_id == cgobject.TYPE_OBJECT:
569             pspecs = cgobject.object_class_list_properties(type_id)
570         elif fundamental_type_id == cgobject.TYPE_INTERFACE:
571             pspecs = cgobject.object_interface_list_properties(type_id)
572         else:
573             raise AssertionError
574
575         for pspec in pspecs:
576             if pspec.owner_type != type_id:
577                 continue
578             ctype = cgobject.type_name(pspec.value_type)
579             readable = (pspec.flags & 1) != 0
580             writable = (pspec.flags & 2) != 0
581             construct = (pspec.flags & 4) != 0
582             construct_only = (pspec.flags & 8) != 0
583             node.properties.append(Property(
584                 pspec.name,
585                 type_name_from_ctype(ctype),
586                 readable, writable, construct, construct_only,
587                 ctype,
588                 ))
589
590     def _introspect_signals(self, node, type_id):
591         for signal_info in cgobject.signal_list(type_id):
592             rtype = self._create_type(signal_info.return_type)
593             return_ = Return(rtype)
594             signal = GLibSignal(signal_info.signal_name, return_)
595             for i, parameter in enumerate(signal_info.get_params()):
596                 if i == 0:
597                     name = 'object'
598                 else:
599                     name = 'p%s' % (i-1, )
600                 ptype = self._create_type(parameter)
601                 param = Parameter(name, ptype)
602                 signal.parameters.append(param)
603             node.signals.append(signal)
604
605     # Resolver
606
607     def _resolve_type_name(self, type_name, ctype=None):
608         # Workaround glib bug #548689, to be included in 2.18.0
609         if type_name == "GParam":
610             type_name = "GObject.ParamSpec"
611
612         res = self._transformer.resolve_type_name_full
613         try:
614             return res(type_name, ctype, self._names)
615         except KeyError, e:
616             return self._transformer.resolve_type_name(type_name, ctype)
617
618     def _validate_type_name(self, name):
619         if name in type_names:
620             return True
621         if name.find('.') >= 0:
622             return True
623         if name in self._names.aliases:
624             return True
625         if name in self._names.names:
626             return True
627         return False
628
629     def _validate_type(self, ptype):
630         if isinstance(ptype, Sequence):
631             etype = ptype.element_type
632             if isinstance(etype, Sequence):
633                 return self._validate_type(etype)
634             return self._validate_type_name(etype)
635         return self._validate_type_name(ptype.name)
636
637     def _resolve_param_type_validate(self, ptype):
638         ptype = self._resolve_param_type(ptype)
639         if self._validating and not self._validate_type(ptype):
640             raise UnknownTypeError("Unknown type %r" % (ptype, ))
641         return ptype
642
643     def _resolve_param_type(self, ptype):
644         try:
645             return self._transformer.resolve_param_type_full(ptype,
646                                                              self._names)
647         except KeyError, e:
648             return self._transformer.resolve_param_type(ptype)
649         return ptype
650
651     def _resolve_node(self, node):
652         if isinstance(node, Function):
653             self._resolve_function_toplevel(node)
654
655         elif isinstance(node, Callback):
656             self._resolve_function(node)
657         elif isinstance(node, GLibObject):
658             self._resolve_glib_object(node)
659         elif isinstance(node, GLibInterface):
660             self._resolve_glib_interface(node)
661         elif isinstance(node, Struct):
662             self._resolve_struct(node)
663         elif isinstance(node, Union):
664             self._resolve_union(node)
665         elif isinstance(node, Alias):
666             self._resolve_alias(node)
667
668     def _resolve_function_toplevel(self, func):
669         newfunc = self._parse_constructor(func)
670         if not newfunc:
671             newfunc = self._parse_method(func)
672             if not newfunc:
673                 self._resolve_function(func)
674                 return
675         self._resolve_function(newfunc)
676
677     def _pair_boxed_type(self, boxed):
678         name = self._transformer.strip_namespace_object(boxed.type_name)
679         pair_node = self._get_attribute(name)
680         if not pair_node:
681             boxed_item = GLibBoxedOther(name, boxed.type_name,
682                                         boxed.get_type)
683         elif isinstance(pair_node, Struct):
684             boxed_item = GLibBoxedStruct(pair_node.name, boxed.type_name,
685                                          boxed.get_type)
686             boxed_item.fields = pair_node.fields
687         elif isinstance(pair_node, Union):
688             boxed_item = GLibBoxedUnion(pair_node.name, boxed.type_name,
689                                          boxed.get_type)
690             boxed_item.fields = pair_node.fields
691         else:
692             return False
693         self._add_attribute(boxed_item, replace=True)
694
695     def _resolve_struct(self, node):
696         for field in node.fields:
697             self._resolve_field(field)
698
699     def _resolve_union(self, node):
700         for field in node.fields:
701             self._resolve_field(field)
702
703     def _force_resolve(self, item, allow_unknown=False):
704         if isinstance(item, Unresolved):
705             if item.target in self._private_internal_types:
706                 return None
707             try:
708                 return self._transformer.gtypename_to_giname(item.target,
709                                                              self._names)
710             except KeyError, e:
711                 if allow_unknown:
712                     print "WARNING: Skipping unknown interface %s" % \
713                         (item.target, )
714                     return None
715                 else:
716                     raise
717         if item in self._private_internal_types:
718             return None
719         return item
720
721     def _resolve_glib_interface(self, node):
722         node.parent = self._force_resolve(node.parent)
723         self._resolve_methods(node.methods)
724         self._resolve_properties(node.properties)
725         self._resolve_signals(node.signals)
726
727     def _resolve_glib_object(self, node):
728         node.parent = self._force_resolve(node.parent)
729         node.interfaces = filter(None,
730             [self._force_resolve(x, allow_unknown=True)
731                                     for x in node.interfaces])
732         self._resolve_constructors(node.constructors)
733         self._resolve_methods(node.methods)
734         self._resolve_properties(node.properties)
735         self._resolve_signals(node.signals)
736
737     def _resolve_glib_boxed(self, node):
738         self._resolve_constructors(node.constructors)
739         self._resolve_methods(node.methods)
740
741     def _resolve_constructors(self, constructors):
742         for ctor in constructors:
743             self._resolve_function(ctor)
744
745     def _resolve_methods(self, methods):
746         for method in methods:
747             self._resolve_function(method)
748
749     def _resolve_signals(self, signals):
750         for signal in signals:
751             self._resolve_function(signal)
752
753     def _resolve_properties(self, properties):
754         for prop in properties:
755             self._resolve_property(prop)
756
757     def _resolve_property(self, prop):
758         prop.type = self._resolve_param_type(prop.type)
759
760     def _resolve_function(self, func):
761         self._resolve_parameters(func.parameters)
762         func.retval.type = self._resolve_param_type(func.retval.type)
763
764     def _resolve_parameters(self, parameters):
765         for parameter in parameters:
766             parameter.type = self._resolve_param_type(parameter.type)
767
768     def _resolve_field(self, field):
769         if isinstance(field, Callback):
770             self._resolve_function(field)
771             return
772         field.type = self._resolve_param_type(field.type)
773
774     def _resolve_alias(self, alias):
775         alias.target = self._resolve_type_name(alias.target, alias.target)
776
777     # Validation
778
779     def _validate(self, nodes):
780         nodes = list(self._names.names.itervalues())
781         i = 0
782         self._validating = True
783         while True:
784             initlen = len(nodes)
785
786             print "Type resolution; pass=%d" % (i, )
787             nodes = list(self._names.names.itervalues())
788             for node in nodes:
789                 try:
790                     self._resolve_node(node)
791                 except UnknownTypeError, e:
792                     print "WARNING: %s: Deleting %r" % (e, node)
793                     self._remove_attribute(node.name)
794             if len(nodes) == initlen:
795                 break
796             i += 1
797             self._print_statistics()
798         self._validating = False