2 # GObject-Introspection - a framework for introspecting GObject libraries
3 # Copyright (C) 2008 Johan Dahlin
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2 of the License, or (at your option) any later version.
10 # This library 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 GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the
17 # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 # Boston, MA 02111-1307, USA.
28 from .ast import (Alias, Bitfield, Callback, Constant, Enum, Function, Member,
29 Namespace, Parameter, Property, Record, Return, Type, Union,
30 Field, VFunction, type_name_from_ctype,
31 default_array_types, TYPE_UINT8, PARAM_TRANSFER_FULL)
32 from .transformer import Names
33 from .glibast import (GLibBoxed, GLibEnum, GLibEnumMember, GLibFlags,
34 GLibInterface, GLibObject, GLibSignal, GLibBoxedStruct,
35 GLibBoxedUnion, GLibBoxedOther, GLibRecord,
37 from .utils import to_underscores, to_underscores_noprefix
39 default_array_types['guchar*'] = TYPE_UINT8
42 G_PARAM_READABLE = 1 << 0
43 G_PARAM_WRITABLE = 1 << 1
44 G_PARAM_CONSTRUCT = 1 << 2
45 G_PARAM_CONSTRUCT_ONLY = 1 << 3
46 G_PARAM_LAX_VALIDATION = 1 << 4
47 G_PARAM_STATIC_NAME = 1 << 5
48 G_PARAM_STATIC_NICK = 1 << 6
49 G_PARAM_STATIC_BLURB = 1 << 7
52 # These ones break GError conventions
53 'g_simple_async_result_new_from_error',
54 'g_simple_async_result_set_from_error',
55 'g_simple_async_result_propagate_error',
56 'g_simple_async_result_report_error_in_idle',
57 'gtk_print_operation_get_error',
60 SYMBOL_BLACKLIST_RE = [re.compile(x) for x in \
61 [r'\w+_marshal_[A-Z]+__', ]]
64 class IntrospectionBinary(object):
66 def __init__(self, args, tmpdir=None):
69 self.tmpdir = tempfile.mkdtemp('', 'tmp-introspect')
74 class Unresolved(object):
76 def __init__(self, target):
80 class UnknownTypeError(Exception):
84 class GLibTransformer(object):
86 def __init__(self, transformer, noclosure=False):
87 self._transformer = transformer
88 self._noclosure = noclosure
89 self._namespace_name = None
91 self._uscore_type_names = {}
93 self._get_type_functions = []
94 self._error_quark_functions = []
96 self._failed_types = {}
97 self._boxed_types = {}
98 self._private_internal_types = {}
99 self._validating = False
103 def _print_statistics(self):
104 nodes = list(self._names.names.itervalues())
106 def count_type(otype):
107 return len([x for x in nodes
108 if isinstance(x[1], otype)])
109 objectcount = count_type(GLibObject)
110 ifacecount = count_type(GLibInterface)
111 enumcount = count_type(GLibEnum)
112 print " %d nodes; %d objects, %d interfaces, %d enums" \
113 % (len(nodes), objectcount, ifacecount, enumcount)
115 def init_parse(self):
116 """Do parsing steps that don't involve the introspection binary
118 This does enough work that get_type_functions() can be called.
122 namespace = self._transformer.parse()
123 self._namespace_name = namespace.name
124 self._namespace_version = namespace.version
126 # First pass: parsing
127 for node in namespace.nodes:
128 self._parse_node(node)
130 # We don't want an alias for this - it's handled specially in
131 # the typelib compiler.
132 if namespace.name == 'GObject':
133 del self._names.aliases['Type']
135 def get_get_type_functions(self):
136 return self._get_type_functions
138 def set_introspection_binary(self, binary):
139 self._binary = binary
142 """Do remaining parsing steps requiring introspection binary"""
144 # Get all the GObject data by passing our list of get_type
145 # functions to the compiled binary
147 self._execute_binary()
149 # Introspection is done from within parsing
151 # Second pass: pair boxed structures
152 for boxed in self._boxed_types.itervalues():
153 self._pair_boxed_type(boxed)
154 # Third pass: delete class structures, resolve
155 # all types we now know about
156 nodes = list(self._names.names.itervalues())
157 for (ns, node) in nodes:
159 self._resolve_node(node)
161 print "WARNING: DELETING node %s: %s" % (node.name, e)
162 self._remove_attribute(node.name)
163 # Another pass, since we need to have the methods parsed
164 # in order to correctly modify them after class/record
166 for (ns, node) in nodes:
167 # associate GtkButtonClass with GtkButton
168 if isinstance(node, Record):
169 self._pair_class_record(node)
170 for (ns, alias) in self._names.aliases.itervalues():
171 self._resolve_alias(alias)
172 self._resolve_quarks()
173 # Fourth pass: ensure all types are known
174 if not self._noclosure:
175 self._resolve_types(nodes)
177 self._validate(nodes)
179 # Create a new namespace with what we found
180 namespace = Namespace(self._namespace_name, self._namespace_version)
181 namespace.nodes = map(lambda x: x[1], self._names.aliases.itervalues())
182 for (ns, x) in self._names.names.itervalues():
183 namespace.nodes.append(x)
188 def _add_attribute(self, node, replace=False):
189 node_name = node.name
190 if (not replace) and node_name in self._names.names:
192 self._names.names[node_name] = (None, node)
194 def _remove_attribute(self, name):
195 del self._names.names[name]
197 def _get_attribute(self, name):
198 node = self._names.names.get(name)
203 def _lookup_node(self, name):
204 if name in type_names:
206 node = self._get_attribute(name)
208 node = self._transformer.get_names().names.get(name)
213 def _register_internal_type(self, type_name, node):
214 self._names.type_names[type_name] = (None, node)
215 uscored = to_underscores(type_name).lower()
216 self._uscore_type_names[uscored] = node
217 # Besides the straight underscore conversion, we also try
218 # removing the underscores from the namespace as a possible C
219 # mapping; e.g. it's webkit_web_view, not web_kit_web_view
220 suffix = self._transformer.remove_prefix(type_name)
221 prefix = type_name[:-len(suffix)]
222 no_uscore_prefixed = (prefix + '_' + to_underscores(suffix)).lower()
223 self._uscore_type_names[no_uscore_prefixed] = node
225 def _resolve_quarks(self):
226 for node in self._error_quark_functions:
227 short = node.symbol[:-len('_quark')]
228 enum = self._uscore_type_names.get(short)
230 enum.error_quark = node.symbol
234 def _resolve_gtypename(self, gtype_name):
236 return self._transformer.gtypename_to_giname(gtype_name,
239 return Unresolved(gtype_name)
241 def _execute_binary(self):
242 in_path = os.path.join(self._binary.tmpdir, 'types.txt')
243 f = open(in_path, 'w')
244 # TODO: Introspect GQuark functions
245 for func in self._get_type_functions:
249 out_path = os.path.join(self._binary.tmpdir, 'dump.xml')
252 args.extend(self._binary.args)
253 args.append('--introspect-dump=%s,%s' % (in_path, out_path))
255 # Invoke the binary, having written our get_type functions to types.txt
257 subprocess.check_call(args, stdout=sys.stdout, stderr=sys.stderr)
258 except subprocess.CalledProcessError, e:
260 self._read_introspect_dump(out_path)
262 # Clean up temporaries
263 shutil.rmtree(self._binary.tmpdir)
265 def _read_introspect_dump(self, xmlpath):
266 from xml.etree.cElementTree import parse
267 tree = parse(xmlpath)
268 root = tree.getroot()
270 self._gtype_data[child.attrib['name']] = child
272 self._introspect_type(child)
274 def _create_gobject(self, node):
275 type_name = 'G' + node.name
276 if type_name == 'GObject':
279 elif type_name == 'GInitiallyUnowned':
280 parent_type_name = 'GObject'
281 parent_gitype = self._resolve_gtypename(parent_type_name)
282 symbol = 'g_initially_unowned_get_type'
285 gnode = GLibObject(node.name, parent_gitype, type_name, symbol, True)
286 if type_name == 'GObject':
287 gnode.fields.extend(node.fields)
289 # http://bugzilla.gnome.org/show_bug.cgi?id=569408
290 # GInitiallyUnowned is actually a typedef for GObject, but
291 # that's not reflected in the GIR, where it appears as a
292 # subclass (as it appears in the GType hierarchy). So
293 # what we do here is copy all of the GObject fields into
294 # GInitiallyUnowned so that struct offset computation
296 gnode.fields = self._names.names['Object'][1].fields
297 self._add_attribute(gnode)
298 self._register_internal_type(type_name, gnode)
302 def _parse_node(self, node):
303 if isinstance(node, Enum):
304 self._parse_enum(node)
305 elif isinstance(node, Bitfield):
306 self._parse_bitfield(node)
307 elif isinstance(node, Function):
308 self._parse_function(node)
309 elif isinstance(node, Record):
310 self._parse_record(node)
311 elif isinstance(node, Callback):
312 self._parse_callback(node)
313 elif isinstance(node, Alias):
314 self._parse_alias(node)
315 elif isinstance(node, Member):
316 # FIXME: atk_misc_instance singletons
318 elif isinstance(node, Union):
319 self._parse_union(node)
320 elif isinstance(node, Constant):
321 self._parse_constant(node)
323 print 'GLIB Transformer: Unhandled node:', node
325 def _parse_alias(self, alias):
326 self._names.aliases[alias.name] = (None, alias)
328 def _parse_enum(self, enum):
329 self._add_attribute(enum)
331 def _parse_bitfield(self, enum):
332 self._add_attribute(enum)
334 def _parse_constant(self, constant):
335 self._add_attribute(constant)
337 def _parse_function(self, func):
338 if func.symbol in SYMBOL_BLACKLIST:
340 if func.symbol.startswith('_'):
342 for regexp in SYMBOL_BLACKLIST_RE:
343 if regexp.match(func.symbol):
345 if self._parse_get_type_function(func):
347 if self._parse_error_quark_function(func):
350 self._add_attribute(func)
352 def _parse_get_type_function(self, func):
354 if not symbol.endswith('_get_type'):
356 if self._namespace_name == 'GLib':
357 # No GObjects in GLib
359 if (self._namespace_name == 'GObject' and
360 symbol in ('g_object_get_type', 'g_initially_unowned_get_type')):
361 # We handle these internally, see _create_gobject
365 # GType *_get_type(void)
366 if func.retval.type.name not in ['Type',
370 print ("Warning: *_get_type function returns '%r'"
371 ", not GObject.Type") % (func.retval.type.name, )
374 self._get_type_functions.append(symbol)
377 def _parse_error_quark_function(self, func):
378 if not func.symbol.endswith('_error_quark'):
382 if func.retval.type.name not in ['GLib.Quark',
386 self._error_quark_functions.append(func)
389 def _name_is_internal_gtype(self, giname):
391 node = self._get_attribute(giname)
392 return isinstance(node, (GLibObject, GLibInterface,
393 GLibBoxed, GLibEnum, GLibFlags))
397 def _parse_static_method(self, func):
398 components = func.symbol.split('_')
399 if len(components) < 2:
402 prefix_components = None
404 for i in xrange(1, len(components)-1):
405 prefix_components = '_'.join(components[0:-i])
406 methname = '_'.join(components[-i:])
407 target_klass = self._uscore_type_names.get(prefix_components)
408 if target_klass and isinstance(target_klass, GLibObject):
413 self._remove_attribute(func.name)
415 target_klass.static_methods.append(func)
416 func.is_method = True
419 def _parse_method(self, func):
420 if not func.parameters:
422 return self._parse_method_common(func, True)
424 def _parse_constructor(self, func):
425 return self._parse_method_common(func, False)
427 def _parse_method_common(self, func, is_method):
428 # Skip _get_type functions, we processed them
430 if func.symbol.endswith('_get_type'):
432 if self._namespace_name == 'GLib':
433 # No GObjects in GLib
437 target_arg = func.retval
439 target_arg = func.parameters[0]
442 # Methods require their first arg to be a known class
443 # Look at the original C type (before namespace stripping), without
444 # pointers: GtkButton -> gtk_button_, so we can figure out the
446 argtype = target_arg.type.ctype.replace('*', '')
447 name = self._transformer.remove_prefix(argtype)
448 name_uscore = to_underscores_noprefix(name).lower()
449 name_offset = func.symbol.find(name_uscore)
452 prefix = func.symbol[:name_offset+len(name_uscore)]
454 # Constructors must have _new
455 # Take everything before that as class name
456 new_idx = func.symbol.find('_new')
459 # Constructors don't return basic types
460 derefed = self._transformer.follow_aliases(target_arg.type.name,
462 if derefed in type_names:
463 #print "NOTE: Rejecting constructor returning basic: %r" \
466 prefix = func.symbol[:new_idx]
468 klass = self._uscore_type_names.get(prefix)
470 #print "NOTE: No valid matching class for likely "+\
471 # "method or constructor: %r" % (func.symbol, )
473 # Enums can't have ctors or methods
474 if isinstance(klass, (GLibEnum, GLibFlags)):
477 # The _uscore_type_names member holds the plain GLibBoxed
478 # object; we want to actually use the struct/record associated
479 if isinstance(klass, (Record, Union)):
480 remove_prefix = klass.symbol
482 remove_prefix = klass.type_name
484 name = self._transformer.remove_prefix(remove_prefix)
485 klass = self._get_attribute(name)
490 # Interfaces can't have constructors, punt to global scope
491 if isinstance(klass, GLibInterface):
492 #print "NOTE: Rejecting constructor for"+\
493 # " interface type: %r" % (func.symbol, )
495 # TODO - check that the return type is a subclass of the
496 # class from the prefix
497 # But for now, ensure that constructor returns are always
498 # the most concrete class
499 name = self._transformer.remove_prefix(remove_prefix)
500 func.retval.type = Type(name, func.retval.type.ctype)
502 self._remove_attribute(func.name)
503 # Strip namespace and object prefix: gtk_window_new -> new
504 func.name = func.symbol[len(prefix)+1:]
506 # We don't need the "this" parameter
507 del func.parameters[0]
508 klass.methods.append(func)
509 func.is_method = True
511 klass.constructors.append(func)
514 def _parse_record(self, record):
515 # This is a hack, but GObject is a rather fundamental piece so.
516 internal_names = ["Object", 'InitiallyUnowned']
517 g_internal_names = ["G" + x for x in internal_names]
518 if (self._namespace_name == 'GObject' and
519 record.name in internal_names):
520 self._create_gobject(record)
522 elif record.name in g_internal_names:
525 node = self._names.names.get(record.name)
527 self._add_attribute(record, replace=True)
528 self._register_internal_type(record.symbol, record)
531 node.fields = record.fields[:]
533 def _parse_union(self, union):
534 node = self._names.names.get(union.name)
536 self._add_attribute(union, replace=True)
537 self._register_internal_type(union.symbol, union)
540 node.fields = union.fields[:]
542 def _parse_callback(self, callback):
543 self._add_attribute(callback)
545 def _strip_class_suffix(self, name):
546 if (name.endswith('Class') or
547 name.endswith('Iface')):
549 elif name.endswith('Interface'):
554 def _arg_is_failed(self, param):
555 ctype = self._transformer.ctype_of(param).replace('*', '')
556 uscored = to_underscores(self._strip_class_suffix(ctype)).lower()
557 if uscored in self._failed_types:
558 print "Warning: failed type: %r" % (param, )
562 def _pair_class_record(self, maybe_class):
563 name = self._strip_class_suffix(maybe_class.name)
564 if name == maybe_class.name:
567 class_struct = maybe_class
568 if self._arg_is_failed(class_struct):
569 print "WARNING: deleting no-type %r" % (class_struct.name, )
570 del self._names.names[class_struct.name]
573 pair_class = self._get_attribute(name)
574 if (not pair_class or
575 not isinstance(pair_class, (GLibObject, GLibInterface))):
578 # Object class fields are assumed to be read-only
579 # (see also _introspect_object and transformer.py)
580 for field in maybe_class.fields:
581 if isinstance(field, Field):
582 field.writable = False
584 # Loop through fields to determine which are virtual
585 # functions and which are signal slots by
586 # assuming everything that doesn't share a name
587 # with a known signal is a virtual slot.
588 for field in maybe_class.fields:
589 if not isinstance(field, Callback):
591 # Check the first parameter is the object
592 if len(field.parameters) == 0:
594 firstparam_type = field.parameters[0].type
595 if firstparam_type != pair_class:
597 # Also double check we don't have a signal with this
599 matched_signal = False
600 for signal in pair_class.signals:
601 if signal.name.replace('-', '_') == field.name:
602 matched_signal = True
606 vfunc = VFunction.from_callback(field)
607 pair_class.virtual_methods.append(vfunc)
609 # Take the set of virtual methods we found, and try
610 # to pair up with any matching methods using the
612 for vfunc in pair_class.virtual_methods:
613 for method in pair_class.methods:
614 if (method.name != vfunc.name or
615 method.retval != vfunc.retval or
616 method.parameters != vfunc.parameters):
618 vfunc.invoker = method.name
620 gclass_struct = GLibRecord.from_record(class_struct)
621 self._remove_attribute(class_struct.name)
622 self._add_attribute(gclass_struct, True)
623 pair_class.glib_type_struct = gclass_struct
624 gclass_struct.is_gtype_struct_for = name
628 def _introspect_type(self, xmlnode):
629 if xmlnode.tag in ('enum', 'flags'):
630 self._introspect_enum(xmlnode)
631 elif xmlnode.tag == 'class':
632 self._introspect_object(xmlnode)
633 elif xmlnode.tag == 'interface':
634 self._introspect_interface(xmlnode)
635 elif xmlnode.tag == 'boxed':
636 self._introspect_boxed(xmlnode)
638 raise ValueError("Unhandled introspection XML tag %s", xmlnode.tag)
640 def _introspect_enum(self, node):
642 for member in node.findall('member'):
643 # Keep the name closer to what we'd take from C by default;
644 # see http://bugzilla.gnome.org/show_bug.cgi?id=575613
645 name = member.attrib['nick'].replace('-', '_')
646 members.append(GLibEnumMember(name,
647 member.attrib['value'],
648 member.attrib['name'],
649 member.attrib['nick']))
651 klass = (GLibFlags if node.tag == 'flags' else GLibEnum)
652 type_name = node.attrib['name']
653 enum_name = self._transformer.remove_prefix(type_name)
654 node = klass(enum_name, type_name, members, node.attrib['get-type'])
655 self._add_attribute(node, replace=True)
656 self._register_internal_type(type_name, node)
658 def _introspect_object(self, xmlnode):
659 type_name = xmlnode.attrib['name']
660 # We handle this specially above; in 2.16 and below there
661 # was no g_object_get_type, for later versions we need
663 if type_name == 'GObject':
665 parent_type_name = xmlnode.attrib['parent']
666 parent_gitype = self._resolve_gtypename(parent_type_name)
667 is_abstract = not not xmlnode.attrib.get('abstract', False)
669 self._transformer.remove_prefix(type_name),
672 xmlnode.attrib['get-type'], is_abstract)
673 self._introspect_properties(node, xmlnode)
674 self._introspect_signals(node, xmlnode)
675 self._introspect_implemented_interfaces(node, xmlnode)
678 record = self._get_attribute(node.name)
679 if record is not None:
680 node.fields = record.fields
681 for field in node.fields:
682 if isinstance(field, Field):
683 # Object instance fields are assumed to be read-only
684 # (see also _pair_class_record and transformer.py)
685 field.writable = False
687 self._add_attribute(node, replace=True)
688 self._register_internal_type(type_name, node)
690 def _introspect_interface(self, xmlnode):
691 type_name = xmlnode.attrib['name']
692 node = GLibInterface(
693 self._transformer.remove_prefix(type_name),
695 type_name, xmlnode.attrib['get-type'])
696 self._introspect_properties(node, xmlnode)
697 self._introspect_signals(node, xmlnode)
698 for child in xmlnode.findall('prerequisite'):
699 name = child.attrib['name']
700 prereq = self._resolve_gtypename(name)
701 node.prerequisites.append(prereq)
702 # GtkFileChooserEmbed is an example of a private interface, we
703 # just filter them out
704 if xmlnode.attrib['get-type'].startswith('_'):
705 print "NOTICE: Marking %s as internal type" % (type_name, )
706 self._private_internal_types[type_name] = node
708 self._add_attribute(node, replace=True)
709 self._register_internal_type(type_name, node)
711 def _introspect_boxed(self, xmlnode):
712 type_name = xmlnode.attrib['name']
713 # This one doesn't go in the main namespace; we associate it with
714 # the struct or union
715 node = GLibBoxed(type_name, xmlnode.attrib['get-type'])
716 self._boxed_types[node.type_name] = node
717 self._register_internal_type(type_name, node)
719 def _introspect_implemented_interfaces(self, node, xmlnode):
721 for interface in xmlnode.findall('implements'):
722 gitype = self._resolve_gtypename(interface.attrib['name'])
723 gt_interfaces.append(gitype)
724 node.interfaces = gt_interfaces
726 def _introspect_properties(self, node, xmlnode):
727 for pspec in xmlnode.findall('property'):
728 ctype = pspec.attrib['type']
729 flags = int(pspec.attrib['flags'])
730 readable = (flags & G_PARAM_READABLE) != 0
731 writable = (flags & G_PARAM_WRITABLE) != 0
732 construct = (flags & G_PARAM_CONSTRUCT) != 0
733 construct_only = (flags & G_PARAM_CONSTRUCT_ONLY) != 0
734 node.properties.append(Property(
735 pspec.attrib['name'],
736 type_name_from_ctype(ctype),
737 readable, writable, construct, construct_only,
741 def _introspect_signals(self, node, xmlnode):
742 for signal_info in xmlnode.findall('signal'):
743 rctype = signal_info.attrib['return']
744 rtype = Type(self._transformer.parse_ctype(rctype), rctype)
745 return_ = Return(rtype, signal_info.attrib['return'])
746 return_.transfer = PARAM_TRANSFER_FULL
747 signal = GLibSignal(signal_info.attrib['name'], return_)
748 for i, parameter in enumerate(signal_info.findall('param')):
752 name = 'p%s' % (i-1, )
753 pctype = parameter.attrib['type']
754 ptype = Type(self._transformer.parse_ctype(pctype), pctype)
755 param = Parameter(name, ptype)
756 param.transfer = 'none'
757 signal.parameters.append(param)
758 node.signals.append(signal)
762 def _resolve_type_name(self, type_name, ctype=None):
763 # Workaround glib bug #548689, to be included in 2.18.0
764 if type_name == "GParam":
765 type_name = "GObject.ParamSpec"
766 res = self._transformer.resolve_type_name_full
768 return res(type_name, ctype, self._names)
770 return self._transformer.resolve_type_name(type_name, ctype)
772 def _resolve_param_type(self, ptype, **kwargs):
773 # Workaround glib bug #548689, to be included in 2.18.0
774 if ptype.name == "GParam":
775 ptype.name = "GObject.ParamSpec"
776 return self._transformer.resolve_param_type_full(ptype,
780 def _resolve_node(self, node):
781 if isinstance(node, Function):
782 self._resolve_function_toplevel(node)
784 elif isinstance(node, Callback):
785 self._resolve_function(node)
786 elif isinstance(node, GLibObject):
787 self._resolve_glib_object(node)
788 elif isinstance(node, GLibInterface):
789 self._resolve_glib_interface(node)
790 elif isinstance(node, Record):
791 self._resolve_record(node)
792 elif isinstance(node, Union):
793 self._resolve_union(node)
794 elif isinstance(node, Alias):
795 self._resolve_alias(node)
797 def _resolve_function_toplevel(self, func):
798 for parser in [self._parse_constructor,
800 self._parse_static_method]:
801 newfunc = parser(func)
803 self._resolve_function(newfunc)
805 self._resolve_function(func)
807 def _pair_boxed_type(self, boxed):
808 name = self._transformer.remove_prefix(boxed.type_name)
809 pair_node = self._get_attribute(name)
811 boxed_item = GLibBoxedOther(name, boxed.type_name,
813 elif isinstance(pair_node, Record):
814 boxed_item = GLibBoxedStruct(pair_node.name, boxed.type_name,
816 boxed_item.fields = pair_node.fields
817 elif isinstance(pair_node, Union):
818 boxed_item = GLibBoxedUnion(pair_node.name, boxed.type_name,
820 boxed_item.fields = pair_node.fields
823 self._add_attribute(boxed_item, replace=True)
825 def _resolve_record(self, node):
826 for field in node.fields:
827 self._resolve_field(field)
829 def _resolve_union(self, node):
830 for field in node.fields:
831 self._resolve_field(field)
833 def _force_resolve(self, item, allow_unknown=False):
834 if isinstance(item, Unresolved):
835 if item.target in self._private_internal_types:
838 return self._transformer.gtypename_to_giname(item.target,
842 print "WARNING: Skipping unknown interface %s" % \
847 if item in self._private_internal_types:
851 def _resolve_glib_interface(self, node):
852 node.parent = self._force_resolve(node.parent)
853 self._resolve_methods(node.methods)
854 self._resolve_properties(node.properties, node)
855 self._resolve_signals(node.signals)
856 node.prerequisites = filter(None,
857 [self._force_resolve(x, allow_unknown=True)
858 for x in node.prerequisites])
860 def _resolve_glib_object(self, node):
861 # If we can't find the parent class, just drop back to GObject.
862 # This supports hidden parent classes.
863 # http://bugzilla.gnome.org/show_bug.cgi?id=561360
865 node.parent = self._force_resolve(node.parent)
867 #print ("WARNING: Parent %r of class %r" +\
868 # " not found; using GObject") % (node.parent.target,
870 node.parent = self._transformer.gtypename_to_giname("GObject",
872 node.interfaces = filter(None,
873 [self._force_resolve(x, allow_unknown=True)
874 for x in node.interfaces])
875 self._resolve_constructors(node.constructors)
876 self._resolve_methods(node.methods)
877 self._resolve_methods(node.static_methods)
878 self._resolve_properties(node.properties, node)
879 self._resolve_signals(node.signals)
880 for field in node.fields:
881 self._resolve_field(field)
883 def _resolve_glib_boxed(self, node):
884 self._resolve_constructors(node.constructors)
885 self._resolve_methods(node.methods)
887 def _resolve_constructors(self, constructors):
888 for ctor in constructors:
889 self._resolve_function(ctor)
891 def _resolve_methods(self, methods):
892 for method in methods:
893 self._resolve_function(method)
895 def _resolve_signals(self, signals):
896 for signal in signals:
897 self._resolve_function(signal)
899 def _resolve_properties(self, properties, context):
901 for prop in properties:
903 self._resolve_property(prop)
907 #print ("WARNING: Deleting object property %r (of %r) "
908 # "with unknown type") % (fail, context)
909 properties.remove(fail)
911 def _resolve_property(self, prop):
912 prop.type = self._resolve_param_type(prop.type, allow_invalid=False)
914 def _adjust_throws(self, func):
915 if func.parameters == []:
918 last_param = func.parameters.pop()
920 if (last_param.type.name == 'GLib.Error' or
921 (self._namespace_name == 'GLib' and
922 last_param.type.name == 'Error')):
925 func.parameters.append(last_param)
927 def _resolve_function(self, func):
928 self._resolve_parameters(func.parameters)
929 func.retval.type = self._resolve_param_type(func.retval.type)
930 self._adjust_throws(func)
932 def _resolve_parameters(self, parameters):
933 for parameter in parameters:
934 parameter.type = self._resolve_param_type(parameter.type)
936 def _resolve_field(self, field):
937 if isinstance(field, Callback):
938 self._resolve_function(field)
939 elif isinstance(field, Record): # non-typedef'd struct
940 self._resolve_record(field)
941 elif isinstance(field, Union): # non-typedef'd union
942 self._resolve_union(field)
944 field.type = self._resolve_param_type(field.type)
946 def _resolve_alias(self, alias):
947 alias.target = self._resolve_type_name(alias.target, alias.target)
949 def _resolve_types(self, nodes):
950 nodes = list(self._names.names.itervalues())
952 self._validating = True
956 #print "Type resolution; pass=%d" % (i, )
957 nodes = list(self._names.names.itervalues())
960 self._resolve_node(node)
961 except UnknownTypeError, e:
962 print "WARNING: %s: Deleting %r" % (e, node)
963 self._remove_attribute(node.name)
964 if len(nodes) == initlen:
967 self._print_statistics()
968 self._validating = False
972 def _validate_interface(self, iface):
973 for vfunc in iface.virtual_methods:
974 if not vfunc.invoker:
975 print ("warning: Interface %r virtual function %r " + \
976 "has no known invoker") % (iface.name, vfunc.name)
978 # This function is called at the very end, before we hand back the
979 # completed namespace to the writer. Add static analysis checks here.
980 def _validate(self, nodes):
981 for (name, node) in nodes:
982 if isinstance(node, GLibInterface):
983 self._validate_interface(node)