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.
23 from .ast import (Bitfield, Callback, Enum, Function, Namespace, Member,
24 Parameter, Return, Struct, Field,
25 Type, Array, Alias, Interface, Class, Node, Union,
26 Varargs, Constant, type_name_from_ctype,
27 type_names, TYPE_STRING, BASIC_GIR_TYPES)
28 from .config import DATADIR, GIR_DIR, GIR_SUFFIX
29 from .glibast import GLibBoxed
30 from .girparser import GIRParser
31 from .odict import odict
32 from .sourcescanner import (
33 SourceSymbol, ctype_name, CTYPE_POINTER,
34 CTYPE_BASIC_TYPE, CTYPE_UNION, CTYPE_ARRAY, CTYPE_TYPEDEF,
35 CTYPE_VOID, CTYPE_ENUM, CTYPE_FUNCTION, CTYPE_STRUCT,
36 CSYMBOL_TYPE_FUNCTION, CSYMBOL_TYPE_TYPEDEF, CSYMBOL_TYPE_STRUCT,
37 CSYMBOL_TYPE_ENUM, CSYMBOL_TYPE_UNION, CSYMBOL_TYPE_OBJECT,
38 CSYMBOL_TYPE_MEMBER, CSYMBOL_TYPE_ELLIPSIS, CSYMBOL_TYPE_CONST,
40 from .utils import to_underscores
42 _xdg_data_dirs = [x for x in os.environ.get('XDG_DATA_DIRS', '').split(':') \
43 + [DATADIR, '/usr/share'] if x]
46 class SkipError(Exception):
51 names = property(lambda self: self._names)
52 aliases = property(lambda self: self._aliases)
53 type_names = property(lambda self: self._type_names)
54 ctypes = property(lambda self: self._ctypes)
57 super(Names, self).__init__()
58 self._names = odict() # Maps from GIName -> (namespace, node)
59 self._aliases = {} # Maps from GIName -> GIName
60 self._type_names = {} # Maps from GTName -> (namespace, node)
61 self._ctypes = {} # Maps from CType -> (namespace, node)
64 class Transformer(object):
66 def __init__(self, cachestore, namespace_name, namespace_version):
67 self._cachestore = cachestore
69 self._namespace = Namespace(namespace_name, namespace_version)
71 self._pkg_config_packages = set()
72 self._typedefs_ns = {}
73 self._strip_prefix = ''
74 self._includes = set()
75 self._includepaths = []
80 def get_includes(self):
83 def set_strip_prefix(self, strip_prefix):
84 self._strip_prefix = strip_prefix
86 def get_strip_prefix(self):
87 return self._strip_prefix
89 def get_pkgconfig_packages(self):
90 return self._pkg_config_packages
92 def set_source_ast(self, src_ast):
93 self.generator = src_ast
97 for symbol in self.generator.get_symbols():
99 node = self._traverse_one(symbol)
103 return self._namespace
105 def set_include_paths(self, paths):
106 self._includepaths = list(paths)
108 def register_include(self, include):
109 if include in self._includes:
111 filename = self._find_include(include)
112 self._parse_include(filename)
113 self._includes.add(include)
117 def _find_include(self, include):
118 searchdirs = self._includepaths[:]
119 for path in _xdg_data_dirs:
120 searchdirs.append(os.path.join(path, GIR_SUFFIX))
121 searchdirs.append(GIR_DIR)
123 girname = '%s-%s.gir' % (include.name, include.version)
125 path = os.path.join(d, girname)
126 if os.path.exists(path):
128 raise ValueError("Couldn't find include %r (search path: %r)"\
129 % (girname, searchdirs))
131 def _parse_include(self, filename):
132 parser = self._cachestore.load(filename)
135 parser.set_include_parsing(True)
136 parser.parse(filename)
137 self._cachestore.store(filename, parser)
139 for include in parser.get_includes():
140 self.register_include(include)
142 for pkg in parser.get_pkgconfig_packages():
143 self._pkg_config_packages.add(pkg)
144 namespace = parser.get_namespace()
145 nsname = namespace.name
146 for node in namespace.nodes:
147 if isinstance(node, Alias):
148 self._names.aliases[node.name] = (nsname, node)
149 elif isinstance(node, (GLibBoxed, Interface, Class)):
150 self._names.type_names[node.type_name] = (nsname, node)
151 giname = '%s.%s' % (nsname, node.name)
152 self._names.names[giname] = (nsname, node)
153 if hasattr(node, 'ctype'):
154 self._names.ctypes[node.ctype] = (nsname, node)
155 elif hasattr(node, 'symbol'):
156 self._names.ctypes[node.symbol] = (nsname, node)
158 def _add_node(self, node):
161 if node.name.startswith('_'):
163 self._namespace.nodes.append(node)
164 self._names.names[node.name] = (None, node)
166 def _strip_namespace_func(self, name):
167 prefix = self._namespace.name.lower() + '_'
168 if name.lower().startswith(prefix):
169 name = name[len(prefix):]
171 prefix = to_underscores(self._namespace.name).lower() + '_'
172 if name.lower().startswith(prefix):
173 name = name[len(prefix):]
174 return self.remove_prefix(name, isfunction=True)
176 def remove_prefix(self, name, isfunction=False):
177 # when --strip-prefix=g:
178 # GHashTable -> HashTable
179 # g_hash_table_new -> hash_table_new
180 prefix = self._strip_prefix.lower()
183 if len(name) > len(prefix) and name.lower().startswith(prefix):
184 name = name[len(prefix):]
186 while name.startswith('_'):
190 def _traverse_one(self, symbol, stype=None):
191 assert isinstance(symbol, SourceSymbol), symbol
195 if stype == CSYMBOL_TYPE_FUNCTION:
196 return self._create_function(symbol)
197 elif stype == CSYMBOL_TYPE_TYPEDEF:
198 return self._create_typedef(symbol)
199 elif stype == CSYMBOL_TYPE_STRUCT:
200 return self._create_struct(symbol)
201 elif stype == CSYMBOL_TYPE_ENUM:
202 return self._create_enum(symbol)
203 elif stype == CSYMBOL_TYPE_OBJECT:
204 return self._create_object(symbol)
205 elif stype == CSYMBOL_TYPE_MEMBER:
206 return self._create_member(symbol)
207 elif stype == CSYMBOL_TYPE_UNION:
208 return self._create_union(symbol)
209 elif stype == CSYMBOL_TYPE_CONST:
210 return self._create_const(symbol)
212 raise NotImplementedError(
213 'Transformer: unhandled symbol: %r' % (symbol, ))
215 def _enum_common_prefix(self, symbol):
216 def common_prefix(a, b):
218 for aword, bword in zip(a.split('_'), b.split('_')):
220 return '_'.join(commonparts) + '_'
221 commonparts.append(aword)
224 # Nothing less than 2 has a common prefix
225 if len(list(symbol.base_type.child_list)) < 2:
228 for child in symbol.base_type.child_list:
232 prefix = common_prefix(prefix, child.ident)
237 def _create_enum(self, symbol):
238 prefix = self._enum_common_prefix(symbol)
240 prefixlen = len(prefix)
244 for child in symbol.base_type.child_list:
246 name = child.ident[prefixlen:]
248 # Ok, the enum members don't have a consistent prefix
249 # among them, so let's just remove the global namespace
251 name = self.remove_prefix(child.ident)
252 members.append(Member(name.lower(),
256 enum_name = self.remove_prefix(symbol.ident)
257 if symbol.base_type.is_bitfield:
261 node = klass(enum_name, symbol.ident, members)
262 self._names.type_names[symbol.ident] = (None, node)
265 def _create_object(self, symbol):
266 return Member(symbol.ident, symbol.base_type.name,
269 def _type_is_callback(self, type):
270 if isinstance(type, Callback):
272 node = self._names.names.get(type.name)
273 if node and isinstance(node[1], Callback):
277 def _handle_closure(self, param, closure_idx, closure_param):
278 if (closure_param.type.name == 'any' and
279 closure_param.name.endswith('data')):
280 param.closure_name = closure_param.name
281 param.closure_index = closure_idx
285 def _handle_destroy(self, param, destroy_idx, destroy_param):
286 if (destroy_param.type.name == 'GLib.DestroyNotify' or
287 destroy_param.type.ctype == 'GDestroyNotify'):
288 param.destroy_name = destroy_param.name
289 param.destroy_index = destroy_idx
293 def _augment_callback_params(self, params):
294 for i, param in enumerate(params):
295 if not self._type_is_callback(param.type):
298 # j is the index where we look for closure/destroy to
299 # group with the callback param
302 continue # no more args -> nothing to group
303 # look at the param directly following for either a
304 # closure or a destroy; only one of these will fire
305 had_closure = self._handle_closure(param, j, params[j])
306 had_destroy = self._handle_destroy(param, j, params[j])
308 # are we out of params, or did we find neither?
309 if j == len(params) or (not had_closure and not had_destroy):
311 # we found either a closure or a destroy; check the
312 # parameter following for the other
314 self._handle_closure(param, j, params[j])
316 self._handle_destroy(param, j, params[j])
318 def _create_function(self, symbol):
319 parameters = list(self._create_parameters(symbol.base_type))
320 return_ = self._create_return(symbol.base_type.base_type)
321 self._augment_callback_params(parameters)
322 name = self._strip_namespace_func(symbol.ident)
323 func = Function(name, return_, parameters, symbol.ident)
326 def _create_source_type(self, source_type):
327 if source_type is None:
329 if source_type.type == CTYPE_VOID:
331 elif source_type.type == CTYPE_BASIC_TYPE:
332 value = source_type.name
333 elif source_type.type == CTYPE_TYPEDEF:
334 value = source_type.name
335 elif source_type.type == CTYPE_ARRAY:
336 return self._create_source_type(source_type.base_type)
337 elif source_type.type == CTYPE_POINTER:
338 value = self._create_source_type(source_type.base_type) + '*'
343 def _create_parameters(self, base_type):
345 # warn if we see annotations for unknown parameters
346 param_names = set(child.ident for child in base_type.child_list)
347 for child in base_type.child_list:
348 yield self._create_parameter(child)
350 def _create_member(self, symbol):
351 source_type = symbol.base_type
352 if (source_type.type == CTYPE_POINTER and
353 symbol.base_type.base_type.type == CTYPE_FUNCTION):
354 node = self._create_callback(symbol)
355 elif source_type.type == CTYPE_STRUCT and source_type.name is None:
356 node = self._create_struct(symbol, anonymous=True)
357 elif source_type.type == CTYPE_UNION and source_type.name is None:
358 node = self._create_union(symbol, anonymous=True)
360 # Special handling for fields; we don't have annotations on them
361 # to apply later, yet.
362 if source_type.type == CTYPE_ARRAY:
363 ctype = self._create_source_type(source_type)
364 canonical_ctype = self._canonicalize_ctype(ctype)
365 if canonical_ctype[-1] == '*':
366 derefed_name = canonical_ctype[:-1]
368 derefed_name = canonical_ctype
369 derefed_name = self.resolve_param_type(derefed_name)
370 ftype = Array(ctype, self.parse_ctype(derefed_name))
371 child_list = list(symbol.base_type.child_list)
372 ftype.zeroterminated = False
374 ftype.size = '%d' % (child_list[0].const_int, )
376 ftype = self._create_type(symbol.base_type,
377 is_param=False, is_retval=False)
378 ftype = self.resolve_param_type(ftype)
379 # Fields are assumed to be read-write
380 # (except for Objects, see also glibtransformer.py)
381 node = Field(symbol.ident, ftype, ftype.name,
382 readable=True, writable=True, bits=symbol.const_int)
385 def _create_typedef(self, symbol):
386 ctype = symbol.base_type.type
387 if (ctype == CTYPE_POINTER and
388 symbol.base_type.base_type.type == CTYPE_FUNCTION):
389 node = self._create_typedef_callback(symbol)
390 elif (ctype == CTYPE_POINTER and
391 symbol.base_type.base_type.type == CTYPE_STRUCT):
392 node = self._create_typedef_struct(symbol, disguised=True)
393 elif ctype == CTYPE_STRUCT:
394 node = self._create_typedef_struct(symbol)
395 elif ctype == CTYPE_UNION:
396 node = self._create_typedef_union(symbol)
397 elif ctype == CTYPE_ENUM:
398 return self._create_enum(symbol)
399 elif ctype in (CTYPE_TYPEDEF,
403 name = self.remove_prefix(symbol.ident)
404 if symbol.base_type.name:
405 target = self.remove_prefix(symbol.base_type.name)
408 if name in type_names:
410 return Alias(name, target, ctype=symbol.ident)
412 raise NotImplementedError(
413 "symbol %r of type %s" % (symbol.ident, ctype_name(ctype)))
416 def _canonicalize_ctype(self, ctype):
417 # First look up the ctype including any pointers;
418 # a few type names like 'char*' have their own aliases
419 # and we need pointer information for those.
420 firstpass = type_name_from_ctype(ctype)
422 # If we have a particular alias for this, skip deep
423 # canonicalization to prevent changing
424 # e.g. char* -> int8*
425 if firstpass != ctype:
428 # We're also done if the type is already a fundamental
429 # known type, or there are no pointers.
430 if ctype in type_names or not firstpass.endswith('*'):
433 # We have a pointer type.
434 # Strip the end pointer, canonicalize our base type
435 base = firstpass[:-1]
436 canonical_base = self._canonicalize_ctype(base)
438 # Append the pointer again
439 canonical = canonical_base + '*'
443 def parse_ctype(self, ctype, is_member=False):
444 canonical = self._canonicalize_ctype(ctype)
446 # Remove all pointers - we require standard calling
447 # conventions. For example, an 'int' is always passed by
448 # value (unless it's out or inout).
449 derefed_typename = canonical.replace('*', '')
451 # Preserve "pointerness" of struct/union members
452 if (is_member and canonical.endswith('*') and
453 derefed_typename in BASIC_GIR_TYPES):
456 return derefed_typename
458 def _create_type(self, source_type, is_param, is_retval):
459 ctype = self._create_source_type(source_type)
460 if ctype.startswith('va_list'):
462 # FIXME: FILE* should not be skipped, it should be handled
464 elif ctype == 'FILE*':
467 is_member = not (is_param or is_retval)
468 # Here we handle basic type parsing; most of the heavy lifting
469 # and inference comes in annotationparser.py when we merge
470 # in annotation data.
471 derefed_name = self.parse_ctype(ctype, is_member)
472 rettype = Type(derefed_name, ctype)
473 rettype.canonical = self._canonicalize_ctype(ctype)
474 derefed_ctype = ctype.replace('*', '')
475 rettype.derefed_canonical = self._canonicalize_ctype(derefed_ctype)
477 canontype = type_name_from_ctype(ctype)
478 # Is it a const char * or a const gpointer?
479 if ((canontype == TYPE_STRING or source_type.type == CTYPE_POINTER) and
480 (source_type.base_type.type_qualifier & TYPE_QUALIFIER_CONST)):
481 rettype.is_const = True
484 def _create_parameter(self, symbol):
485 if symbol.type == CSYMBOL_TYPE_ELLIPSIS:
488 ptype = self._create_type(symbol.base_type,
489 is_param=True, is_retval=False)
490 ptype = self.resolve_param_type(ptype)
491 return Parameter(symbol.ident, ptype)
493 def _create_return(self, source_type):
494 rtype = self._create_type(source_type,
495 is_param=False, is_retval=True)
496 rtype = self.resolve_param_type(rtype)
497 return_ = Return(rtype)
500 def _create_const(self, symbol):
501 # Don't create constants for non-public things
502 # http://bugzilla.gnome.org/show_bug.cgi?id=572790
503 if (symbol.source_filename is None or
504 not symbol.source_filename.endswith('.h')):
506 name = self.remove_prefix(symbol.ident)
507 if symbol.const_string is not None:
509 value = symbol.const_string
510 elif symbol.const_int is not None:
512 value = symbol.const_int
513 elif symbol.const_double is not None:
515 value = symbol.const_double
517 raise AssertionError()
519 const = Constant(name, type_name, value)
522 def _create_typedef_struct(self, symbol, disguised=False):
523 name = self.remove_prefix(symbol.ident)
524 struct = Struct(name, symbol.ident, disguised)
525 self._typedefs_ns[symbol.ident] = struct
526 self._create_struct(symbol)
529 def _create_typedef_union(self, symbol):
530 name = self.remove_prefix(symbol.ident)
531 union = Union(name, symbol.ident)
532 self._typedefs_ns[symbol.ident] = union
533 self._create_union(symbol)
536 def _create_typedef_callback(self, symbol):
537 callback = self._create_callback(symbol)
538 self._typedefs_ns[callback.name] = callback
541 def _create_compound(self, klass, symbol, anonymous):
542 if symbol.ident is None:
543 # the compound is an anonymous member of another union or a struct
545 compound = klass(None, None)
547 compound = self._typedefs_ns.get(symbol.ident, None)
550 # This is a bit of a hack; really we should try
551 # to resolve through the typedefs to find the real
553 if symbol.ident.startswith('_'):
554 name = symbol.ident[1:]
555 compound = self._typedefs_ns.get(name, None)
559 name = self.remove_prefix(name)
560 compound = klass(name, symbol.ident)
562 for child in symbol.base_type.child_list:
563 field = self._traverse_one(child)
565 compound.fields.append(field)
569 def _create_struct(self, symbol, anonymous=False):
570 return self._create_compound(Struct, symbol, anonymous)
572 def _create_union(self, symbol, anonymous=False):
573 return self._create_compound(Union, symbol, anonymous)
575 def _create_callback(self, symbol):
576 parameters = list(self._create_parameters(symbol.base_type.base_type))
577 retval = self._create_return(symbol.base_type.base_type.base_type)
579 # Mark the 'user_data' arguments
580 for i, param in enumerate(parameters):
581 if (param.type.name == 'any' and
582 param.name == 'user_data'):
583 param.closure_index = i
585 if symbol.ident.find('_') > 0:
586 name = self.remove_prefix(symbol.ident, True)
588 name = self.remove_prefix(symbol.ident)
589 callback = Callback(name, retval, parameters, symbol.ident)
593 def _typepair_to_str(self, item):
597 return '%s.%s' % (nsname, item.name)
599 def _resolve_type_name_1(self, type_name, ctype, names):
600 # First look using the built-in names
603 return type_names[ctype]
607 return type_names[type_name]
612 ctype = ctype.replace('*', '')
613 resolved = names.ctypes.get(ctype)
615 return self._typepair_to_str(resolved)
616 type_name = self.remove_prefix(type_name)
617 resolved = names.aliases.get(type_name)
619 return self._typepair_to_str(resolved)
620 resolved = names.names.get(type_name)
622 return self._typepair_to_str(resolved)
623 resolved = names.type_names.get(type_name)
625 return self._typepair_to_str(resolved)
626 raise KeyError("failed to find %r" % (type_name, ))
628 def resolve_type_name_full(self, type_name, ctype,
629 names, allow_invalid=True):
631 return self._resolve_type_name_1(type_name, ctype, names)
634 return self._resolve_type_name_1(type_name, ctype, self._names)
636 if not allow_invalid:
640 def resolve_type_name(self, type_name, ctype=None):
642 return self.resolve_type_name_full(type_name, ctype, self._names)
646 def gtypename_to_giname(self, gtname, names):
647 resolved = names.type_names.get(gtname)
649 return self._typepair_to_str(resolved)
650 resolved = self._names.type_names.get(gtname)
652 return self._typepair_to_str(resolved)
653 raise KeyError("Failed to resolve GType name: %r" % (gtname, ))
655 def ctype_of(self, obj):
656 if hasattr(obj, 'ctype'):
658 elif hasattr(obj, 'symbol'):
663 def resolve_param_type_full(self, ptype, names, **kwargs):
664 if isinstance(ptype, Node):
665 ptype.name = self.resolve_type_name_full(ptype.name,
666 self.ctype_of(ptype),
668 elif isinstance(ptype, basestring):
669 return self.resolve_type_name_full(ptype, ptype, names, **kwargs)
671 raise AssertionError("Unhandled param: %r" % (ptype, ))
674 def resolve_param_type(self, ptype):
676 return self.resolve_param_type_full(ptype, self._names)
680 def follow_aliases(self, type_name, names):
682 resolved = names.aliases.get(type_name)
684 (ns, alias) = resolved
685 type_name = alias.target