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
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-1.0'))
122 girname = '%s-%s.gir' % (include.name, include.version)
124 path = os.path.join(d, girname)
125 if os.path.exists(path):
127 raise ValueError("Couldn't find include %r (search path: %r)"\
128 % (girname, searchdirs))
130 def _parse_include(self, filename):
131 parser = self._cachestore.load(filename)
134 parser.set_include_parsing(True)
135 parser.parse(filename)
136 self._cachestore.store(filename, parser)
138 for include in parser.get_includes():
139 self.register_include(include)
141 for pkg in parser.get_pkgconfig_packages():
142 self._pkg_config_packages.add(pkg)
143 namespace = parser.get_namespace()
144 nsname = namespace.name
145 for node in namespace.nodes:
146 if isinstance(node, Alias):
147 self._names.aliases[node.name] = (nsname, node)
148 elif isinstance(node, (GLibBoxed, Interface, Class)):
149 self._names.type_names[node.type_name] = (nsname, node)
150 giname = '%s.%s' % (nsname, node.name)
151 self._names.names[giname] = (nsname, node)
152 if hasattr(node, 'ctype'):
153 self._names.ctypes[node.ctype] = (nsname, node)
154 elif hasattr(node, 'symbol'):
155 self._names.ctypes[node.symbol] = (nsname, node)
157 def _add_node(self, node):
160 if node.name.startswith('_'):
162 self._namespace.nodes.append(node)
163 self._names.names[node.name] = (None, node)
165 def _strip_namespace_func(self, name):
166 prefix = self._namespace.name.lower() + '_'
167 if name.lower().startswith(prefix):
168 name = name[len(prefix):]
170 prefix = to_underscores(self._namespace.name).lower() + '_'
171 if name.lower().startswith(prefix):
172 name = name[len(prefix):]
173 return self.remove_prefix(name, isfunction=True)
175 def remove_prefix(self, name, isfunction=False):
176 # when --strip-prefix=g:
177 # GHashTable -> HashTable
178 # g_hash_table_new -> hash_table_new
179 prefix = self._strip_prefix.lower()
182 if len(name) > len(prefix) and name.lower().startswith(prefix):
183 name = name[len(prefix):]
185 while name.startswith('_'):
189 def _traverse_one(self, symbol, stype=None):
190 assert isinstance(symbol, SourceSymbol), symbol
194 if stype == CSYMBOL_TYPE_FUNCTION:
195 return self._create_function(symbol)
196 elif stype == CSYMBOL_TYPE_TYPEDEF:
197 return self._create_typedef(symbol)
198 elif stype == CSYMBOL_TYPE_STRUCT:
199 return self._create_struct(symbol)
200 elif stype == CSYMBOL_TYPE_ENUM:
201 return self._create_enum(symbol)
202 elif stype == CSYMBOL_TYPE_OBJECT:
203 return self._create_object(symbol)
204 elif stype == CSYMBOL_TYPE_MEMBER:
205 return self._create_member(symbol)
206 elif stype == CSYMBOL_TYPE_UNION:
207 return self._create_union(symbol)
208 elif stype == CSYMBOL_TYPE_CONST:
209 return self._create_const(symbol)
211 raise NotImplementedError(
212 'Transformer: unhandled symbol: %r' % (symbol, ))
214 def _enum_common_prefix(self, symbol):
215 def common_prefix(a, b):
225 # Nothing less than 2 has a common prefix
226 if len(list(symbol.base_type.child_list)) < 2:
229 for child in symbol.base_type.child_list:
233 prefix = common_prefix(prefix, child.ident)
238 def _create_enum(self, symbol):
239 prefix = self._enum_common_prefix(symbol)
241 prefixlen = len(prefix)
245 for child in symbol.base_type.child_list:
247 name = child.ident[prefixlen:]
249 # Ok, the enum members don't have a consistent prefix
250 # among them, so let's just remove the global namespace
252 name = self.remove_prefix(child.ident)
253 members.append(Member(name.lower(),
257 enum_name = self.remove_prefix(symbol.ident)
258 if symbol.base_type.is_bitfield:
262 node = klass(enum_name, symbol.ident, members)
263 self._names.type_names[symbol.ident] = (None, node)
266 def _create_object(self, symbol):
267 return Member(symbol.ident, symbol.base_type.name,
270 def _type_is_callback(self, type):
271 if (isinstance(type, Callback) or
272 isinstance(self._typedefs_ns.get(type.name), Callback)):
276 def _handle_closure(self, param, closure_idx, closure_param):
277 if (closure_param.type.name == 'any' and
278 closure_param.name.endswith('data')):
279 param.closure_name = closure_param.name
280 param.closure_index = closure_idx
284 def _handle_destroy(self, param, destroy_idx, destroy_param):
285 if ((self._namespace.name == 'GLib' and
286 destroy_param.type.name == 'DestroyNotify') or
287 destroy_param.type.name == 'GLib.DestroyNotify'):
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 if ((canontype == TYPE_STRING or
479 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 not symbol.source_filename.endswith('.h'):
505 name = self.remove_prefix(symbol.ident)
506 if symbol.const_string is not None:
508 value = symbol.const_string
509 elif symbol.const_int is not None:
511 value = symbol.const_int
512 elif symbol.const_double is not None:
514 value = symbol.const_double
516 raise AssertionError()
518 const = Constant(name, type_name, value)
521 def _create_typedef_struct(self, symbol, disguised=False):
522 name = self.remove_prefix(symbol.ident)
523 struct = Struct(name, symbol.ident, disguised)
524 self._typedefs_ns[symbol.ident] = struct
525 self._create_struct(symbol)
528 def _create_typedef_union(self, symbol):
529 name = self.remove_prefix(symbol.ident)
530 union = Union(name, symbol.ident)
531 self._typedefs_ns[symbol.ident] = union
532 self._create_union(symbol)
535 def _create_typedef_callback(self, symbol):
536 callback = self._create_callback(symbol)
537 self._typedefs_ns[callback.name] = callback
540 def _create_compound(self, klass, symbol, anonymous):
541 if symbol.ident is None:
542 # the compound is an anonymous member of another union or a struct
544 compound = klass(None, None)
546 compound = self._typedefs_ns.get(symbol.ident, None)
549 # This is a bit of a hack; really we should try
550 # to resolve through the typedefs to find the real
552 if symbol.ident.startswith('_'):
553 name = symbol.ident[1:]
554 compound = self._typedefs_ns.get(name, None)
558 name = self.remove_prefix(name)
559 compound = klass(name, symbol.ident)
561 for child in symbol.base_type.child_list:
562 field = self._traverse_one(child)
564 compound.fields.append(field)
568 def _create_struct(self, symbol, anonymous=False):
569 return self._create_compound(Struct, symbol, anonymous)
571 def _create_union(self, symbol, anonymous=False):
572 return self._create_compound(Union, symbol, anonymous)
574 def _create_callback(self, symbol):
575 parameters = list(self._create_parameters(symbol.base_type.base_type))
576 retval = self._create_return(symbol.base_type.base_type.base_type)
578 # Mark the 'user_data' arguments
579 for i, param in enumerate(parameters):
580 if (param.type.name == 'any' and
581 param.name == 'user_data'):
582 param.closure_index = i
584 if symbol.ident.find('_') > 0:
585 name = self.remove_prefix(symbol.ident, True)
587 name = self.remove_prefix(symbol.ident)
588 callback = Callback(name, retval, parameters, symbol.ident)
592 def _typepair_to_str(self, item):
596 return '%s.%s' % (nsname, item.name)
598 def _resolve_type_name_1(self, type_name, ctype, names):
599 # First look using the built-in names
602 return type_names[ctype]
606 return type_names[type_name]
611 ctype = ctype.replace('*', '')
612 resolved = names.ctypes.get(ctype)
614 return self._typepair_to_str(resolved)
615 type_name = self.remove_prefix(type_name)
616 resolved = names.aliases.get(type_name)
618 return self._typepair_to_str(resolved)
619 resolved = names.names.get(type_name)
621 return self._typepair_to_str(resolved)
622 resolved = names.type_names.get(type_name)
624 return self._typepair_to_str(resolved)
625 raise KeyError("failed to find %r" % (type_name, ))
627 def resolve_type_name_full(self, type_name, ctype,
628 names, allow_invalid=True):
630 return self._resolve_type_name_1(type_name, ctype, names)
633 return self._resolve_type_name_1(type_name, ctype, self._names)
635 if not allow_invalid:
639 def resolve_type_name(self, type_name, ctype=None):
641 return self.resolve_type_name_full(type_name, ctype, self._names)
645 def gtypename_to_giname(self, gtname, names):
646 resolved = names.type_names.get(gtname)
648 return self._typepair_to_str(resolved)
649 resolved = self._names.type_names.get(gtname)
651 return self._typepair_to_str(resolved)
652 raise KeyError("Failed to resolve GType name: %r" % (gtname, ))
654 def ctype_of(self, obj):
655 if hasattr(obj, 'ctype'):
657 elif hasattr(obj, 'symbol'):
662 def resolve_param_type_full(self, ptype, names, **kwargs):
663 if isinstance(ptype, Node):
664 ptype.name = self.resolve_type_name_full(ptype.name,
665 self.ctype_of(ptype),
667 elif isinstance(ptype, basestring):
668 return self.resolve_type_name_full(ptype, None, names, **kwargs)
670 raise AssertionError("Unhandled param: %r" % (ptype, ))
673 def resolve_param_type(self, ptype):
675 return self.resolve_param_type_full(ptype, self._names)
679 def follow_aliases(self, type_name, names):
681 resolved = names.aliases.get(type_name)
683 (ns, alias) = resolved
684 type_name = alias.target