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.
26 from .cachestore import CacheStore
27 from .girparser import GIRParser
28 from .sourcescanner import (
29 SourceSymbol, ctype_name, CTYPE_POINTER,
30 CTYPE_BASIC_TYPE, CTYPE_UNION, CTYPE_ARRAY, CTYPE_TYPEDEF,
31 CTYPE_VOID, CTYPE_ENUM, CTYPE_FUNCTION, CTYPE_STRUCT,
32 CSYMBOL_TYPE_FUNCTION, CSYMBOL_TYPE_TYPEDEF, CSYMBOL_TYPE_STRUCT,
33 CSYMBOL_TYPE_ENUM, CSYMBOL_TYPE_UNION, CSYMBOL_TYPE_OBJECT,
34 CSYMBOL_TYPE_MEMBER, CSYMBOL_TYPE_ELLIPSIS, CSYMBOL_TYPE_CONST,
37 class TransformerException(Exception):
41 _xdg_data_dirs = [x for x in os.environ.get('XDG_DATA_DIRS', '').split(os.pathsep)]
42 _xdg_data_dirs.append(DATADIR)
45 _xdg_data_dirs.append('/usr/share')
48 class Transformer(object):
49 namespace = property(lambda self: self._namespace)
51 def __init__(self, namespace, accept_unprefixed=False):
52 self._cachestore = CacheStore()
53 self._accept_unprefixed = accept_unprefixed
54 self._namespace = namespace
55 self._pkg_config_packages = set()
56 self._typedefs_ns = {}
57 self._includes = {} # <string namespace -> Namespace>
58 self._include_names = set() # string namespace
59 self._includepaths = []
60 self._passthrough_mode = False
61 self._annotations = {}
63 def get_includes(self):
64 return self._include_names
66 def get_pkgconfig_packages(self):
67 return self._pkg_config_packages
69 def disable_cache(self):
70 self._cachestore = None
72 def set_passthrough_mode(self):
73 self._passthrough_mode = True
75 def set_annotations(self, annotations):
76 self._annotations = annotations
78 def _append_new_node(self, node):
79 original = self._namespace.get(node.name)
80 # Special case constants here; we allow duplication to sort-of
81 # handle #ifdef. But this introduces an arch-dependency in the .gir
82 # file. So far this has only come up scanning glib - in theory, other
83 # modules will just depend on that.
84 if isinstance(original, ast.Constant) and isinstance(node, ast.Constant):
88 positions.update(original.file_positions)
89 positions.update(node.file_positions)
90 message.fatal("Namespace conflict for '%s'" % (node.name, ),
93 self._namespace.append(node)
95 def parse(self, symbols):
96 for symbol in symbols:
98 # https://bugzilla.gnome.org/show_bug.cgi?id=550616
99 if symbol.ident in ['gst_g_error_get_type']:
101 node = self._traverse_one(symbol)
103 self._append_new_node(node)
105 # Now look through the namespace for things like
106 # typedef struct _Foo Foo;
107 # where we've never seen the struct _Foo. Just create
108 # an empty structure for these as "disguised"
109 # If we do have a class/interface, merge fields
110 for typedef, compound in self._typedefs_ns.iteritems():
111 ns_compound = self._namespace.get(compound.name)
113 ns_compound = self._namespace.get('_' + compound.name)
114 if (not ns_compound and isinstance(compound, (ast.Record, ast.Union))
115 and len(compound.fields) == 0):
116 disguised = ast.Record(compound.name, typedef, disguised=True)
117 self._namespace.append(disguised)
118 elif not ns_compound:
119 self._namespace.append(compound)
120 elif isinstance(ns_compound, (ast.Record, ast.Union)) and len(ns_compound.fields) == 0:
121 ns_compound.fields = compound.fields
122 self._typedefs_ns = None
124 def set_include_paths(self, paths):
125 self._includepaths = list(paths)
127 def register_include(self, include):
128 if include in self._include_names:
130 filename = self._find_include(include)
131 self._parse_include(filename)
132 self._include_names.add(include)
134 def register_include_uninstalled(self, include_path):
135 basename = os.path.basename(include_path)
136 if not basename.endswith('.gir'):
138 "Include path %r must be a filename path ending in .gir" % (include_path, ))
139 girname = basename[:-4]
140 include = ast.Include.from_string(girname)
141 if include in self._include_names:
143 self._parse_include(include_path, uninstalled=True)
144 self._include_names.add(include)
146 def lookup_giname(self, name):
147 """Given a name of the form Foo or Bar.Foo,
148 return the corresponding ast.Node, or None if none
149 available. Will throw KeyError however for unknown
152 return self._namespace.get(name)
154 (ns, name) = name.split('.', 1)
155 if ns == self._namespace.name:
156 return self._namespace.get(name)
157 include = self._includes[ns]
158 return include.get(name)
160 def lookup_typenode(self, typeobj):
161 """Given a Type object, if it points to a giname,
162 calls lookup_giname() on the name. Otherwise return
164 if typeobj.target_giname:
165 return self.lookup_giname(typeobj.target_giname)
170 def _find_include(self, include):
171 searchdirs = self._includepaths[:]
172 for path in _xdg_data_dirs:
173 searchdirs.append(os.path.join(path, 'gir-1.0'))
174 searchdirs.append(os.path.join(DATADIR, 'gir-1.0'))
176 girname = '%s-%s.gir' % (include.name, include.version)
178 path = os.path.join(d, girname)
179 if os.path.exists(path):
181 sys.stderr.write("Couldn't find include %r (search path: %r)\n"\
182 % (girname, searchdirs))
186 def parse_from_gir(cls, filename, extra_include_dirs=None):
188 if extra_include_dirs is not None:
189 self.set_include_paths(extra_include_dirs)
190 self.set_passthrough_mode()
191 self._parse_include(filename)
192 parser = self._cachestore.load(filename)
193 self._namespace = parser.get_namespace()
194 del self._includes[self._namespace.name]
197 def _parse_include(self, filename, uninstalled=False):
199 if self._cachestore is not None:
200 parser = self._cachestore.load(filename)
202 parser = GIRParser(types_only=not self._passthrough_mode)
203 parser.parse(filename)
204 if self._cachestore is not None:
205 self._cachestore.store(filename, parser)
207 for include in parser.get_includes():
208 self.register_include(include)
211 for pkg in parser.get_pkgconfig_packages():
212 self._pkg_config_packages.add(pkg)
213 namespace = parser.get_namespace()
214 self._includes[namespace.name] = namespace
216 def _iter_namespaces(self):
217 """Return an iterator over all included namespaces; the
218 currently-scanned namespace is first."""
219 yield self._namespace
220 for ns in self._includes.itervalues():
223 def _sort_matches(self, x, y):
224 if x[0] is self._namespace:
226 elif y[0] is self._namespace:
228 return cmp(x[2], y[2])
230 def _split_c_string_for_namespace_matches(self, name, is_identifier=False):
231 matches = [] # Namespaces which might contain this name
232 unprefixed_namespaces = [] # Namespaces with no prefix, last resort
233 for ns in self._iter_namespaces():
235 prefixes = ns.identifier_prefixes
236 elif name[0].isupper():
237 prefixes = ns._ucase_symbol_prefixes
239 prefixes = ns.symbol_prefixes
241 for prefix in prefixes:
242 if (not is_identifier) and (not prefix.endswith('_')):
243 prefix = prefix + '_'
244 if name.startswith(prefix):
245 matches.append((ns, name[len(prefix):], len(prefix)))
248 unprefixed_namespaces.append(ns)
250 matches.sort(self._sort_matches)
251 return map(lambda x: (x[0], x[1]), matches)
252 elif self._accept_unprefixed:
253 return [(self._namespace, name)]
254 elif unprefixed_namespaces:
255 # A bit of a hack; this function ideally shouldn't look through the
256 # contents of namespaces; but since we aren't scanning anything
257 # without a prefix, it's not too bad.
258 for ns in unprefixed_namespaces:
261 raise ValueError("Unknown namespace for %s %r"
262 % ('identifier' if is_identifier else 'symbol', name, ))
264 def split_ctype_namespaces(self, ident):
265 """Given a StudlyCaps string identifier like FooBar, return a
266 list of (namespace, stripped_identifier) sorted by namespace length,
267 or raise ValueError. As a special case, if the current namespace matches,
268 it is always biggest (i.e. last)."""
269 return self._split_c_string_for_namespace_matches(ident, is_identifier=True)
271 def split_csymbol_namespaces(self, symbol):
272 """Given a C symbol like foo_bar_do_baz, return a list of
273 (namespace, stripped_symbol) sorted by namespace match probablity, or
275 return self._split_c_string_for_namespace_matches(symbol, is_identifier=False)
277 def split_csymbol(self, symbol):
278 """Given a C symbol like foo_bar_do_baz, return the most probable
279 (namespace, stripped_symbol) match, or raise ValueError."""
280 matches = self._split_c_string_for_namespace_matches(symbol, is_identifier=False)
283 def strip_identifier(self, ident):
284 hidden = ident.startswith('_')
288 matches = self.split_ctype_namespaces(ident)
289 except ValueError, e:
290 raise TransformerException(str(e))
291 for ns, name in matches:
292 if ns is self._namespace:
296 (ns, name) = matches[-1]
297 raise TransformerException(
298 "Skipping foreign identifier %r from namespace %s" % (
302 def _strip_symbol(self, symbol):
304 hidden = ident.startswith('_')
308 (ns, name) = self.split_csymbol(ident)
309 except ValueError, e:
310 raise TransformerException(str(e))
311 if ns != self._namespace:
312 raise TransformerException(
313 "Skipping foreign symbol from namespace %s" % (ns.name, ))
318 def _traverse_one(self, symbol, stype=None, parent_symbol=None):
319 assert isinstance(symbol, SourceSymbol), symbol
323 if stype == CSYMBOL_TYPE_FUNCTION:
324 return self._create_function(symbol)
325 elif stype == CSYMBOL_TYPE_TYPEDEF:
326 return self._create_typedef(symbol)
327 elif stype == CSYMBOL_TYPE_STRUCT:
328 return self._create_struct(symbol)
329 elif stype == CSYMBOL_TYPE_ENUM:
330 return self._create_enum(symbol)
331 elif stype == CSYMBOL_TYPE_MEMBER:
332 return self._create_member(symbol, parent_symbol)
333 elif stype == CSYMBOL_TYPE_UNION:
334 return self._create_union(symbol)
335 elif stype == CSYMBOL_TYPE_CONST:
336 # Don't parse constants which are marked (skip)
337 docblock = self._annotations.get(symbol.ident)
338 if not docblock or not 'skip' in docblock.options:
339 return self._create_const(symbol)
340 # Ignore variable declarations in the header
341 elif stype == CSYMBOL_TYPE_OBJECT:
344 print 'transformer: unhandled symbol: %r' % (symbol, )
346 def _enum_common_prefix(self, symbol):
347 def common_prefix(a, b):
349 for aword, bword in zip(a.split('_'), b.split('_')):
351 return '_'.join(commonparts) + '_'
352 commonparts.append(aword)
355 # Nothing less than 2 has a common prefix
356 if len(list(symbol.base_type.child_list)) < 2:
359 for child in symbol.base_type.child_list:
363 prefix = common_prefix(prefix, child.ident)
368 def _create_enum(self, symbol):
369 prefix = self._enum_common_prefix(symbol)
371 prefixlen = len(prefix)
375 for child in symbol.base_type.child_list:
379 name = child.ident[prefixlen:]
381 # Ok, the enum members don't have a consistent prefix
382 # among them, so let's just remove the global namespace
385 name = self._strip_symbol(child)
386 except TransformerException, e:
387 message.warn_symbol(symbol, e)
389 members.append(ast.Member(name.lower(),
395 enum_name = self.strip_identifier(symbol.ident)
396 except TransformerException, e:
397 message.warn_symbol(symbol, e)
399 if symbol.base_type.is_bitfield:
403 node = klass(enum_name, symbol.ident, members=members)
404 node.add_symbol_reference(symbol)
407 def _create_function(self, symbol):
408 # Drop functions that start with _ very early on here
409 if symbol.ident.startswith('_'):
411 parameters = list(self._create_parameters(symbol.base_type))
412 return_ = self._create_return(symbol.base_type.base_type)
414 name = self._strip_symbol(symbol)
415 except TransformerException, e:
416 message.warn_symbol(symbol, e)
418 func = ast.Function(name, return_, parameters, False, symbol.ident)
419 func.add_symbol_reference(symbol)
422 def _create_source_type(self, source_type):
423 if source_type is None:
425 if source_type.type == CTYPE_VOID:
427 elif source_type.type == CTYPE_BASIC_TYPE:
428 value = source_type.name
429 elif source_type.type == CTYPE_TYPEDEF:
430 value = source_type.name
431 elif source_type.type == CTYPE_ARRAY:
432 return self._create_source_type(source_type.base_type)
433 elif source_type.type == CTYPE_POINTER:
434 value = self._create_source_type(source_type.base_type) + '*'
439 def _create_parameters(self, base_type):
440 # warn if we see annotations for unknown parameters
441 param_names = set(child.ident for child in base_type.child_list)
442 for child in base_type.child_list:
443 yield self._create_parameter(child)
445 def _synthesize_union_type(self, symbol, parent_symbol):
446 # Synthesize a named union so that it can be referenced.
447 parent_ident = parent_symbol.ident
448 # FIXME: Should split_ctype_namespaces handle the hidden case?
449 hidden = parent_ident.startswith('_')
451 parent_ident = parent_ident[1:]
452 matches = self.split_ctype_namespaces(parent_ident)
453 (namespace, parent_name) = matches[-1]
454 assert namespace and parent_name
456 parent_name = '_' + parent_name
457 fake_union = ast.Union("%s__%s__union" % (parent_name, symbol.ident))
458 # _parse_fields accesses <type>.base_type.child_list, so we have to
459 # pass symbol.base_type even though that refers to the array, not the
461 self._parse_fields(symbol.base_type, fake_union)
462 self._append_new_node(fake_union)
463 fake_type = ast.Type(
464 target_giname="%s.%s" % (namespace.name, fake_union.name))
467 def _create_member(self, symbol, parent_symbol=None):
468 source_type = symbol.base_type
469 if (source_type.type == CTYPE_POINTER and
470 symbol.base_type.base_type.type == CTYPE_FUNCTION):
471 node = self._create_callback(symbol, member=True)
472 elif source_type.type == CTYPE_STRUCT and source_type.name is None:
473 node = self._create_struct(symbol, anonymous=True)
474 elif source_type.type == CTYPE_UNION and source_type.name is None:
475 node = self._create_union(symbol, anonymous=True)
477 # Special handling for fields; we don't have annotations on them
478 # to apply later, yet.
479 if source_type.type == CTYPE_ARRAY:
480 # If the array contains anonymous unions, like in the GValue
481 # struct, we need to handle this specially. This is necessary
482 # to be able to properly calculate the size of the compound
483 # type (e.g. GValue) that contains this array, see
484 # <https://bugzilla.gnome.org/show_bug.cgi?id=657040>.
485 if (source_type.base_type.type == CTYPE_UNION and
486 source_type.base_type.name is None):
487 synthesized_type = self._synthesize_union_type(symbol, parent_symbol)
488 ftype = ast.Array(None, synthesized_type)
490 ctype = self._create_source_type(source_type)
491 canonical_ctype = self._canonicalize_ctype(ctype)
492 if canonical_ctype[-1] == '*':
493 derefed_name = canonical_ctype[:-1]
495 derefed_name = canonical_ctype
496 ftype = ast.Array(None, self.create_type_from_ctype_string(ctype),
498 child_list = list(symbol.base_type.child_list)
499 ftype.zeroterminated = False
501 ftype.size = child_list[0].const_int
503 ftype = self._create_type_from_base(symbol.base_type)
504 # ast.Fields are assumed to be read-write
505 # (except for Objects, see also glibtransformer.py)
506 node = ast.Field(symbol.ident, ftype,
507 readable=True, writable=True,
508 bits=symbol.const_int)
510 node.readable = False
511 node.writable = False
515 def _create_typedef(self, symbol):
516 ctype = symbol.base_type.type
517 if (ctype == CTYPE_POINTER and
518 symbol.base_type.base_type.type == CTYPE_FUNCTION):
519 node = self._create_typedef_callback(symbol)
520 elif (ctype == CTYPE_POINTER and
521 symbol.base_type.base_type.type == CTYPE_STRUCT):
522 node = self._create_typedef_struct(symbol, disguised=True)
523 elif ctype == CTYPE_STRUCT:
524 node = self._create_typedef_struct(symbol)
525 elif ctype == CTYPE_UNION:
526 node = self._create_typedef_union(symbol)
527 elif ctype == CTYPE_ENUM:
528 return self._create_enum(symbol)
529 elif ctype in (CTYPE_TYPEDEF,
534 name = self.strip_identifier(symbol.ident)
535 except TransformerException, e:
538 if symbol.base_type.name:
539 target = self.create_type_from_ctype_string(symbol.base_type.name)
541 target = ast.TYPE_ANY
542 if name in ast.type_names:
544 return ast.Alias(name, target, ctype=symbol.ident)
546 raise NotImplementedError(
547 "symbol %r of type %s" % (symbol.ident, ctype_name(ctype)))
550 def _canonicalize_ctype(self, ctype):
551 # First look up the ctype including any pointers;
552 # a few type names like 'char*' have their own aliases
553 # and we need pointer information for those.
554 firstpass = ast.type_names.get(ctype)
556 # If we have a particular alias for this, skip deep
557 # canonicalization to prevent changing
558 # e.g. char* -> int8*
560 return firstpass.target_fundamental
562 if not ctype.endswith('*'):
565 # We have a pointer type.
566 # Strip the end pointer, canonicalize our base type
568 canonical_base = self._canonicalize_ctype(base)
570 # Append the pointer again
571 canonical = canonical_base + '*'
575 def parse_ctype(self, ctype, is_member=False):
576 canonical = self._canonicalize_ctype(ctype)
578 # Remove all pointers - we require standard calling
579 # conventions. For example, an 'int' is always passed by
580 # value (unless it's out or inout).
581 derefed_typename = canonical.replace('*', '')
583 # Preserve "pointerness" of struct/union members
584 if (is_member and canonical.endswith('*') and
585 derefed_typename in ast.basic_type_names):
588 return derefed_typename
590 def _create_type_from_base(self, source_type, is_parameter=False, is_return=False):
591 ctype = self._create_source_type(source_type)
592 const = ((source_type.type == CTYPE_POINTER) and
593 (source_type.base_type.type_qualifier & TYPE_QUALIFIER_CONST))
594 return self.create_type_from_ctype_string(ctype, is_const=const,
595 is_parameter=is_parameter, is_return=is_return)
597 def _create_bare_container_type(self, base, ctype=None,
599 if base in ('GList', 'GSList', 'GLib.List', 'GLib.SList'):
600 if base in ('GList', 'GSList'):
601 name = 'GLib.' + base[1:]
604 return ast.List(name, ast.TYPE_ANY, ctype=ctype,
606 elif base in ('GArray', 'GPtrArray', 'GByteArray',
607 'GLib.Array', 'GLib.PtrArray', 'GLib.ByteArray',
608 'GObject.Array', 'GObject.PtrArray', 'GObject.ByteArray'):
610 name = 'GLib.' + base.split('.', 1)[1]
612 name = 'GLib.' + base[1:]
613 return ast.Array(name, ast.TYPE_ANY, ctype=ctype,
615 elif base in ('GHashTable', 'GLib.HashTable', 'GObject.HashTable'):
616 return ast.Map(ast.TYPE_ANY, ast.TYPE_ANY, ctype=ctype, is_const=is_const)
619 def create_type_from_ctype_string(self, ctype, is_const=False,
620 is_parameter=False, is_return=False):
621 canonical = self._canonicalize_ctype(ctype)
622 base = canonical.replace('*', '')
624 # Special default: char ** -> ast.Array, same for GStrv
625 if (is_return and canonical == 'utf8*') or base == 'GStrv':
626 bare_utf8 = ast.TYPE_STRING.clone()
627 bare_utf8.ctype = None
628 return ast.Array(None, bare_utf8, ctype=ctype,
631 fundamental = ast.type_names.get(base)
632 if fundamental is not None:
633 return ast.Type(target_fundamental=fundamental.target_fundamental,
636 container = self._create_bare_container_type(base, ctype=ctype, is_const=is_const)
639 return ast.Type(ctype=ctype, is_const=is_const)
641 def _create_parameter(self, symbol):
642 if symbol.type == CSYMBOL_TYPE_ELLIPSIS:
643 ptype = ast.Varargs()
645 ptype = self._create_type_from_base(symbol.base_type, is_parameter=True)
646 return ast.Parameter(symbol.ident, ptype)
648 def _create_return(self, source_type):
649 typeval = self._create_type_from_base(source_type, is_return=True)
650 return ast.Return(typeval)
652 def _create_const(self, symbol):
653 # Don't create constants for non-public things
654 # http://bugzilla.gnome.org/show_bug.cgi?id=572790
655 if (symbol.source_filename is None or
656 not symbol.source_filename.endswith('.h')):
659 name = self._strip_symbol(symbol)
660 except TransformerException, e:
661 message.warn_symbol(symbol, e)
663 if symbol.const_string is not None:
664 typeval = ast.TYPE_STRING
665 value = unicode(symbol.const_string, 'utf-8')
666 elif symbol.const_int is not None:
667 typeval = ast.TYPE_INT
668 value = '%d' % (symbol.const_int, )
669 elif symbol.const_double is not None:
670 typeval = ast.TYPE_DOUBLE
671 value = '%f' % (symbol.const_double, )
673 raise AssertionError()
675 const = ast.Constant(name, typeval, value,
677 const.add_symbol_reference(symbol)
680 def _create_typedef_struct(self, symbol, disguised=False):
682 name = self.strip_identifier(symbol.ident)
683 except TransformerException, e:
684 message.warn_symbol(symbol, e)
686 struct = ast.Record(name, symbol.ident, disguised=disguised)
687 self._parse_fields(symbol, struct)
688 struct.add_symbol_reference(symbol)
689 self._typedefs_ns[symbol.ident] = struct
692 def _create_typedef_union(self, symbol):
694 name = self.strip_identifier(symbol.ident)
695 except TransformerException, e:
698 union = ast.Union(name, symbol.ident)
699 self._parse_fields(symbol, union)
700 union.add_symbol_reference(symbol)
701 self._typedefs_ns[symbol.ident] = union
704 def _create_typedef_callback(self, symbol):
705 callback = self._create_callback(symbol)
708 self._typedefs_ns[callback.name] = callback
711 def _parse_fields(self, symbol, compound):
712 for child in symbol.base_type.child_list:
713 child_node = self._traverse_one(child, parent_symbol=symbol)
716 if isinstance(child_node, ast.Field):
719 field = ast.Field(child.ident, None, True, False,
720 anonymous_node=child_node)
721 compound.fields.append(field)
723 def _create_compound(self, klass, symbol, anonymous):
724 if symbol.ident is None:
725 # the compound is an anonymous member of another union or a struct
727 compound = klass(None, None)
729 compound = self._typedefs_ns.get(symbol.ident, None)
732 # This is a bit of a hack; really we should try
733 # to resolve through the typedefs to find the real
735 if symbol.ident.startswith('_'):
736 compound = self._typedefs_ns.get(symbol.ident[1:], None)
742 name = self.strip_identifier(symbol.ident)
743 except TransformerException, e:
746 compound = klass(name, symbol.ident)
748 self._parse_fields(symbol, compound)
749 compound.add_symbol_reference(symbol)
752 def _create_struct(self, symbol, anonymous=False):
753 return self._create_compound(ast.Record, symbol, anonymous)
755 def _create_union(self, symbol, anonymous=False):
756 return self._create_compound(ast.Union, symbol, anonymous)
758 def _create_callback(self, symbol, member=False):
759 parameters = list(self._create_parameters(symbol.base_type.base_type))
760 retval = self._create_return(symbol.base_type.base_type.base_type)
762 # Mark the 'user_data' arguments
763 for i, param in enumerate(parameters):
764 if (param.type.target_fundamental == 'gpointer' and
765 param.argname == 'user_data'):
766 param.closure_name = param.argname
770 elif symbol.ident.find('_') > 0:
772 name = self._strip_symbol(symbol)
773 except TransformerException, e:
774 message.warn_symbol(symbol, e)
778 name = self.strip_identifier(symbol.ident)
779 except TransformerException, e:
782 callback = ast.Callback(name, retval, parameters, False,
784 callback.add_symbol_reference(symbol)
788 def create_type_from_user_string(self, typestr):
789 """Parse a C type string (as might be given from an
790 annotation) and resolve it. For compatibility, we can consume
791 both GI type string (utf8, Foo.Bar) style, as well as C (char *, FooBar) style.
793 Note that type resolution may not succeed."""
795 container = self._create_bare_container_type(typestr)
798 return self._namespace.type_from_name(typestr)
799 typeval = self.create_type_from_ctype_string(typestr)
800 self.resolve_type(typeval)
802 # Explicitly clear out the c_type; there isn't one in this case.
806 def _resolve_type_from_ctype_all_namespaces(self, typeval, pointer_stripped):
807 # If we can't determine the namespace from the type name,
808 # fall back to trying all of our includes. An example of this is mutter,
809 # which has nominal namespace of "Meta", but a few classes are
810 # "Mutter". We don't export that data in introspection currently.
811 # Basically the library should be fixed, but we'll hack around it here.
812 for namespace in self._includes.itervalues():
813 target = namespace.get_by_ctype(pointer_stripped)
815 typeval.target_giname = '%s.%s' % (namespace.name, target.name)
819 def _resolve_type_from_ctype(self, typeval):
820 assert typeval.ctype is not None
821 pointer_stripped = typeval.ctype.replace('*', '')
823 matches = self.split_ctype_namespaces(pointer_stripped)
824 except ValueError, e:
825 return self._resolve_type_from_ctype_all_namespaces(typeval, pointer_stripped)
827 for namespace, name in matches:
828 target = namespace.get(name)
830 target = namespace.get_by_ctype(pointer_stripped)
832 typeval.target_giname = '%s.%s' % (namespace.name, target.name)
836 def _resolve_type_from_gtype_name(self, typeval):
837 assert typeval.gtype_name is not None
838 for ns in self._iter_namespaces():
839 for node in ns.itervalues():
840 if not (isinstance(node, (ast.Class, ast.Interface))
841 or (isinstance(node, ast.Registered) and node.get_type is not None)):
843 if node.gtype_name == typeval.gtype_name:
844 typeval.target_giname = '%s.%s' % (ns.name, node.name)
848 def resolve_type(self, typeval):
849 if isinstance(typeval, (ast.Array, ast.List)):
850 return self.resolve_type(typeval.element_type)
851 elif isinstance(typeval, ast.Map):
852 key_resolved = self.resolve_type(typeval.key_type)
853 value_resolved = self.resolve_type(typeval.value_type)
854 return key_resolved and value_resolved
855 elif typeval.resolved:
858 return self._resolve_type_from_ctype(typeval)
859 elif typeval.gtype_name:
860 return self._resolve_type_from_gtype_name(typeval)
862 def _typepair_to_str(self, item):
866 return '%s.%s' % (nsname, item.name)
868 def gtypename_to_giname(self, gtname, names):
869 resolved = names.type_names.get(gtname)
871 return self._typepair_to_str(resolved)
872 resolved = self._names.type_names.get(gtname)
874 return self._typepair_to_str(resolved)
875 raise KeyError("Failed to resolve GType name: %r" % (gtname, ))
877 def ctype_of(self, obj):
878 if hasattr(obj, 'ctype'):
880 elif hasattr(obj, 'symbol'):
885 def resolve_aliases(self, typenode):
886 """Removes all aliases from typenode, returns first non-alias
887 in the typenode alias chain. Returns typenode argument if it
889 while isinstance(typenode, ast.Alias):
890 if typenode.target.target_giname is not None:
891 typenode = self.lookup_giname(typenode.target.target_giname)
892 elif typenode.target.target_fundamental is not None:
893 typenode = ast.type_names[typenode.target.target_fundamental]