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.
24 from .ast import (Bitfield, Callback, Enum, Function, Namespace, Member,
25 Parameter, Return, Struct, Field,
26 Type, Array, Alias, Interface, Class, Node, Union,
27 Varargs, Constant, type_name_from_ctype,
28 type_names, TYPE_STRING, BASIC_GIR_TYPES)
29 from .config import DATADIR, GIR_DIR, GIR_SUFFIX
30 from .glibast import GLibBoxed
31 from .girparser import GIRParser
32 from .odict import odict
33 from .sourcescanner import (
34 SourceSymbol, ctype_name, CTYPE_POINTER,
35 CTYPE_BASIC_TYPE, CTYPE_UNION, CTYPE_ARRAY, CTYPE_TYPEDEF,
36 CTYPE_VOID, CTYPE_ENUM, CTYPE_FUNCTION, CTYPE_STRUCT,
37 CSYMBOL_TYPE_FUNCTION, CSYMBOL_TYPE_TYPEDEF, CSYMBOL_TYPE_STRUCT,
38 CSYMBOL_TYPE_ENUM, CSYMBOL_TYPE_UNION, CSYMBOL_TYPE_OBJECT,
39 CSYMBOL_TYPE_MEMBER, CSYMBOL_TYPE_ELLIPSIS, CSYMBOL_TYPE_CONST,
41 from .utils import to_underscores
43 _xdg_data_dirs = [x for x in os.environ.get('XDG_DATA_DIRS', '').split(':') \
44 + [DATADIR, '/usr/share'] if x]
47 class SkipError(Exception):
50 class VaListSkipError(SkipError):
54 names = property(lambda self: self._names)
55 aliases = property(lambda self: self._aliases)
56 type_names = property(lambda self: self._type_names)
57 ctypes = property(lambda self: self._ctypes)
60 super(Names, self).__init__()
61 self._names = odict() # Maps from GIName -> (namespace, node)
62 self._aliases = {} # Maps from GIName -> GIName
63 self._type_names = {} # Maps from GTName -> (namespace, node)
64 self._ctypes = {} # Maps from CType -> (namespace, node)
67 class Transformer(object):
69 def __init__(self, cachestore, namespace_name, namespace_version):
70 self._cachestore = cachestore
72 self._namespace = Namespace(namespace_name, namespace_version)
74 self._pkg_config_packages = set()
75 self._typedefs_ns = {}
76 self._strip_prefix = ''
77 self._includes = set()
78 self._includepaths = []
83 def get_includes(self):
86 def set_strip_prefix(self, strip_prefix):
87 self._strip_prefix = strip_prefix
89 def get_strip_prefix(self):
90 return self._strip_prefix
92 def get_pkgconfig_packages(self):
93 return self._pkg_config_packages
95 def set_source_ast(self, src_ast):
96 self.generator = src_ast
100 for symbol in self.generator.get_symbols():
102 node = self._traverse_one(symbol)
106 return self._namespace
108 def set_include_paths(self, paths):
109 self._includepaths = list(paths)
111 def register_include(self, include):
112 if include in self._includes:
114 filename = self._find_include(include)
115 self._parse_include(filename)
116 self._includes.add(include)
120 def _find_include(self, include):
121 searchdirs = self._includepaths[:]
122 for path in _xdg_data_dirs:
123 searchdirs.append(os.path.join(path, GIR_SUFFIX))
124 searchdirs.append(GIR_DIR)
126 girname = '%s-%s.gir' % (include.name, include.version)
128 path = os.path.join(d, girname)
129 if os.path.exists(path):
131 sys.stderr.write("Couldn't find include %r (search path: %r)\n"\
132 % (girname, searchdirs))
135 def _parse_include(self, filename):
136 parser = self._cachestore.load(filename)
139 parser.set_include_parsing(True)
140 parser.parse(filename)
141 self._cachestore.store(filename, parser)
143 for include in parser.get_includes():
144 self.register_include(include)
146 for pkg in parser.get_pkgconfig_packages():
147 self._pkg_config_packages.add(pkg)
148 namespace = parser.get_namespace()
149 nsname = namespace.name
150 for node in namespace.nodes:
151 if isinstance(node, Alias):
152 self._names.aliases[node.name] = (nsname, node)
153 elif isinstance(node, (GLibBoxed, Interface, Class)):
154 self._names.type_names[node.type_name] = (nsname, node)
155 giname = '%s.%s' % (nsname, node.name)
156 self._names.names[giname] = (nsname, node)
157 if hasattr(node, 'ctype'):
158 self._names.ctypes[node.ctype] = (nsname, node)
159 elif hasattr(node, 'symbol'):
160 self._names.ctypes[node.symbol] = (nsname, node)
162 def _add_node(self, node):
165 if node.name.startswith('_'):
167 self._namespace.nodes.append(node)
168 self._names.names[node.name] = (None, node)
170 def _strip_namespace_func(self, name):
171 prefix = self._namespace.name.lower() + '_'
172 if name.lower().startswith(prefix):
173 name = name[len(prefix):]
175 prefix = to_underscores(self._namespace.name).lower() + '_'
176 if name.lower().startswith(prefix):
177 name = name[len(prefix):]
178 return self.remove_prefix(name, isfunction=True)
180 def remove_prefix(self, name, isfunction=False):
181 # when --strip-prefix=g:
182 # GHashTable -> HashTable
183 # g_hash_table_new -> hash_table_new
184 prefix = self._strip_prefix.lower()
187 if len(name) > len(prefix) and name.lower().startswith(prefix):
188 name = name[len(prefix):]
190 while name.startswith('_'):
194 def _traverse_one(self, symbol, stype=None):
195 assert isinstance(symbol, SourceSymbol), symbol
199 if stype == CSYMBOL_TYPE_FUNCTION:
200 return self._create_function(symbol)
201 elif stype == CSYMBOL_TYPE_TYPEDEF:
202 return self._create_typedef(symbol)
203 elif stype == CSYMBOL_TYPE_STRUCT:
204 return self._create_struct(symbol)
205 elif stype == CSYMBOL_TYPE_ENUM:
206 return self._create_enum(symbol)
207 elif stype == CSYMBOL_TYPE_OBJECT:
208 return self._create_object(symbol)
209 elif stype == CSYMBOL_TYPE_MEMBER:
210 return self._create_member(symbol)
211 elif stype == CSYMBOL_TYPE_UNION:
212 return self._create_union(symbol)
213 elif stype == CSYMBOL_TYPE_CONST:
214 return self._create_const(symbol)
216 raise NotImplementedError(
217 'Transformer: unhandled symbol: %r' % (symbol, ))
219 def _enum_common_prefix(self, symbol):
220 def common_prefix(a, b):
222 for aword, bword in zip(a.split('_'), b.split('_')):
224 return '_'.join(commonparts) + '_'
225 commonparts.append(aword)
228 # Nothing less than 2 has a common prefix
229 if len(list(symbol.base_type.child_list)) < 2:
232 for child in symbol.base_type.child_list:
236 prefix = common_prefix(prefix, child.ident)
241 def _create_enum(self, symbol):
242 prefix = self._enum_common_prefix(symbol)
244 prefixlen = len(prefix)
248 for child in symbol.base_type.child_list:
250 name = child.ident[prefixlen:]
252 # Ok, the enum members don't have a consistent prefix
253 # among them, so let's just remove the global namespace
255 name = self.remove_prefix(child.ident)
256 members.append(Member(name.lower(),
260 enum_name = self.remove_prefix(symbol.ident)
261 if symbol.base_type.is_bitfield:
265 node = klass(enum_name, symbol.ident, members)
266 self._names.type_names[symbol.ident] = (None, node)
269 def _create_object(self, symbol):
270 return Member(symbol.ident, symbol.base_type.name,
273 def _type_is_callback(self, type):
274 if isinstance(type, Callback):
276 node = self._names.names.get(type.name)
277 if node and isinstance(node[1], Callback):
281 def _handle_closure(self, param, closure_idx, closure_param):
282 if (closure_param.type.name == 'any' and
283 closure_param.name.endswith('data')):
284 param.closure_name = closure_param.name
285 param.closure_index = closure_idx
289 def _handle_destroy(self, param, destroy_idx, destroy_param):
290 if (destroy_param.type.name == 'GLib.DestroyNotify' or
291 destroy_param.type.ctype == 'GDestroyNotify'):
292 param.destroy_name = destroy_param.name
293 param.destroy_index = destroy_idx
297 def _augment_callback_params(self, params):
298 for i, param in enumerate(params):
299 if not self._type_is_callback(param.type):
302 # set a default scope
303 if param.scope is None:
306 # j is the index where we look for closure/destroy to
307 # group with the callback param
310 continue # no more args -> nothing to group
311 # look at the param directly following for either a
312 # closure or a destroy; only one of these will fire
313 had_closure = self._handle_closure(param, j, params[j])
314 had_destroy = self._handle_destroy(param, j, params[j])
316 # are we out of params, or did we find neither?
317 if j == len(params) or (not had_closure and not had_destroy):
319 # we found either a closure or a destroy; check the
320 # parameter following for the other
322 self._handle_closure(param, j, params[j])
324 self._handle_destroy(param, j, params[j])
326 def _create_function(self, symbol):
327 parameters = list(self._create_parameters(symbol.base_type))
328 return_ = self._create_return(symbol.base_type.base_type)
329 self._augment_callback_params(parameters)
330 name = self._strip_namespace_func(symbol.ident)
331 func = Function(name, return_, parameters, symbol.ident)
334 def _create_source_type(self, source_type):
335 if source_type is None:
337 if source_type.type == CTYPE_VOID:
339 elif source_type.type == CTYPE_BASIC_TYPE:
340 value = source_type.name
341 elif source_type.type == CTYPE_TYPEDEF:
342 value = source_type.name
343 elif source_type.type == CTYPE_ARRAY:
344 return self._create_source_type(source_type.base_type)
345 elif source_type.type == CTYPE_POINTER:
346 value = self._create_source_type(source_type.base_type) + '*'
351 def _create_parameters(self, base_type):
353 # warn if we see annotations for unknown parameters
354 param_names = set(child.ident for child in base_type.child_list)
355 for child in base_type.child_list:
356 yield self._create_parameter(child)
358 def _create_member(self, symbol):
359 source_type = symbol.base_type
360 if (source_type.type == CTYPE_POINTER and
361 symbol.base_type.base_type.type == CTYPE_FUNCTION):
363 node = self._create_callback(symbol)
364 except VaListSkipError:
365 #this handles va_list members, and converts them
366 #to unwritable, unreadable void*
367 ftype = Type("any", "void*")
368 ftype = self.resolve_param_type(ftype)
369 node = Field(symbol.ident, ftype, ftype.name,
370 readable=False, writable=False, bits=symbol.const_int)
373 elif source_type.type == CTYPE_STRUCT and source_type.name is None:
374 node = self._create_struct(symbol, anonymous=True)
375 elif source_type.type == CTYPE_UNION and source_type.name is None:
376 node = self._create_union(symbol, anonymous=True)
378 # Special handling for fields; we don't have annotations on them
379 # to apply later, yet.
380 if source_type.type == CTYPE_ARRAY:
381 ctype = self._create_source_type(source_type)
382 canonical_ctype = self._canonicalize_ctype(ctype)
383 if canonical_ctype[-1] == '*':
384 derefed_name = canonical_ctype[:-1]
386 derefed_name = canonical_ctype
387 derefed_name = self.resolve_param_type(derefed_name)
388 ftype = Array(ctype, self.parse_ctype(derefed_name))
389 child_list = list(symbol.base_type.child_list)
390 ftype.zeroterminated = False
392 ftype.size = '%d' % (child_list[0].const_int, )
394 ftype = self._create_type(symbol.base_type,
395 is_param=False, is_retval=False)
396 ftype = self.resolve_param_type(ftype)
397 # Fields are assumed to be read-write
398 # (except for Objects, see also glibtransformer.py)
399 node = Field(symbol.ident, ftype, ftype.name,
400 readable=True, writable=True, bits=symbol.const_int)
403 def _create_typedef(self, symbol):
404 ctype = symbol.base_type.type
405 if (ctype == CTYPE_POINTER and
406 symbol.base_type.base_type.type == CTYPE_FUNCTION):
407 node = self._create_typedef_callback(symbol)
408 elif (ctype == CTYPE_POINTER and
409 symbol.base_type.base_type.type == CTYPE_STRUCT):
410 node = self._create_typedef_struct(symbol, disguised=True)
411 elif ctype == CTYPE_STRUCT:
412 node = self._create_typedef_struct(symbol)
413 elif ctype == CTYPE_UNION:
414 node = self._create_typedef_union(symbol)
415 elif ctype == CTYPE_ENUM:
416 return self._create_enum(symbol)
417 elif ctype in (CTYPE_TYPEDEF,
421 name = self.remove_prefix(symbol.ident)
422 if symbol.base_type.name:
423 target = self.remove_prefix(symbol.base_type.name)
426 if name in type_names:
428 return Alias(name, target, ctype=symbol.ident)
430 raise NotImplementedError(
431 "symbol %r of type %s" % (symbol.ident, ctype_name(ctype)))
434 def _canonicalize_ctype(self, ctype):
435 # First look up the ctype including any pointers;
436 # a few type names like 'char*' have their own aliases
437 # and we need pointer information for those.
438 firstpass = type_name_from_ctype(ctype)
440 # If we have a particular alias for this, skip deep
441 # canonicalization to prevent changing
442 # e.g. char* -> int8*
443 if firstpass != ctype:
446 # We're also done if the type is already a fundamental
447 # known type, or there are no pointers.
448 if ctype in type_names or not firstpass.endswith('*'):
451 # We have a pointer type.
452 # Strip the end pointer, canonicalize our base type
453 base = firstpass[:-1]
454 canonical_base = self._canonicalize_ctype(base)
456 # Append the pointer again
457 canonical = canonical_base + '*'
461 def parse_ctype(self, ctype, is_member=False):
462 canonical = self._canonicalize_ctype(ctype)
464 # Remove all pointers - we require standard calling
465 # conventions. For example, an 'int' is always passed by
466 # value (unless it's out or inout).
467 derefed_typename = canonical.replace('*', '')
469 # Preserve "pointerness" of struct/union members
470 if (is_member and canonical.endswith('*') and
471 derefed_typename in BASIC_GIR_TYPES):
474 return derefed_typename
476 def _create_type(self, source_type, is_param, is_retval):
477 ctype = self._create_source_type(source_type)
478 if ctype.startswith('va_list'):
479 raise VaListSkipError()
480 # FIXME: FILE* should not be skipped, it should be handled
482 elif ctype == 'FILE*':
485 is_member = not (is_param or is_retval)
486 # Here we handle basic type parsing; most of the heavy lifting
487 # and inference comes in annotationparser.py when we merge
488 # in annotation data.
489 derefed_name = self.parse_ctype(ctype, is_member)
490 rettype = Type(derefed_name, ctype)
491 rettype.canonical = self._canonicalize_ctype(ctype)
492 derefed_ctype = ctype.replace('*', '')
493 rettype.derefed_canonical = self._canonicalize_ctype(derefed_ctype)
495 canontype = type_name_from_ctype(ctype)
496 # Is it a const char * or a const gpointer?
497 if ((canontype == TYPE_STRING or source_type.type == CTYPE_POINTER) and
498 (source_type.base_type.type_qualifier & TYPE_QUALIFIER_CONST)):
499 rettype.is_const = True
502 def _create_parameter(self, symbol):
503 if symbol.type == CSYMBOL_TYPE_ELLIPSIS:
506 ptype = self._create_type(symbol.base_type,
507 is_param=True, is_retval=False)
508 ptype = self.resolve_param_type(ptype)
509 return Parameter(symbol.ident, ptype)
511 def _create_return(self, source_type):
512 rtype = self._create_type(source_type,
513 is_param=False, is_retval=True)
514 rtype = self.resolve_param_type(rtype)
515 return_ = Return(rtype)
518 def _create_const(self, symbol):
519 # Don't create constants for non-public things
520 # http://bugzilla.gnome.org/show_bug.cgi?id=572790
521 if (symbol.source_filename is None or
522 not symbol.source_filename.endswith('.h')):
524 name = self.remove_prefix(symbol.ident)
525 if symbol.const_string is not None:
527 value = symbol.const_string
528 elif symbol.const_int is not None:
530 value = symbol.const_int
531 elif symbol.const_double is not None:
533 value = symbol.const_double
535 raise AssertionError()
537 const = Constant(name, type_name, value)
540 def _create_typedef_struct(self, symbol, disguised=False):
541 name = self.remove_prefix(symbol.ident)
542 struct = Struct(name, symbol.ident, disguised)
543 self._typedefs_ns[symbol.ident] = struct
544 self._create_struct(symbol)
547 def _create_typedef_union(self, symbol):
548 name = self.remove_prefix(symbol.ident)
549 union = Union(name, symbol.ident)
550 self._typedefs_ns[symbol.ident] = union
551 self._create_union(symbol)
554 def _create_typedef_callback(self, symbol):
555 callback = self._create_callback(symbol)
556 self._typedefs_ns[callback.name] = callback
559 def _create_compound(self, klass, symbol, anonymous):
560 if symbol.ident is None:
561 # the compound is an anonymous member of another union or a struct
563 compound = klass(None, None)
565 compound = self._typedefs_ns.get(symbol.ident, None)
568 # This is a bit of a hack; really we should try
569 # to resolve through the typedefs to find the real
571 if symbol.ident.startswith('_'):
572 name = symbol.ident[1:]
573 compound = self._typedefs_ns.get(name, None)
577 name = self.remove_prefix(name)
578 compound = klass(name, symbol.ident)
580 for child in symbol.base_type.child_list:
581 field = self._traverse_one(child)
583 compound.fields.append(field)
587 def _create_struct(self, symbol, anonymous=False):
588 return self._create_compound(Struct, symbol, anonymous)
590 def _create_union(self, symbol, anonymous=False):
591 return self._create_compound(Union, symbol, anonymous)
593 def _create_callback(self, symbol):
594 parameters = list(self._create_parameters(symbol.base_type.base_type))
595 retval = self._create_return(symbol.base_type.base_type.base_type)
597 # Mark the 'user_data' arguments
598 for i, param in enumerate(parameters):
599 if (param.type.name == 'any' and
600 param.name == 'user_data'):
601 param.closure_index = i
603 if symbol.ident.find('_') > 0:
604 name = self.remove_prefix(symbol.ident, True)
606 name = self.remove_prefix(symbol.ident)
607 callback = Callback(name, retval, parameters, symbol.ident)
611 def _typepair_to_str(self, item):
615 return '%s.%s' % (nsname, item.name)
617 def _resolve_type_name_1(self, type_name, ctype, names):
618 # First look using the built-in names
621 return type_names[ctype]
625 return type_names[type_name]
630 ctype = ctype.replace('*', '')
631 resolved = names.ctypes.get(ctype)
633 return self._typepair_to_str(resolved)
634 type_name = self.remove_prefix(type_name)
635 resolved = names.aliases.get(type_name)
637 return self._typepair_to_str(resolved)
638 resolved = names.names.get(type_name)
640 return self._typepair_to_str(resolved)
641 resolved = names.type_names.get(type_name)
643 return self._typepair_to_str(resolved)
644 raise KeyError("failed to find %r" % (type_name, ))
646 def resolve_type_name_full(self, type_name, ctype,
647 names, allow_invalid=True):
649 return self._resolve_type_name_1(type_name, ctype, names)
652 return self._resolve_type_name_1(type_name, ctype, self._names)
654 if not allow_invalid:
658 def resolve_type_name(self, type_name, ctype=None):
660 return self.resolve_type_name_full(type_name, ctype, self._names)
664 def gtypename_to_giname(self, gtname, names):
665 resolved = names.type_names.get(gtname)
667 return self._typepair_to_str(resolved)
668 resolved = self._names.type_names.get(gtname)
670 return self._typepair_to_str(resolved)
671 raise KeyError("Failed to resolve GType name: %r" % (gtname, ))
673 def ctype_of(self, obj):
674 if hasattr(obj, 'ctype'):
676 elif hasattr(obj, 'symbol'):
681 def resolve_param_type_full(self, ptype, names, **kwargs):
682 if isinstance(ptype, Node):
683 ptype.name = self.resolve_type_name_full(ptype.name,
684 self.ctype_of(ptype),
686 elif isinstance(ptype, basestring):
687 return self.resolve_type_name_full(ptype, ptype, names, **kwargs)
689 raise AssertionError("Unhandled param: %r" % (ptype, ))
692 def resolve_param_type(self, ptype):
694 return self.resolve_param_type_full(ptype, self._names)
698 def follow_aliases(self, type_name, names):
700 resolved = names.aliases.get(type_name)
702 (ns, alias) = resolved
703 type_name = alias.target
708 def iter_enums(self):
709 for node in self._namespace.nodes:
710 if isinstance(node, Enum):