cindex.py revision be51e43ba2c57b8032286af4e8713485b6dc78c3
1#===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===#
2#
3#                     The LLVM Compiler Infrastructure
4#
5# This file is distributed under the University of Illinois Open Source
6# License. See LICENSE.TXT for details.
7#
8#===------------------------------------------------------------------------===#
9
10r"""
11Clang Indexing Library Bindings
12===============================
13
14This module provides an interface to the Clang indexing library. It is a
15low-level interface to the indexing library which attempts to match the Clang
16API directly while also being "pythonic". Notable differences from the C API
17are:
18
19 * string results are returned as Python strings, not CXString objects.
20
21 * null cursors are translated to None.
22
23 * access to child cursors is done via iteration, not visitation.
24
25The major indexing objects are:
26
27  Index
28
29    The top-level object which manages some global library state.
30
31  TranslationUnit
32
33    High-level object encapsulating the AST for a single translation unit. These
34    can be loaded from .ast files or parsed on the fly.
35
36  Cursor
37
38    Generic object for representing a node in the AST.
39
40  SourceRange, SourceLocation, and File
41
42    Objects representing information about the input source.
43
44Most object information is exposed using properties, when the underlying API
45call is efficient.
46"""
47
48# TODO
49# ====
50#
51# o API support for invalid translation units. Currently we can't even get the
52#   diagnostics on failure because they refer to locations in an object that
53#   will have been invalidated.
54#
55# o fix memory management issues (currently client must hold on to index and
56#   translation unit, or risk crashes).
57#
58# o expose code completion APIs.
59#
60# o cleanup ctypes wrapping, would be nice to separate the ctypes details more
61#   clearly, and hide from the external interface (i.e., help(cindex)).
62#
63# o implement additional SourceLocation, SourceRange, and File methods.
64
65from ctypes import *
66import collections
67
68import clang.enumerations
69
70def get_cindex_library():
71    # FIXME: It's probably not the case that the library is actually found in
72    # this location. We need a better system of identifying and loading the
73    # CIndex library. It could be on path or elsewhere, or versioned, etc.
74    import platform
75    name = platform.system()
76    if name == 'Darwin':
77        return cdll.LoadLibrary('libclang.dylib')
78    elif name == 'Windows':
79        return cdll.LoadLibrary('libclang.dll')
80    else:
81        return cdll.LoadLibrary('libclang.so')
82
83# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
84# object. This is a problem, because it means that from_parameter will see an
85# integer and pass the wrong value on platforms where int != void*. Work around
86# this by marshalling object arguments as void**.
87c_object_p = POINTER(c_void_p)
88
89lib = get_cindex_library()
90callbacks = {}
91
92### Exception Classes ###
93
94class TranslationUnitLoadError(Exception):
95    """Represents an error that occurred when loading a TranslationUnit.
96
97    This is raised in the case where a TranslationUnit could not be
98    instantiated due to failure in the libclang library.
99
100    FIXME: Make libclang expose additional error information in this scenario.
101    """
102    pass
103
104class TranslationUnitSaveError(Exception):
105    """Represents an error that occurred when saving a TranslationUnit.
106
107    Each error has associated with it an enumerated value, accessible under
108    e.save_error. Consumers can compare the value with one of the ERROR_
109    constants in this class.
110    """
111
112    # Indicates that an unknown error occurred. This typically indicates that
113    # I/O failed during save.
114    ERROR_UNKNOWN = 1
115
116    # Indicates that errors during translation prevented saving. The errors
117    # should be available via the TranslationUnit's diagnostics.
118    ERROR_TRANSLATION_ERRORS = 2
119
120    # Indicates that the translation unit was somehow invalid.
121    ERROR_INVALID_TU = 3
122
123    def __init__(self, enumeration, message):
124        assert isinstance(enumeration, int)
125
126        if enumeration < 1 or enumeration > 3:
127            raise Exception("Encountered undefined TranslationUnit save error "
128                            "constant: %d. Please file a bug to have this "
129                            "value supported." % enumeration)
130
131        self.save_error = enumeration
132        Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
133
134### Structures and Utility Classes ###
135
136class _CXString(Structure):
137    """Helper for transforming CXString results."""
138
139    _fields_ = [("spelling", c_char_p), ("free", c_int)]
140
141    def __del__(self):
142        lib.clang_disposeString(self)
143
144    @staticmethod
145    def from_result(res, fn, args):
146        assert isinstance(res, _CXString)
147        return lib.clang_getCString(res)
148
149class SourceLocation(Structure):
150    """
151    A SourceLocation represents a particular location within a source file.
152    """
153    _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
154    _data = None
155
156    def _get_instantiation(self):
157        if self._data is None:
158            f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
159            lib.clang_getInstantiationLocation(self, byref(f), byref(l),
160                    byref(c), byref(o))
161            if f:
162                f = File(f)
163            else:
164                f = None
165            self._data = (f, int(l.value), int(c.value), int(o.value))
166        return self._data
167
168    @staticmethod
169    def from_position(tu, file, line, column):
170        """
171        Retrieve the source location associated with a given file/line/column in
172        a particular translation unit.
173        """
174        return lib.clang_getLocation(tu, file, line, column)
175
176    @staticmethod
177    def from_offset(tu, file, offset):
178        """Retrieve a SourceLocation from a given character offset.
179
180        tu -- TranslationUnit file belongs to
181        file -- File instance to obtain offset from
182        offset -- Integer character offset within file
183        """
184        return lib.clang_getLocationForOffset(tu, file, offset)
185
186    @property
187    def file(self):
188        """Get the file represented by this source location."""
189        return self._get_instantiation()[0]
190
191    @property
192    def line(self):
193        """Get the line represented by this source location."""
194        return self._get_instantiation()[1]
195
196    @property
197    def column(self):
198        """Get the column represented by this source location."""
199        return self._get_instantiation()[2]
200
201    @property
202    def offset(self):
203        """Get the file offset represented by this source location."""
204        return self._get_instantiation()[3]
205
206    def __eq__(self, other):
207        return lib.clang_equalLocations(self, other)
208
209    def __ne__(self, other):
210        return not self.__eq__(other)
211
212    def __repr__(self):
213        if self.file:
214            filename = self.file.name
215        else:
216            filename = None
217        return "<SourceLocation file %r, line %r, column %r>" % (
218            filename, self.line, self.column)
219
220class SourceRange(Structure):
221    """
222    A SourceRange describes a range of source locations within the source
223    code.
224    """
225    _fields_ = [
226        ("ptr_data", c_void_p * 2),
227        ("begin_int_data", c_uint),
228        ("end_int_data", c_uint)]
229
230    # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
231    # object.
232    @staticmethod
233    def from_locations(start, end):
234        return lib.clang_getRange(start, end)
235
236    @property
237    def start(self):
238        """
239        Return a SourceLocation representing the first character within a
240        source range.
241        """
242        return lib.clang_getRangeStart(self)
243
244    @property
245    def end(self):
246        """
247        Return a SourceLocation representing the last character within a
248        source range.
249        """
250        return lib.clang_getRangeEnd(self)
251
252    def __eq__(self, other):
253        return lib.clang_equalRanges(self, other)
254
255    def __ne__(self, other):
256        return not self.__eq__(other)
257
258    def __repr__(self):
259        return "<SourceRange start %r, end %r>" % (self.start, self.end)
260
261class Diagnostic(object):
262    """
263    A Diagnostic is a single instance of a Clang diagnostic. It includes the
264    diagnostic severity, the message, the location the diagnostic occurred, as
265    well as additional source ranges and associated fix-it hints.
266    """
267
268    Ignored = 0
269    Note    = 1
270    Warning = 2
271    Error   = 3
272    Fatal   = 4
273
274    def __init__(self, ptr):
275        self.ptr = ptr
276
277    def __del__(self):
278        lib.clang_disposeDiagnostic(self)
279
280    @property
281    def severity(self):
282        return lib.clang_getDiagnosticSeverity(self)
283
284    @property
285    def location(self):
286        return lib.clang_getDiagnosticLocation(self)
287
288    @property
289    def spelling(self):
290        return lib.clang_getDiagnosticSpelling(self)
291
292    @property
293    def ranges(self):
294        class RangeIterator:
295            def __init__(self, diag):
296                self.diag = diag
297
298            def __len__(self):
299                return int(lib.clang_getDiagnosticNumRanges(self.diag))
300
301            def __getitem__(self, key):
302                if (key >= len(self)):
303                    raise IndexError
304                return lib.clang_getDiagnosticRange(self.diag, key)
305
306        return RangeIterator(self)
307
308    @property
309    def fixits(self):
310        class FixItIterator:
311            def __init__(self, diag):
312                self.diag = diag
313
314            def __len__(self):
315                return int(lib.clang_getDiagnosticNumFixIts(self.diag))
316
317            def __getitem__(self, key):
318                range = SourceRange()
319                value = lib.clang_getDiagnosticFixIt(self.diag, key,
320                        byref(range))
321                if len(value) == 0:
322                    raise IndexError
323
324                return FixIt(range, value)
325
326        return FixItIterator(self)
327
328    @property
329    def category_number(self):
330        """The category number for this diagnostic."""
331        return lib.clang_getDiagnosticCategory(self)
332
333    @property
334    def category_name(self):
335        """The string name of the category for this diagnostic."""
336        return lib.clang_getDiagnosticCategoryName(self.category_number)
337
338    @property
339    def option(self):
340        """The command-line option that enables this diagnostic."""
341        return lib.clang_getDiagnosticOption(self, None)
342
343    @property
344    def disable_option(self):
345        """The command-line option that disables this diagnostic."""
346        disable = _CXString()
347        lib.clang_getDiagnosticOption(self, byref(disable))
348
349        return lib.clang_getCString(disable)
350
351    def __repr__(self):
352        return "<Diagnostic severity %r, location %r, spelling %r>" % (
353            self.severity, self.location, self.spelling)
354
355    def from_param(self):
356      return self.ptr
357
358class FixIt(object):
359    """
360    A FixIt represents a transformation to be applied to the source to
361    "fix-it". The fix-it shouldbe applied by replacing the given source range
362    with the given value.
363    """
364
365    def __init__(self, range, value):
366        self.range = range
367        self.value = value
368
369    def __repr__(self):
370        return "<FixIt range %r, value %r>" % (self.range, self.value)
371
372class TokenGroup(object):
373    """Helper class to facilitate token management.
374
375    Tokens are allocated from libclang in chunks. They must be disposed of as a
376    collective group.
377
378    One purpose of this class is for instances to represent groups of allocated
379    tokens. Each token in a group contains a reference back to an instance of
380    this class. When all tokens from a group are garbage collected, it allows
381    this class to be garbage collected. When this class is garbage collected,
382    it calls the libclang destructor which invalidates all tokens in the group.
383
384    You should not instantiate this class outside of this module.
385    """
386    def __init__(self, tu, memory, count):
387        self._tu = tu
388        self._memory = memory
389        self._count = count
390
391    def __del__(self):
392        lib.clang_disposeTokens(self._tu, self._memory, self._count)
393
394    @staticmethod
395    def get_tokens(tu, extent):
396        """Helper method to return all tokens in an extent.
397
398        This functionality is needed multiple places in this module. We define
399        it here because it seems like a logical place.
400        """
401        tokens_memory = POINTER(Token)()
402        tokens_count = c_uint()
403
404        lib.clang_tokenize(tu, extent, byref(tokens_memory),
405                byref(tokens_count))
406
407        count = int(tokens_count.value)
408
409        # If we get no tokens, no memory was allocated. Be sure not to return
410        # anything and potentially call a destructor on nothing.
411        if count < 1:
412            return
413
414        tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
415
416        token_group = TokenGroup(tu, tokens_memory, tokens_count)
417
418        for i in xrange(0, count):
419            token = Token()
420            token.int_data = tokens_array[i].int_data
421            token.ptr_data = tokens_array[i].ptr_data
422            token._tu = tu
423            token._group = token_group
424
425            yield token
426
427class TokenKind(object):
428    """Describes a specific type of a Token."""
429
430    _value_map = {} # int -> TokenKind
431
432    def __init__(self, value, name):
433        """Create a new TokenKind instance from a numeric value and a name."""
434        self.value = value
435        self.name = name
436
437    def __repr__(self):
438        return 'TokenKind.%s' % (self.name,)
439
440    @staticmethod
441    def from_value(value):
442        """Obtain a registered TokenKind instance from its value."""
443        result = TokenKind._value_map.get(value, None)
444
445        if result is None:
446            raise ValueError('Unknown TokenKind: %d' % value)
447
448        return result
449
450    @staticmethod
451    def register(value, name):
452        """Register a new TokenKind enumeration.
453
454        This should only be called at module load time by code within this
455        package.
456        """
457        if value in TokenKind._value_map:
458            raise ValueError('TokenKind already registered: %d' % value)
459
460        kind = TokenKind(value, name)
461        TokenKind._value_map[value] = kind
462        setattr(TokenKind, name, kind)
463
464### Cursor Kinds ###
465
466class CursorKind(object):
467    """
468    A CursorKind describes the kind of entity that a cursor points to.
469    """
470
471    # The unique kind objects, indexed by id.
472    _kinds = []
473    _name_map = None
474
475    def __init__(self, value):
476        if value >= len(CursorKind._kinds):
477            CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1)
478        if CursorKind._kinds[value] is not None:
479            raise ValueError,'CursorKind already loaded'
480        self.value = value
481        CursorKind._kinds[value] = self
482        CursorKind._name_map = None
483
484    def from_param(self):
485        return self.value
486
487    @property
488    def name(self):
489        """Get the enumeration name of this cursor kind."""
490        if self._name_map is None:
491            self._name_map = {}
492            for key,value in CursorKind.__dict__.items():
493                if isinstance(value,CursorKind):
494                    self._name_map[value] = key
495        return self._name_map[self]
496
497    @staticmethod
498    def from_id(id):
499        if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None:
500            raise ValueError,'Unknown cursor kind'
501        return CursorKind._kinds[id]
502
503    @staticmethod
504    def get_all_kinds():
505        """Return all CursorKind enumeration instances."""
506        return filter(None, CursorKind._kinds)
507
508    def is_declaration(self):
509        """Test if this is a declaration kind."""
510        return lib.clang_isDeclaration(self)
511
512    def is_reference(self):
513        """Test if this is a reference kind."""
514        return lib.clang_isReference(self)
515
516    def is_expression(self):
517        """Test if this is an expression kind."""
518        return lib.clang_isExpression(self)
519
520    def is_statement(self):
521        """Test if this is a statement kind."""
522        return lib.clang_isStatement(self)
523
524    def is_attribute(self):
525        """Test if this is an attribute kind."""
526        return lib.clang_isAttribute(self)
527
528    def is_invalid(self):
529        """Test if this is an invalid kind."""
530        return lib.clang_isInvalid(self)
531
532    def is_translation_unit(self):
533        """Test if this is a translation unit kind."""
534        return lib.clang_isTranslationUnit(self)
535
536    def is_preprocessing(self):
537        """Test if this is a preprocessing kind."""
538        return lib.clang_isPreprocessing(self)
539
540    def is_unexposed(self):
541        """Test if this is an unexposed kind."""
542        return lib.clang_isUnexposed(self)
543
544    def __repr__(self):
545        return 'CursorKind.%s' % (self.name,)
546
547# FIXME: Is there a nicer way to expose this enumeration? We could potentially
548# represent the nested structure, or even build a class hierarchy. The main
549# things we want for sure are (a) simple external access to kinds, (b) a place
550# to hang a description and name, (c) easy to keep in sync with Index.h.
551
552###
553# Declaration Kinds
554
555# A declaration whose specific kind is not exposed via this interface.
556#
557# Unexposed declarations have the same operations as any other kind of
558# declaration; one can extract their location information, spelling, find their
559# definitions, etc. However, the specific kind of the declaration is not
560# reported.
561CursorKind.UNEXPOSED_DECL = CursorKind(1)
562
563# A C or C++ struct.
564CursorKind.STRUCT_DECL = CursorKind(2)
565
566# A C or C++ union.
567CursorKind.UNION_DECL = CursorKind(3)
568
569# A C++ class.
570CursorKind.CLASS_DECL = CursorKind(4)
571
572# An enumeration.
573CursorKind.ENUM_DECL = CursorKind(5)
574
575# A field (in C) or non-static data member (in C++) in a struct, union, or C++
576# class.
577CursorKind.FIELD_DECL = CursorKind(6)
578
579# An enumerator constant.
580CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
581
582# A function.
583CursorKind.FUNCTION_DECL = CursorKind(8)
584
585# A variable.
586CursorKind.VAR_DECL = CursorKind(9)
587
588# A function or method parameter.
589CursorKind.PARM_DECL = CursorKind(10)
590
591# An Objective-C @interface.
592CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
593
594# An Objective-C @interface for a category.
595CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
596
597# An Objective-C @protocol declaration.
598CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
599
600# An Objective-C @property declaration.
601CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
602
603# An Objective-C instance variable.
604CursorKind.OBJC_IVAR_DECL = CursorKind(15)
605
606# An Objective-C instance method.
607CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
608
609# An Objective-C class method.
610CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
611
612# An Objective-C @implementation.
613CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
614
615# An Objective-C @implementation for a category.
616CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
617
618# A typedef.
619CursorKind.TYPEDEF_DECL = CursorKind(20)
620
621# A C++ class method.
622CursorKind.CXX_METHOD = CursorKind(21)
623
624# A C++ namespace.
625CursorKind.NAMESPACE = CursorKind(22)
626
627# A linkage specification, e.g. 'extern "C"'.
628CursorKind.LINKAGE_SPEC = CursorKind(23)
629
630# A C++ constructor.
631CursorKind.CONSTRUCTOR = CursorKind(24)
632
633# A C++ destructor.
634CursorKind.DESTRUCTOR = CursorKind(25)
635
636# A C++ conversion function.
637CursorKind.CONVERSION_FUNCTION = CursorKind(26)
638
639# A C++ template type parameter
640CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
641
642# A C++ non-type template paramater.
643CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
644
645# A C++ template template parameter.
646CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29)
647
648# A C++ function template.
649CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
650
651# A C++ class template.
652CursorKind.CLASS_TEMPLATE = CursorKind(31)
653
654# A C++ class template partial specialization.
655CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
656
657# A C++ namespace alias declaration.
658CursorKind.NAMESPACE_ALIAS = CursorKind(33)
659
660# A C++ using directive
661CursorKind.USING_DIRECTIVE = CursorKind(34)
662
663# A C++ using declaration
664CursorKind.USING_DECLARATION = CursorKind(35)
665
666# A Type alias decl.
667CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
668
669# A Objective-C synthesize decl
670CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
671
672# A Objective-C dynamic decl
673CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
674
675# A C++ access specifier decl.
676CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
677
678
679###
680# Reference Kinds
681
682CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
683CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
684CursorKind.OBJC_CLASS_REF = CursorKind(42)
685
686# A reference to a type declaration.
687#
688# A type reference occurs anywhere where a type is named but not
689# declared. For example, given:
690#   typedef unsigned size_type;
691#   size_type size;
692#
693# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
694# while the type of the variable "size" is referenced. The cursor
695# referenced by the type of size is the typedef for size_type.
696CursorKind.TYPE_REF = CursorKind(43)
697CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
698
699# A reference to a class template, function template, template
700# template parameter, or class template partial specialization.
701CursorKind.TEMPLATE_REF = CursorKind(45)
702
703# A reference to a namespace or namepsace alias.
704CursorKind.NAMESPACE_REF = CursorKind(46)
705
706# A reference to a member of a struct, union, or class that occurs in
707# some non-expression context, e.g., a designated initializer.
708CursorKind.MEMBER_REF = CursorKind(47)
709
710# A reference to a labeled statement.
711CursorKind.LABEL_REF = CursorKind(48)
712
713# A reference toa a set of overloaded functions or function templates
714# that has not yet been resolved to a specific function or function template.
715CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
716
717###
718# Invalid/Error Kinds
719
720CursorKind.INVALID_FILE = CursorKind(70)
721CursorKind.NO_DECL_FOUND = CursorKind(71)
722CursorKind.NOT_IMPLEMENTED = CursorKind(72)
723CursorKind.INVALID_CODE = CursorKind(73)
724
725###
726# Expression Kinds
727
728# An expression whose specific kind is not exposed via this interface.
729#
730# Unexposed expressions have the same operations as any other kind of
731# expression; one can extract their location information, spelling, children,
732# etc. However, the specific kind of the expression is not reported.
733CursorKind.UNEXPOSED_EXPR = CursorKind(100)
734
735# An expression that refers to some value declaration, such as a function,
736# varible, or enumerator.
737CursorKind.DECL_REF_EXPR = CursorKind(101)
738
739# An expression that refers to a member of a struct, union, class, Objective-C
740# class, etc.
741CursorKind.MEMBER_REF_EXPR = CursorKind(102)
742
743# An expression that calls a function.
744CursorKind.CALL_EXPR = CursorKind(103)
745
746# An expression that sends a message to an Objective-C object or class.
747CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
748
749# An expression that represents a block literal.
750CursorKind.BLOCK_EXPR = CursorKind(105)
751
752# An integer literal.
753CursorKind.INTEGER_LITERAL = CursorKind(106)
754
755# A floating point number literal.
756CursorKind.FLOATING_LITERAL = CursorKind(107)
757
758# An imaginary number literal.
759CursorKind.IMAGINARY_LITERAL = CursorKind(108)
760
761# A string literal.
762CursorKind.STRING_LITERAL = CursorKind(109)
763
764# A character literal.
765CursorKind.CHARACTER_LITERAL = CursorKind(110)
766
767# A parenthesized expression, e.g. "(1)".
768#
769# This AST node is only formed if full location information is requested.
770CursorKind.PAREN_EXPR = CursorKind(111)
771
772# This represents the unary-expression's (except sizeof and
773# alignof).
774CursorKind.UNARY_OPERATOR = CursorKind(112)
775
776# [C99 6.5.2.1] Array Subscripting.
777CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
778
779# A builtin binary operation expression such as "x + y" or
780# "x <= y".
781CursorKind.BINARY_OPERATOR = CursorKind(114)
782
783# Compound assignment such as "+=".
784CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
785
786# The ?: ternary operator.
787CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
788
789# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
790# (C++ [expr.cast]), which uses the syntax (Type)expr.
791#
792# For example: (int)f.
793CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
794
795# [C99 6.5.2.5]
796CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
797
798# Describes an C or C++ initializer list.
799CursorKind.INIT_LIST_EXPR = CursorKind(119)
800
801# The GNU address of label extension, representing &&label.
802CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
803
804# This is the GNU Statement Expression extension: ({int X=4; X;})
805CursorKind.StmtExpr = CursorKind(121)
806
807# Represents a C11 generic selection.
808CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
809
810# Implements the GNU __null extension, which is a name for a null
811# pointer constant that has integral type (e.g., int or long) and is the same
812# size and alignment as a pointer.
813#
814# The __null extension is typically only used by system headers, which define
815# NULL as __null in C++ rather than using 0 (which is an integer that may not
816# match the size of a pointer).
817CursorKind.GNU_NULL_EXPR = CursorKind(123)
818
819# C++'s static_cast<> expression.
820CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
821
822# C++'s dynamic_cast<> expression.
823CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
824
825# C++'s reinterpret_cast<> expression.
826CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
827
828# C++'s const_cast<> expression.
829CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
830
831# Represents an explicit C++ type conversion that uses "functional"
832# notion (C++ [expr.type.conv]).
833#
834# Example:
835# \code
836#   x = int(0.5);
837# \endcode
838CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
839
840# A C++ typeid expression (C++ [expr.typeid]).
841CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
842
843# [C++ 2.13.5] C++ Boolean Literal.
844CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
845
846# [C++0x 2.14.7] C++ Pointer Literal.
847CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
848
849# Represents the "this" expression in C++
850CursorKind.CXX_THIS_EXPR = CursorKind(132)
851
852# [C++ 15] C++ Throw Expression.
853#
854# This handles 'throw' and 'throw' assignment-expression. When
855# assignment-expression isn't present, Op will be null.
856CursorKind.CXX_THROW_EXPR = CursorKind(133)
857
858# A new expression for memory allocation and constructor calls, e.g:
859# "new CXXNewExpr(foo)".
860CursorKind.CXX_NEW_EXPR = CursorKind(134)
861
862# A delete expression for memory deallocation and destructor calls,
863# e.g. "delete[] pArray".
864CursorKind.CXX_DELETE_EXPR = CursorKind(135)
865
866# Represents a unary expression.
867CursorKind.CXX_UNARY_EXPR = CursorKind(136)
868
869# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
870CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
871
872# ObjCEncodeExpr, used for in Objective-C.
873CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
874
875# ObjCSelectorExpr used for in Objective-C.
876CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
877
878# Objective-C's protocol expression.
879CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
880
881# An Objective-C "bridged" cast expression, which casts between
882# Objective-C pointers and C pointers, transferring ownership in the process.
883#
884# \code
885#   NSString *str = (__bridge_transfer NSString *)CFCreateString();
886# \endcode
887CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
888
889# Represents a C++0x pack expansion that produces a sequence of
890# expressions.
891#
892# A pack expansion expression contains a pattern (which itself is an
893# expression) followed by an ellipsis. For example:
894CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
895
896# Represents an expression that computes the length of a parameter
897# pack.
898CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
899
900# A statement whose specific kind is not exposed via this interface.
901#
902# Unexposed statements have the same operations as any other kind of statement;
903# one can extract their location information, spelling, children, etc. However,
904# the specific kind of the statement is not reported.
905CursorKind.UNEXPOSED_STMT = CursorKind(200)
906
907# A labelled statement in a function.
908CursorKind.LABEL_STMT = CursorKind(201)
909
910# A compound statement
911CursorKind.COMPOUND_STMT = CursorKind(202)
912
913# A case statement.
914CursorKind.CASE_STMT = CursorKind(203)
915
916# A default statement.
917CursorKind.DEFAULT_STMT = CursorKind(204)
918
919# An if statement.
920CursorKind.IF_STMT = CursorKind(205)
921
922# A switch statement.
923CursorKind.SWITCH_STMT = CursorKind(206)
924
925# A while statement.
926CursorKind.WHILE_STMT = CursorKind(207)
927
928# A do statement.
929CursorKind.DO_STMT = CursorKind(208)
930
931# A for statement.
932CursorKind.FOR_STMT = CursorKind(209)
933
934# A goto statement.
935CursorKind.GOTO_STMT = CursorKind(210)
936
937# An indirect goto statement.
938CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
939
940# A continue statement.
941CursorKind.CONTINUE_STMT = CursorKind(212)
942
943# A break statement.
944CursorKind.BREAK_STMT = CursorKind(213)
945
946# A return statement.
947CursorKind.RETURN_STMT = CursorKind(214)
948
949# A GNU-style inline assembler statement.
950CursorKind.ASM_STMT = CursorKind(215)
951
952# Objective-C's overall @try-@catch-@finally statement.
953CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
954
955# Objective-C's @catch statement.
956CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
957
958# Objective-C's @finally statement.
959CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
960
961# Objective-C's @throw statement.
962CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
963
964# Objective-C's @synchronized statement.
965CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
966
967# Objective-C's autorealease pool statement.
968CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
969
970# Objective-C's for collection statement.
971CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
972
973# C++'s catch statement.
974CursorKind.CXX_CATCH_STMT = CursorKind(223)
975
976# C++'s try statement.
977CursorKind.CXX_TRY_STMT = CursorKind(224)
978
979# C++'s for (* : *) statement.
980CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
981
982# Windows Structured Exception Handling's try statement.
983CursorKind.SEH_TRY_STMT = CursorKind(226)
984
985# Windows Structured Exception Handling's except statement.
986CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
987
988# Windows Structured Exception Handling's finally statement.
989CursorKind.SEH_FINALLY_STMT = CursorKind(228)
990
991# The null statement.
992CursorKind.NULL_STMT = CursorKind(230)
993
994# Adaptor class for mixing declarations with statements and expressions.
995CursorKind.DECL_STMT = CursorKind(231)
996
997###
998# Other Kinds
999
1000# Cursor that represents the translation unit itself.
1001#
1002# The translation unit cursor exists primarily to act as the root cursor for
1003# traversing the contents of a translation unit.
1004CursorKind.TRANSLATION_UNIT = CursorKind(300)
1005
1006###
1007# Attributes
1008
1009# An attribute whoe specific kind is note exposed via this interface
1010CursorKind.UNEXPOSED_ATTR = CursorKind(400)
1011
1012CursorKind.IB_ACTION_ATTR = CursorKind(401)
1013CursorKind.IB_OUTLET_ATTR = CursorKind(402)
1014CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
1015
1016CursorKind.CXX_FINAL_ATTR = CursorKind(404)
1017CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
1018CursorKind.ANNOTATE_ATTR = CursorKind(406)
1019CursorKind.ASM_LABEL_ATTR = CursorKind(407)
1020
1021###
1022# Preprocessing
1023CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
1024CursorKind.MACRO_DEFINITION = CursorKind(501)
1025CursorKind.MACRO_INSTANTIATION = CursorKind(502)
1026CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
1027
1028### Cursors ###
1029
1030class Cursor(Structure):
1031    """
1032    The Cursor class represents a reference to an element within the AST. It
1033    acts as a kind of iterator.
1034    """
1035    _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
1036
1037    @staticmethod
1038    def from_location(tu, location):
1039        # We store a reference to the TU in the instance so the TU won't get
1040        # collected before the cursor.
1041        cursor = lib.clang_getCursor(tu, location)
1042        cursor._tu = tu
1043
1044        return cursor
1045
1046    def __eq__(self, other):
1047        return lib.clang_equalCursors(self, other)
1048
1049    def __ne__(self, other):
1050        return not self.__eq__(other)
1051
1052    def is_definition(self):
1053        """
1054        Returns true if the declaration pointed at by the cursor is also a
1055        definition of that entity.
1056        """
1057        return lib.clang_isCursorDefinition(self)
1058
1059    def is_static_method(self):
1060        """Returns True if the cursor refers to a C++ member function or member
1061        function template that is declared 'static'.
1062        """
1063        return lib.clang_CXXMethod_isStatic(self)
1064
1065    def get_definition(self):
1066        """
1067        If the cursor is a reference to a declaration or a declaration of
1068        some entity, return a cursor that points to the definition of that
1069        entity.
1070        """
1071        # TODO: Should probably check that this is either a reference or
1072        # declaration prior to issuing the lookup.
1073        return lib.clang_getCursorDefinition(self)
1074
1075    def get_usr(self):
1076        """Return the Unified Symbol Resultion (USR) for the entity referenced
1077        by the given cursor (or None).
1078
1079        A Unified Symbol Resolution (USR) is a string that identifies a
1080        particular entity (function, class, variable, etc.) within a
1081        program. USRs can be compared across translation units to determine,
1082        e.g., when references in one translation refer to an entity defined in
1083        another translation unit."""
1084        return lib.clang_getCursorUSR(self)
1085
1086    @property
1087    def kind(self):
1088        """Return the kind of this cursor."""
1089        return CursorKind.from_id(self._kind_id)
1090
1091    @property
1092    def spelling(self):
1093        """Return the spelling of the entity pointed at by the cursor."""
1094        if not self.kind.is_declaration():
1095            # FIXME: clang_getCursorSpelling should be fixed to not assert on
1096            # this, for consistency with clang_getCursorUSR.
1097            return None
1098        if not hasattr(self, '_spelling'):
1099            self._spelling = lib.clang_getCursorSpelling(self)
1100
1101        return self._spelling
1102
1103    @property
1104    def displayname(self):
1105        """
1106        Return the display name for the entity referenced by this cursor.
1107
1108        The display name contains extra information that helps identify the cursor,
1109        such as the parameters of a function or template or the arguments of a
1110        class template specialization.
1111        """
1112        if not hasattr(self, '_displayname'):
1113            self._displayname = lib.clang_getCursorDisplayName(self)
1114
1115        return self._displayname
1116
1117    @property
1118    def location(self):
1119        """
1120        Return the source location (the starting character) of the entity
1121        pointed at by the cursor.
1122        """
1123        if not hasattr(self, '_loc'):
1124            self._loc = lib.clang_getCursorLocation(self)
1125
1126        return self._loc
1127
1128    @property
1129    def extent(self):
1130        """
1131        Return the source range (the range of text) occupied by the entity
1132        pointed at by the cursor.
1133        """
1134        if not hasattr(self, '_extent'):
1135            self._extent = lib.clang_getCursorExtent(self)
1136
1137        return self._extent
1138
1139    @property
1140    def type(self):
1141        """
1142        Retrieve the Type (if any) of the entity pointed at by the cursor.
1143        """
1144        if not hasattr(self, '_type'):
1145            self._type = lib.clang_getCursorType(self)
1146
1147        return self._type
1148
1149    @property
1150    def canonical(self):
1151        """Return the canonical Cursor corresponding to this Cursor.
1152
1153        The canonical cursor is the cursor which is representative for the
1154        underlying entity. For example, if you have multiple forward
1155        declarations for the same class, the canonical cursor for the forward
1156        declarations will be identical.
1157        """
1158        if not hasattr(self, '_canonical'):
1159            self._canonical = lib.clang_getCanonicalCursor(self)
1160
1161        return self._canonical
1162
1163    @property
1164    def result_type(self):
1165        """Retrieve the Type of the result for this Cursor."""
1166        if not hasattr(self, '_result_type'):
1167            self._result_type = lib.clang_getResultType(self.type)
1168
1169        return self._result_type
1170
1171    @property
1172    def underlying_typedef_type(self):
1173        """Return the underlying type of a typedef declaration.
1174
1175        Returns a Type for the typedef this cursor is a declaration for. If
1176        the current cursor is not a typedef, this raises.
1177        """
1178        if not hasattr(self, '_underlying_type'):
1179            assert self.kind.is_declaration()
1180            self._underlying_type = lib.clang_getTypedefDeclUnderlyingType(self)
1181
1182        return self._underlying_type
1183
1184    @property
1185    def enum_type(self):
1186        """Return the integer type of an enum declaration.
1187
1188        Returns a Type corresponding to an integer. If the cursor is not for an
1189        enum, this raises.
1190        """
1191        if not hasattr(self, '_enum_type'):
1192            assert self.kind == CursorKind.ENUM_DECL
1193            self._enum_type = lib.clang_getEnumDeclIntegerType(self)
1194
1195        return self._enum_type
1196
1197    @property
1198    def enum_value(self):
1199        """Return the value of an enum constant."""
1200        if not hasattr(self, '_enum_value'):
1201            assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1202            # Figure out the underlying type of the enum to know if it
1203            # is a signed or unsigned quantity.
1204            underlying_type = self.type
1205            if underlying_type.kind == TypeKind.ENUM:
1206                underlying_type = underlying_type.get_declaration().enum_type
1207            if underlying_type.kind in (TypeKind.CHAR_U,
1208                                        TypeKind.UCHAR,
1209                                        TypeKind.CHAR16,
1210                                        TypeKind.CHAR32,
1211                                        TypeKind.USHORT,
1212                                        TypeKind.UINT,
1213                                        TypeKind.ULONG,
1214                                        TypeKind.ULONGLONG,
1215                                        TypeKind.UINT128):
1216                self._enum_value = lib.clang_getEnumConstantDeclUnsignedValue(self)
1217            else:
1218                self._enum_value = lib.clang_getEnumConstantDeclValue(self)
1219        return self._enum_value
1220
1221    @property
1222    def objc_type_encoding(self):
1223        """Return the Objective-C type encoding as a str."""
1224        if not hasattr(self, '_objc_type_encoding'):
1225            self._objc_type_encoding = lib.clang_getDeclObjCTypeEncoding(self)
1226
1227        return self._objc_type_encoding
1228
1229    @property
1230    def hash(self):
1231        """Returns a hash of the cursor as an int."""
1232        if not hasattr(self, '_hash'):
1233            self._hash = lib.clang_hashCursor(self)
1234
1235        return self._hash
1236
1237    @property
1238    def semantic_parent(self):
1239        """Return the semantic parent for this cursor."""
1240        if not hasattr(self, '_semantic_parent'):
1241            self._semantic_parent = lib.clang_getCursorSemanticParent(self)
1242
1243        return self._semantic_parent
1244
1245    @property
1246    def lexical_parent(self):
1247        """Return the lexical parent for this cursor."""
1248        if not hasattr(self, '_lexical_parent'):
1249            self._lexical_parent = lib.clang_getCursorLexicalParent(self)
1250
1251        return self._lexical_parent
1252
1253    @property
1254    def translation_unit(self):
1255        """Returns the TranslationUnit to which this Cursor belongs."""
1256        # If this triggers an AttributeError, the instance was not properly
1257        # created.
1258        return self._tu
1259
1260    def get_children(self):
1261        """Return an iterator for accessing the children of this cursor."""
1262
1263        # FIXME: Expose iteration from CIndex, PR6125.
1264        def visitor(child, parent, children):
1265            # FIXME: Document this assertion in API.
1266            # FIXME: There should just be an isNull method.
1267            assert child != lib.clang_getNullCursor()
1268
1269            # Create reference to TU so it isn't GC'd before Cursor.
1270            child._tu = self._tu
1271            children.append(child)
1272            return 1 # continue
1273        children = []
1274        lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
1275            children)
1276        return iter(children)
1277
1278    def get_tokens(self):
1279        """Obtain Token instances formulating that compose this Cursor.
1280
1281        This is a generator for Token instances. It returns all tokens which
1282        occupy the extent this cursor occupies.
1283        """
1284        return TokenGroup.get_tokens(self._tu, self.extent)
1285
1286    @staticmethod
1287    def from_result(res, fn, args):
1288        assert isinstance(res, Cursor)
1289        # FIXME: There should just be an isNull method.
1290        if res == lib.clang_getNullCursor():
1291            return None
1292
1293        # Store a reference to the TU in the Python object so it won't get GC'd
1294        # before the Cursor.
1295        tu = None
1296        for arg in args:
1297            if isinstance(arg, TranslationUnit):
1298                tu = arg
1299                break
1300
1301            if hasattr(arg, 'translation_unit'):
1302                tu = arg.translation_unit
1303                break
1304
1305        assert tu is not None
1306
1307        res._tu = tu
1308        return res
1309
1310    @staticmethod
1311    def from_cursor_result(res, fn, args):
1312        assert isinstance(res, Cursor)
1313        if res == lib.clang_getNullCursor():
1314            return None
1315
1316        res._tu = args[0]._tu
1317        return res
1318
1319### Type Kinds ###
1320
1321class TypeKind(object):
1322    """
1323    Describes the kind of type.
1324    """
1325
1326    # The unique kind objects, indexed by id.
1327    _kinds = []
1328    _name_map = None
1329
1330    def __init__(self, value):
1331        if value >= len(TypeKind._kinds):
1332            TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
1333        if TypeKind._kinds[value] is not None:
1334            raise ValueError,'TypeKind already loaded'
1335        self.value = value
1336        TypeKind._kinds[value] = self
1337        TypeKind._name_map = None
1338
1339    def from_param(self):
1340        return self.value
1341
1342    @property
1343    def name(self):
1344        """Get the enumeration name of this cursor kind."""
1345        if self._name_map is None:
1346            self._name_map = {}
1347            for key,value in TypeKind.__dict__.items():
1348                if isinstance(value,TypeKind):
1349                    self._name_map[value] = key
1350        return self._name_map[self]
1351
1352    @property
1353    def spelling(self):
1354        """Retrieve the spelling of this TypeKind."""
1355        return lib.clang_getTypeKindSpelling(self.value)
1356
1357    @staticmethod
1358    def from_id(id):
1359        if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
1360            raise ValueError,'Unknown type kind %d' % id
1361        return TypeKind._kinds[id]
1362
1363    def __repr__(self):
1364        return 'TypeKind.%s' % (self.name,)
1365
1366TypeKind.INVALID = TypeKind(0)
1367TypeKind.UNEXPOSED = TypeKind(1)
1368TypeKind.VOID = TypeKind(2)
1369TypeKind.BOOL = TypeKind(3)
1370TypeKind.CHAR_U = TypeKind(4)
1371TypeKind.UCHAR = TypeKind(5)
1372TypeKind.CHAR16 = TypeKind(6)
1373TypeKind.CHAR32 = TypeKind(7)
1374TypeKind.USHORT = TypeKind(8)
1375TypeKind.UINT = TypeKind(9)
1376TypeKind.ULONG = TypeKind(10)
1377TypeKind.ULONGLONG = TypeKind(11)
1378TypeKind.UINT128 = TypeKind(12)
1379TypeKind.CHAR_S = TypeKind(13)
1380TypeKind.SCHAR = TypeKind(14)
1381TypeKind.WCHAR = TypeKind(15)
1382TypeKind.SHORT = TypeKind(16)
1383TypeKind.INT = TypeKind(17)
1384TypeKind.LONG = TypeKind(18)
1385TypeKind.LONGLONG = TypeKind(19)
1386TypeKind.INT128 = TypeKind(20)
1387TypeKind.FLOAT = TypeKind(21)
1388TypeKind.DOUBLE = TypeKind(22)
1389TypeKind.LONGDOUBLE = TypeKind(23)
1390TypeKind.NULLPTR = TypeKind(24)
1391TypeKind.OVERLOAD = TypeKind(25)
1392TypeKind.DEPENDENT = TypeKind(26)
1393TypeKind.OBJCID = TypeKind(27)
1394TypeKind.OBJCCLASS = TypeKind(28)
1395TypeKind.OBJCSEL = TypeKind(29)
1396TypeKind.COMPLEX = TypeKind(100)
1397TypeKind.POINTER = TypeKind(101)
1398TypeKind.BLOCKPOINTER = TypeKind(102)
1399TypeKind.LVALUEREFERENCE = TypeKind(103)
1400TypeKind.RVALUEREFERENCE = TypeKind(104)
1401TypeKind.RECORD = TypeKind(105)
1402TypeKind.ENUM = TypeKind(106)
1403TypeKind.TYPEDEF = TypeKind(107)
1404TypeKind.OBJCINTERFACE = TypeKind(108)
1405TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1406TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1407TypeKind.FUNCTIONPROTO = TypeKind(111)
1408TypeKind.CONSTANTARRAY = TypeKind(112)
1409TypeKind.VECTOR = TypeKind(113)
1410
1411class Type(Structure):
1412    """
1413    The type of an element in the abstract syntax tree.
1414    """
1415    _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1416
1417    @property
1418    def kind(self):
1419        """Return the kind of this type."""
1420        return TypeKind.from_id(self._kind_id)
1421
1422    def argument_types(self):
1423        """Retrieve a container for the non-variadic arguments for this type.
1424
1425        The returned object is iterable and indexable. Each item in the
1426        container is a Type instance.
1427        """
1428        class ArgumentsIterator(collections.Sequence):
1429            def __init__(self, parent):
1430                self.parent = parent
1431                self.length = None
1432
1433            def __len__(self):
1434                if self.length is None:
1435                    self.length = lib.clang_getNumArgTypes(self.parent)
1436
1437                return self.length
1438
1439            def __getitem__(self, key):
1440                # FIXME Support slice objects.
1441                if not isinstance(key, int):
1442                    raise TypeError("Must supply a non-negative int.")
1443
1444                if key < 0:
1445                    raise IndexError("Only non-negative indexes are accepted.")
1446
1447                if key >= len(self):
1448                    raise IndexError("Index greater than container length: "
1449                                     "%d > %d" % ( key, len(self) ))
1450
1451                result = lib.clang_getArgType(self.parent, key)
1452                if result.kind == TypeKind.INVALID:
1453                    raise IndexError("Argument could not be retrieved.")
1454
1455                return result
1456
1457        assert self.kind == TypeKind.FUNCTIONPROTO
1458        return ArgumentsIterator(self)
1459
1460    @property
1461    def element_type(self):
1462        """Retrieve the Type of elements within this Type.
1463
1464        If accessed on a type that is not an array, complex, or vector type, an
1465        exception will be raised.
1466        """
1467        result = lib.clang_getElementType(self)
1468        if result.kind == TypeKind.INVALID:
1469            raise Exception('Element type not available on this type.')
1470
1471        return result
1472
1473    @property
1474    def element_count(self):
1475        """Retrieve the number of elements in this type.
1476
1477        Returns an int.
1478
1479        If the Type is not an array or vector, this raises.
1480        """
1481        result = lib.clang_getNumElements(self)
1482        if result < 0:
1483            raise Exception('Type does not have elements.')
1484
1485        return result
1486
1487    @property
1488    def translation_unit(self):
1489        """The TranslationUnit to which this Type is associated."""
1490        # If this triggers an AttributeError, the instance was not properly
1491        # instantiated.
1492        return self._tu
1493
1494    @staticmethod
1495    def from_result(res, fn, args):
1496        assert isinstance(res, Type)
1497
1498        tu = None
1499        for arg in args:
1500            if hasattr(arg, 'translation_unit'):
1501                tu = arg.translation_unit
1502                break
1503
1504        assert tu is not None
1505        res._tu = tu
1506
1507        return res
1508
1509    def get_canonical(self):
1510        """
1511        Return the canonical type for a Type.
1512
1513        Clang's type system explicitly models typedefs and all the
1514        ways a specific type can be represented.  The canonical type
1515        is the underlying type with all the "sugar" removed.  For
1516        example, if 'T' is a typedef for 'int', the canonical type for
1517        'T' would be 'int'.
1518        """
1519        return lib.clang_getCanonicalType(self)
1520
1521    def is_const_qualified(self):
1522        """Determine whether a Type has the "const" qualifier set.
1523
1524        This does not look through typedefs that may have added "const"
1525        at a different level.
1526        """
1527        return lib.clang_isConstQualifiedType(self)
1528
1529    def is_volatile_qualified(self):
1530        """Determine whether a Type has the "volatile" qualifier set.
1531
1532        This does not look through typedefs that may have added "volatile"
1533        at a different level.
1534        """
1535        return lib.clang_isVolatileQualifiedType(self)
1536
1537    def is_restrict_qualified(self):
1538        """Determine whether a Type has the "restrict" qualifier set.
1539
1540        This does not look through typedefs that may have added "restrict" at
1541        a different level.
1542        """
1543        return lib.clang_isRestrictQualifiedType(self)
1544
1545    def is_function_variadic(self):
1546        """Determine whether this function Type is a variadic function type."""
1547        assert self.kind == TypeKind.FUNCTIONPROTO
1548
1549        return lib.clang_isFunctionTypeVariadic(self)
1550
1551    def is_pod(self):
1552        """Determine whether this Type represents plain old data (POD)."""
1553        return lib.clang_isPODType(self)
1554
1555    def get_pointee(self):
1556        """
1557        For pointer types, returns the type of the pointee.
1558        """
1559        return lib.clang_getPointeeType(self)
1560
1561    def get_declaration(self):
1562        """
1563        Return the cursor for the declaration of the given type.
1564        """
1565        return lib.clang_getTypeDeclaration(self)
1566
1567    def get_result(self):
1568        """
1569        Retrieve the result type associated with a function type.
1570        """
1571        return lib.clang_getResultType(self)
1572
1573    def get_array_element_type(self):
1574        """
1575        Retrieve the type of the elements of the array type.
1576        """
1577        return lib.clang_getArrayElementType(self)
1578
1579    def get_array_size(self):
1580        """
1581        Retrieve the size of the constant array.
1582        """
1583        return lib.clang_getArraySize(self)
1584
1585    def __eq__(self, other):
1586        if type(other) != type(self):
1587            return False
1588
1589        return lib.clang_equalTypes(self, other)
1590
1591    def __ne__(self, other):
1592        return not self.__eq__(other)
1593
1594## CIndex Objects ##
1595
1596# CIndex objects (derived from ClangObject) are essentially lightweight
1597# wrappers attached to some underlying object, which is exposed via CIndex as
1598# a void*.
1599
1600class ClangObject(object):
1601    """
1602    A helper for Clang objects. This class helps act as an intermediary for
1603    the ctypes library and the Clang CIndex library.
1604    """
1605    def __init__(self, obj):
1606        assert isinstance(obj, c_object_p) and obj
1607        self.obj = self._as_parameter_ = obj
1608
1609    def from_param(self):
1610        return self._as_parameter_
1611
1612
1613class _CXUnsavedFile(Structure):
1614    """Helper for passing unsaved file arguments."""
1615    _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1616
1617class CompletionChunk:
1618    class Kind:
1619        def __init__(self, name):
1620            self.name = name
1621
1622        def __str__(self):
1623            return self.name
1624
1625        def __repr__(self):
1626            return "<ChunkKind: %s>" % self
1627
1628    def __init__(self, completionString, key):
1629        self.cs = completionString
1630        self.key = key
1631
1632    def __repr__(self):
1633        return "{'" + self.spelling + "', " + str(self.kind) + "}"
1634
1635    @property
1636    def spelling(self):
1637        return lib.clang_getCompletionChunkText(self.cs, self.key).spelling
1638
1639    @property
1640    def kind(self):
1641        res = lib.clang_getCompletionChunkKind(self.cs, self.key)
1642        return completionChunkKindMap[res]
1643
1644    @property
1645    def string(self):
1646        res = lib.clang_getCompletionChunkCompletionString(self.cs, self.key)
1647
1648        if (res):
1649          return CompletionString(res)
1650        else:
1651          None
1652
1653    def isKindOptional(self):
1654      return self.kind == completionChunkKindMap[0]
1655
1656    def isKindTypedText(self):
1657      return self.kind == completionChunkKindMap[1]
1658
1659    def isKindPlaceHolder(self):
1660      return self.kind == completionChunkKindMap[3]
1661
1662    def isKindInformative(self):
1663      return self.kind == completionChunkKindMap[4]
1664
1665    def isKindResultType(self):
1666      return self.kind == completionChunkKindMap[15]
1667
1668completionChunkKindMap = {
1669            0: CompletionChunk.Kind("Optional"),
1670            1: CompletionChunk.Kind("TypedText"),
1671            2: CompletionChunk.Kind("Text"),
1672            3: CompletionChunk.Kind("Placeholder"),
1673            4: CompletionChunk.Kind("Informative"),
1674            5: CompletionChunk.Kind("CurrentParameter"),
1675            6: CompletionChunk.Kind("LeftParen"),
1676            7: CompletionChunk.Kind("RightParen"),
1677            8: CompletionChunk.Kind("LeftBracket"),
1678            9: CompletionChunk.Kind("RightBracket"),
1679            10: CompletionChunk.Kind("LeftBrace"),
1680            11: CompletionChunk.Kind("RightBrace"),
1681            12: CompletionChunk.Kind("LeftAngle"),
1682            13: CompletionChunk.Kind("RightAngle"),
1683            14: CompletionChunk.Kind("Comma"),
1684            15: CompletionChunk.Kind("ResultType"),
1685            16: CompletionChunk.Kind("Colon"),
1686            17: CompletionChunk.Kind("SemiColon"),
1687            18: CompletionChunk.Kind("Equal"),
1688            19: CompletionChunk.Kind("HorizontalSpace"),
1689            20: CompletionChunk.Kind("VerticalSpace")}
1690
1691class CompletionString(ClangObject):
1692    class Availability:
1693        def __init__(self, name):
1694            self.name = name
1695
1696        def __str__(self):
1697            return self.name
1698
1699        def __repr__(self):
1700            return "<Availability: %s>" % self
1701
1702    def __len__(self):
1703        return lib.clang_getNumCompletionChunks(self.obj)
1704
1705    def __getitem__(self, key):
1706        if len(self) <= key:
1707            raise IndexError
1708        return CompletionChunk(self.obj, key)
1709
1710    @property
1711    def priority(self):
1712        return lib.clang_getCompletionPriority(self.obj)
1713
1714    @property
1715    def availability(self):
1716        res = lib.clang_getCompletionAvailability(self.obj)
1717        return availabilityKinds[res]
1718
1719    def __repr__(self):
1720        return " | ".join([str(a) for a in self]) \
1721               + " || Priority: " + str(self.priority) \
1722               + " || Availability: " + str(self.availability)
1723
1724availabilityKinds = {
1725            0: CompletionChunk.Kind("Available"),
1726            1: CompletionChunk.Kind("Deprecated"),
1727            2: CompletionChunk.Kind("NotAvailable")}
1728
1729class CodeCompletionResult(Structure):
1730    _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
1731
1732    def __repr__(self):
1733        return str(CompletionString(self.completionString))
1734
1735    @property
1736    def kind(self):
1737        return CursorKind.from_id(self.cursorKind)
1738
1739    @property
1740    def string(self):
1741        return CompletionString(self.completionString)
1742
1743class CCRStructure(Structure):
1744    _fields_ = [('results', POINTER(CodeCompletionResult)),
1745                ('numResults', c_int)]
1746
1747    def __len__(self):
1748        return self.numResults
1749
1750    def __getitem__(self, key):
1751        if len(self) <= key:
1752            raise IndexError
1753
1754        return self.results[key]
1755
1756class CodeCompletionResults(ClangObject):
1757    def __init__(self, ptr):
1758        assert isinstance(ptr, POINTER(CCRStructure)) and ptr
1759        self.ptr = self._as_parameter_ = ptr
1760
1761    def from_param(self):
1762        return self._as_parameter_
1763
1764    def __del__(self):
1765        CodeCompletionResults_dispose(self)
1766
1767    @property
1768    def results(self):
1769        return self.ptr.contents
1770
1771    @property
1772    def diagnostics(self):
1773        class DiagnosticsItr:
1774            def __init__(self, ccr):
1775                self.ccr= ccr
1776
1777            def __len__(self):
1778                return int(lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
1779
1780            def __getitem__(self, key):
1781                return lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
1782
1783        return DiagnosticsItr(self)
1784
1785
1786class Index(ClangObject):
1787    """
1788    The Index type provides the primary interface to the Clang CIndex library,
1789    primarily by providing an interface for reading and parsing translation
1790    units.
1791    """
1792
1793    @staticmethod
1794    def create(excludeDecls=False):
1795        """
1796        Create a new Index.
1797        Parameters:
1798        excludeDecls -- Exclude local declarations from translation units.
1799        """
1800        return Index(lib.clang_createIndex(excludeDecls, 0))
1801
1802    def __del__(self):
1803        lib.clang_disposeIndex(self)
1804
1805    def read(self, path):
1806        """Load a TranslationUnit from the given AST file."""
1807        return TranslationUnit.from_ast(path, self)
1808
1809    def parse(self, path, args=None, unsaved_files=None, options = 0):
1810        """Load the translation unit from the given source code file by running
1811        clang and generating the AST before loading. Additional command line
1812        parameters can be passed to clang via the args parameter.
1813
1814        In-memory contents for files can be provided by passing a list of pairs
1815        to as unsaved_files, the first item should be the filenames to be mapped
1816        and the second should be the contents to be substituted for the
1817        file. The contents may be passed as strings or file objects.
1818
1819        If an error was encountered during parsing, a TranslationUnitLoadError
1820        will be raised.
1821        """
1822        return TranslationUnit.from_source(path, args, unsaved_files, options,
1823                                           self)
1824
1825class TranslationUnit(ClangObject):
1826    """Represents a source code translation unit.
1827
1828    This is one of the main types in the API. Any time you wish to interact
1829    with Clang's representation of a source file, you typically start with a
1830    translation unit.
1831    """
1832
1833    # Default parsing mode.
1834    PARSE_NONE = 0
1835
1836    # Instruct the parser to create a detailed processing record containing
1837    # metadata not normally retained.
1838    PARSE_DETAILED_PROCESSING_RECORD = 1
1839
1840    # Indicates that the translation unit is incomplete. This is typically used
1841    # when parsing headers.
1842    PARSE_INCOMPLETE = 2
1843
1844    # Instruct the parser to create a pre-compiled preamble for the translation
1845    # unit. This caches the preamble (included files at top of source file).
1846    # This is useful if the translation unit will be reparsed and you don't
1847    # want to incur the overhead of reparsing the preamble.
1848    PARSE_PRECOMPILED_PREAMBLE = 4
1849
1850    # Cache code completion information on parse. This adds time to parsing but
1851    # speeds up code completion.
1852    PARSE_CACHE_COMPLETION_RESULTS = 8
1853
1854    # Flags with values 16 and 32 are deprecated and intentionally omitted.
1855
1856    # Do not parse function bodies. This is useful if you only care about
1857    # searching for declarations/definitions.
1858    PARSE_SKIP_FUNCTION_BODIES = 64
1859
1860    @classmethod
1861    def from_source(cls, filename, args=None, unsaved_files=None, options=0,
1862                    index=None):
1863        """Create a TranslationUnit by parsing source.
1864
1865        This is capable of processing source code both from files on the
1866        filesystem as well as in-memory contents.
1867
1868        Command-line arguments that would be passed to clang are specified as
1869        a list via args. These can be used to specify include paths, warnings,
1870        etc. e.g. ["-Wall", "-I/path/to/include"].
1871
1872        In-memory file content can be provided via unsaved_files. This is an
1873        iterable of 2-tuples. The first element is the str filename. The
1874        second element defines the content. Content can be provided as str
1875        source code or as file objects (anything with a read() method). If
1876        a file object is being used, content will be read until EOF and the
1877        read cursor will not be reset to its original position.
1878
1879        options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
1880        control parsing behavior.
1881
1882        index is an Index instance to utilize. If not provided, a new Index
1883        will be created for this TranslationUnit.
1884
1885        To parse source from the filesystem, the filename of the file to parse
1886        is specified by the filename argument. Or, filename could be None and
1887        the args list would contain the filename(s) to parse.
1888
1889        To parse source from an in-memory buffer, set filename to the virtual
1890        filename you wish to associate with this source (e.g. "test.c"). The
1891        contents of that file are then provided in unsaved_files.
1892
1893        If an error occurs, a TranslationUnitLoadError is raised.
1894
1895        Please note that a TranslationUnit with parser errors may be returned.
1896        It is the caller's responsibility to check tu.diagnostics for errors.
1897
1898        Also note that Clang infers the source language from the extension of
1899        the input filename. If you pass in source code containing a C++ class
1900        declaration with the filename "test.c" parsing will fail.
1901        """
1902        if args is None:
1903            args = []
1904
1905        if unsaved_files is None:
1906            unsaved_files = []
1907
1908        if index is None:
1909            index = Index.create()
1910
1911        args_array = None
1912        if len(args) > 0:
1913            args_array = (c_char_p * len(args))(* args)
1914
1915        unsaved_array = None
1916        if len(unsaved_files) > 0:
1917            unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
1918            for i, (name, contents) in enumerate(unsaved_files):
1919                if hasattr(contents, "read"):
1920                    contents = contents.read()
1921
1922                unsaved_array[i].name = name
1923                unsaved_array[i].contents = contents
1924                unsaved_array[i].length = len(contents)
1925
1926        ptr = lib.clang_parseTranslationUnit(index, filename, args_array,
1927                                    len(args), unsaved_array,
1928                                    len(unsaved_files), options)
1929
1930        if ptr is None:
1931            raise TranslationUnitLoadError("Error parsing translation unit.")
1932
1933        return cls(ptr, index=index)
1934
1935    @classmethod
1936    def from_ast_file(cls, filename, index=None):
1937        """Create a TranslationUnit instance from a saved AST file.
1938
1939        A previously-saved AST file (provided with -emit-ast or
1940        TranslationUnit.save()) is loaded from the filename specified.
1941
1942        If the file cannot be loaded, a TranslationUnitLoadError will be
1943        raised.
1944
1945        index is optional and is the Index instance to use. If not provided,
1946        a default Index will be created.
1947        """
1948        if index is None:
1949            index = Index.create()
1950
1951        ptr = lib.clang_createTranslationUnit(index, filename)
1952        if ptr is None:
1953            raise TranslationUnitLoadError(filename)
1954
1955        return cls(ptr=ptr, index=index)
1956
1957    def __init__(self, ptr, index):
1958        """Create a TranslationUnit instance.
1959
1960        TranslationUnits should be created using one of the from_* @classmethod
1961        functions above. __init__ is only called internally.
1962        """
1963        assert isinstance(index, Index)
1964
1965        ClangObject.__init__(self, ptr)
1966
1967    def __del__(self):
1968        lib.clang_disposeTranslationUnit(self)
1969
1970    @property
1971    def cursor(self):
1972        """Retrieve the cursor that represents the given translation unit."""
1973        return lib.clang_getTranslationUnitCursor(self)
1974
1975    @property
1976    def spelling(self):
1977        """Get the original translation unit source file name."""
1978        return lib.clang_getTranslationUnitSpelling(self)
1979
1980    def get_includes(self):
1981        """
1982        Return an iterable sequence of FileInclusion objects that describe the
1983        sequence of inclusions in a translation unit. The first object in
1984        this sequence is always the input file. Note that this method will not
1985        recursively iterate over header files included through precompiled
1986        headers.
1987        """
1988        def visitor(fobj, lptr, depth, includes):
1989            if depth > 0:
1990                loc = lptr.contents
1991                includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
1992
1993        # Automatically adapt CIndex/ctype pointers to python objects
1994        includes = []
1995        lib.clang_getInclusions(self,
1996                callbacks['translation_unit_includes'](visitor), includes)
1997
1998        return iter(includes)
1999
2000    def get_file(self, filename):
2001        """Obtain a File from this translation unit."""
2002
2003        return File.from_name(self, filename)
2004
2005    def get_location(self, filename, position):
2006        """Obtain a SourceLocation for a file in this translation unit.
2007
2008        The position can be specified by passing:
2009
2010          - Integer file offset. Initial file offset is 0.
2011          - 2-tuple of (line number, column number). Initial file position is
2012            (0, 0)
2013        """
2014        f = self.get_file(filename)
2015
2016        if isinstance(position, int):
2017            return SourceLocation.from_offset(self, f, position)
2018
2019        return SourceLocation.from_position(self, f, position[0], position[1])
2020
2021    def get_extent(self, filename, locations):
2022        """Obtain a SourceRange from this translation unit.
2023
2024        The bounds of the SourceRange must ultimately be defined by a start and
2025        end SourceLocation. For the locations argument, you can pass:
2026
2027          - 2 SourceLocation instances in a 2-tuple or list.
2028          - 2 int file offsets via a 2-tuple or list.
2029          - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
2030
2031        e.g.
2032
2033        get_extent('foo.c', (5, 10))
2034        get_extent('foo.c', ((1, 1), (1, 15)))
2035        """
2036        f = self.get_file(filename)
2037
2038        if len(locations) < 2:
2039            raise Exception('Must pass object with at least 2 elements')
2040
2041        start_location, end_location = locations
2042
2043        if hasattr(start_location, '__len__'):
2044            start_location = SourceLocation.from_position(self, f,
2045                start_location[0], start_location[1])
2046        elif isinstance(start_location, int):
2047            start_location = SourceLocation.from_offset(self, f,
2048                start_location)
2049
2050        if hasattr(end_location, '__len__'):
2051            end_location = SourceLocation.from_position(self, f,
2052                end_location[0], end_location[1])
2053        elif isinstance(end_location, int):
2054            end_location = SourceLocation.from_offset(self, f, end_location)
2055
2056        assert isinstance(start_location, SourceLocation)
2057        assert isinstance(end_location, SourceLocation)
2058
2059        return SourceRange.from_locations(start_location, end_location)
2060
2061    @property
2062    def diagnostics(self):
2063        """
2064        Return an iterable (and indexable) object containing the diagnostics.
2065        """
2066        class DiagIterator:
2067            def __init__(self, tu):
2068                self.tu = tu
2069
2070            def __len__(self):
2071                return int(lib.clang_getNumDiagnostics(self.tu))
2072
2073            def __getitem__(self, key):
2074                diag = lib.clang_getDiagnostic(self.tu, key)
2075                if not diag:
2076                    raise IndexError
2077                return Diagnostic(diag)
2078
2079        return DiagIterator(self)
2080
2081    def reparse(self, unsaved_files=None, options=0):
2082        """
2083        Reparse an already parsed translation unit.
2084
2085        In-memory contents for files can be provided by passing a list of pairs
2086        as unsaved_files, the first items should be the filenames to be mapped
2087        and the second should be the contents to be substituted for the
2088        file. The contents may be passed as strings or file objects.
2089        """
2090        if unsaved_files is None:
2091            unsaved_files = []
2092
2093        unsaved_files_array = 0
2094        if len(unsaved_files):
2095            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2096            for i,(name,value) in enumerate(unsaved_files):
2097                if not isinstance(value, str):
2098                    # FIXME: It would be great to support an efficient version
2099                    # of this, one day.
2100                    value = value.read()
2101                    print value
2102                if not isinstance(value, str):
2103                    raise TypeError,'Unexpected unsaved file contents.'
2104                unsaved_files_array[i].name = name
2105                unsaved_files_array[i].contents = value
2106                unsaved_files_array[i].length = len(value)
2107        ptr = lib.clang_reparseTranslationUnit(self, len(unsaved_files),
2108                unsaved_files_array, options)
2109
2110    def save(self, filename):
2111        """Saves the TranslationUnit to a file.
2112
2113        This is equivalent to passing -emit-ast to the clang frontend. The
2114        saved file can be loaded back into a TranslationUnit. Or, if it
2115        corresponds to a header, it can be used as a pre-compiled header file.
2116
2117        If an error occurs while saving, a TranslationUnitSaveError is raised.
2118        If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
2119        the constructed TranslationUnit was not valid at time of save. In this
2120        case, the reason(s) why should be available via
2121        TranslationUnit.diagnostics().
2122
2123        filename -- The path to save the translation unit to.
2124        """
2125        options = lib.clang_defaultSaveOptions(self)
2126        result = int(lib.clang_saveTranslationUnit(self, filename, options))
2127        if result != 0:
2128            raise TranslationUnitSaveError(result,
2129                'Error saving TranslationUnit.')
2130
2131    def codeComplete(self, path, line, column, unsaved_files=None, options=0):
2132        """
2133        Code complete in this translation unit.
2134
2135        In-memory contents for files can be provided by passing a list of pairs
2136        as unsaved_files, the first items should be the filenames to be mapped
2137        and the second should be the contents to be substituted for the
2138        file. The contents may be passed as strings or file objects.
2139        """
2140        if unsaved_files is None:
2141            unsaved_files = []
2142
2143        unsaved_files_array = 0
2144        if len(unsaved_files):
2145            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2146            for i,(name,value) in enumerate(unsaved_files):
2147                if not isinstance(value, str):
2148                    # FIXME: It would be great to support an efficient version
2149                    # of this, one day.
2150                    value = value.read()
2151                    print value
2152                if not isinstance(value, str):
2153                    raise TypeError,'Unexpected unsaved file contents.'
2154                unsaved_files_array[i].name = name
2155                unsaved_files_array[i].contents = value
2156                unsaved_files_array[i].length = len(value)
2157        ptr = lib.clang_codeCompleteAt(self, path, line, column,
2158                unsaved_files_array, len(unsaved_files), options)
2159        if ptr:
2160            return CodeCompletionResults(ptr)
2161        return None
2162
2163    def get_tokens(self, locations=None, extent=None):
2164        """Obtain tokens in this translation unit.
2165
2166        This is a generator for Token instances. The caller specifies a range
2167        of source code to obtain tokens for. The range can be specified as a
2168        2-tuple of SourceLocation or as a SourceRange. If both are defined,
2169        behavior is undefined.
2170        """
2171        if locations is not None:
2172            extent = SourceRange(start=locations[0], end=locations[1])
2173
2174        return TokenGroup.get_tokens(self, extent)
2175
2176class File(ClangObject):
2177    """
2178    The File class represents a particular source file that is part of a
2179    translation unit.
2180    """
2181
2182    @staticmethod
2183    def from_name(translation_unit, file_name):
2184        """Retrieve a file handle within the given translation unit."""
2185        return File(lib.clang_getFile(translation_unit, file_name))
2186
2187    @property
2188    def name(self):
2189        """Return the complete file and path name of the file."""
2190        return lib.clang_getCString(lib.clang_getFileName(self))
2191
2192    @property
2193    def time(self):
2194        """Return the last modification time of the file."""
2195        return lib.clang_getFileTime(self)
2196
2197    def __str__(self):
2198        return self.name
2199
2200    def __repr__(self):
2201        return "<File: %s>" % (self.name)
2202
2203    @staticmethod
2204    def from_cursor_result(res, fn, args):
2205        assert isinstance(res, File)
2206
2207        # Copy a reference to the TranslationUnit to prevent premature GC.
2208        res._tu = args[0]._tu
2209        return res
2210
2211class FileInclusion(object):
2212    """
2213    The FileInclusion class represents the inclusion of one source file by
2214    another via a '#include' directive or as the input file for the translation
2215    unit. This class provides information about the included file, the including
2216    file, the location of the '#include' directive and the depth of the included
2217    file in the stack. Note that the input file has depth 0.
2218    """
2219
2220    def __init__(self, src, tgt, loc, depth):
2221        self.source = src
2222        self.include = tgt
2223        self.location = loc
2224        self.depth = depth
2225
2226    @property
2227    def is_input_file(self):
2228        """True if the included file is the input file."""
2229        return self.depth == 0
2230
2231class CompilationDatabaseError(Exception):
2232    """Represents an error that occurred when working with a CompilationDatabase
2233
2234    Each error is associated to an enumerated value, accessible under
2235    e.cdb_error. Consumers can compare the value with one of the ERROR_
2236    constants in this class.
2237    """
2238
2239    # An unknown error occured
2240    ERROR_UNKNOWN = 0
2241
2242    # The database could not be loaded
2243    ERROR_CANNOTLOADDATABASE = 1
2244
2245    def __init__(self, enumeration, message):
2246        assert isinstance(enumeration, int)
2247
2248        if enumeration > 1:
2249            raise Exception("Encountered undefined CompilationDatabase error "
2250                            "constant: %d. Please file a bug to have this "
2251                            "value supported." % enumeration)
2252
2253        self.cdb_error = enumeration
2254        Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
2255
2256class CompileCommand(object):
2257    """Represents the compile command used to build a file"""
2258    def __init__(self, cmd, ccmds):
2259        self.cmd = cmd
2260        # Keep a reference to the originating CompileCommands
2261        # to prevent garbage collection
2262        self.ccmds = ccmds
2263
2264    @property
2265    def directory(self):
2266        """Get the working directory for this CompileCommand"""
2267        return lib.clang_CompileCommand_getDirectory(self.cmd)
2268
2269    @property
2270    def arguments(self):
2271        """
2272        Get an iterable object providing each argument in the
2273        command line for the compiler invocation as a _CXString.
2274
2275        Invariant : the first argument is the compiler executable
2276        """
2277        length = lib.clang_CompileCommand_getNumArgs(self.cmd)
2278        for i in xrange(length):
2279            yield lib.clang_CompileCommand_getArg(self.cmd, i)
2280
2281class CompileCommands(object):
2282    """
2283    CompileCommands is an iterable object containing all CompileCommand
2284    that can be used for building a specific file.
2285    """
2286    def __init__(self, ccmds):
2287        self.ccmds = ccmds
2288
2289    def __del__(self):
2290        lib.clang_CompileCommands_dispose(self.ccmds)
2291
2292    def __len__(self):
2293        return int(lib.clang_CompileCommands_getSize(self.ccmds))
2294
2295    def __getitem__(self, i):
2296        cc = lib.clang_CompileCommands_getCommand(self.ccmds, i)
2297        if not cc:
2298            raise IndexError
2299        return CompileCommand(cc, self)
2300
2301    @staticmethod
2302    def from_result(res, fn, args):
2303        if not res:
2304            return None
2305        return CompileCommands(res)
2306
2307class CompilationDatabase(ClangObject):
2308    """
2309    The CompilationDatabase is a wrapper class around
2310    clang::tooling::CompilationDatabase
2311
2312    It enables querying how a specific source file can be built.
2313    """
2314
2315    def __del__(self):
2316        lib.clang_CompilationDatabase_dispose(self)
2317
2318    @staticmethod
2319    def from_result(res, fn, args):
2320        if not res:
2321            raise CompilationDatabaseError(0,
2322                                           "CompilationDatabase loading failed")
2323        return CompilationDatabase(res)
2324
2325    @staticmethod
2326    def fromDirectory(buildDir):
2327        """Builds a CompilationDatabase from the database found in buildDir"""
2328        errorCode = c_uint()
2329        try:
2330            cdb = lib.clang_CompilationDatabase_fromDirectory(buildDir,
2331                byref(errorCode))
2332        except CompilationDatabaseError as e:
2333            raise CompilationDatabaseError(int(errorCode.value),
2334                                           "CompilationDatabase loading failed")
2335        return cdb
2336
2337    def getCompileCommands(self, filename):
2338        """
2339        Get an iterable object providing all the CompileCommands available to
2340        build filename. Returns None if filename is not found in the database.
2341        """
2342        return lib.clang_CompilationDatabase_getCompileCommands(self, filename)
2343
2344class Token(Structure):
2345    """Represents a single token from the preprocessor.
2346
2347    Tokens are effectively segments of source code. Source code is first parsed
2348    into tokens before being converted into the AST and Cursors.
2349
2350    Tokens are obtained from parsed TranslationUnit instances. You currently
2351    can't create tokens manually.
2352    """
2353    _fields_ = [
2354        ('int_data', c_uint * 4),
2355        ('ptr_data', c_void_p)
2356    ]
2357
2358    @property
2359    def spelling(self):
2360        """The spelling of this token.
2361
2362        This is the textual representation of the token in source.
2363        """
2364        return lib.clang_getTokenSpelling(self._tu, self)
2365
2366    @property
2367    def kind(self):
2368        """Obtain the TokenKind of the current token."""
2369        return TokenKind.from_value(lib.clang_getTokenKind(self))
2370
2371    @property
2372    def location(self):
2373        """The SourceLocation this Token occurs at."""
2374        return lib.clang_getTokenLocation(self._tu, self)
2375
2376    @property
2377    def extent(self):
2378        """The SourceRange this Token occupies."""
2379        return lib.clang_getTokenExtent(self._tu, self)
2380
2381    @property
2382    def cursor(self):
2383        """The Cursor this Token corresponds to."""
2384        cursor = Cursor()
2385
2386        lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
2387
2388        return cursor
2389
2390# Now comes the plumbing to hook up the C library.
2391
2392# Register callback types in common container.
2393callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
2394        POINTER(SourceLocation), c_uint, py_object)
2395callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
2396
2397def register_functions(lib):
2398    """Register function prototypes with a libclang library instance.
2399
2400    This must be called as part of library instantiation so Python knows how
2401    to call out to the shared library.
2402    """
2403    # Functions are registered in strictly alphabetical order.
2404    lib.clang_annotateTokens.argtype = [TranslationUnit, POINTER(Token),
2405                                        c_uint, POINTER(Cursor)]
2406
2407    lib.clang_CompilationDatabase_dispose.argtypes = [c_object_p]
2408
2409    lib.clang_CompilationDatabase_fromDirectory.argtypes = [c_char_p,
2410        POINTER(c_uint)]
2411    lib.clang_CompilationDatabase_fromDirectory.restype = c_object_p
2412    lib.clang_CompilationDatabase_fromDirectory.errcheck = CompilationDatabase.from_result
2413
2414    lib.clang_CompilationDatabase_getCompileCommands.argtypes = [c_object_p, c_char_p]
2415    lib.clang_CompilationDatabase_getCompileCommands.restype = c_object_p
2416    lib.clang_CompilationDatabase_getCompileCommands.errcheck = CompileCommands.from_result
2417
2418    lib.clang_CompileCommands_dispose.argtypes = [c_object_p]
2419
2420    lib.clang_CompileCommands_getCommand.argtypes = [c_object_p, c_uint]
2421    lib.clang_CompileCommands_getCommand.restype = c_object_p
2422
2423    lib.clang_CompileCommands_getSize.argtypes = [c_object_p]
2424    lib.clang_CompileCommands_getSize.restype = c_uint
2425
2426    lib.clang_CompileCommand_getArg.argtypes = [c_object_p, c_uint]
2427    lib.clang_CompileCommand_getArg.restype = _CXString
2428    lib.clang_CompileCommand_getArg.errcheck = _CXString.from_result
2429
2430    lib.clang_CompileCommand_getDirectory.argtypes = [c_object_p]
2431    lib.clang_CompileCommand_getDirectory.restype = _CXString
2432    lib.clang_CompileCommand_getDirectory.errcheck = _CXString.from_result
2433
2434    lib.clang_CompileCommand_getNumArgs.argtypes = [c_object_p]
2435    lib.clang_CompileCommand_getNumArgs.restype = c_uint
2436
2437    lib.clang_codeCompleteAt.argtypes = [TranslationUnit, c_char_p, c_int,
2438        c_int, c_void_p, c_int, c_int]
2439    lib.clang_codeCompleteAt.restype = POINTER(CCRStructure)
2440
2441    lib.clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults,
2442        c_int]
2443    lib.clang_codeCompleteGetDiagnostic.restype = Diagnostic
2444
2445    lib.clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults]
2446    lib.clang_codeCompleteGetNumDiagnostics.restype = c_int
2447
2448    lib.clang_createIndex.argtypes = [c_int, c_int]
2449    lib.clang_createIndex.restype = c_object_p
2450
2451    lib.clang_createTranslationUnit.argtypes = [Index, c_char_p]
2452    lib.clang_createTranslationUnit.restype = c_object_p
2453
2454    lib.clang_CXXMethod_isStatic.argtypes = [Cursor]
2455    lib.clang_CXXMethod_isStatic.restype = bool
2456
2457    lib.clang_CXXMethod_isVirtual.argtypes = [Cursor]
2458    lib.clang_CXXMethod_isVirtual.restype = bool
2459
2460    lib.clang_defaultSaveOptions.argtypes = [TranslationUnit]
2461    lib.clang_defaultSaveOptions.restype = c_uint
2462
2463    lib.clang_disposeCodeCompleteResults.argtypes = [CodeCompletionResults]
2464
2465    #lib.clang_disposeCXTUResourceUsage.argtypes = [CXTUResourceUsage]
2466
2467    lib.clang_disposeDiagnostic.argtypes = [Diagnostic]
2468
2469    lib.clang_disposeIndex.argtypes = [Index]
2470
2471    lib.clang_disposeString.argtypes = [_CXString]
2472
2473    lib.clang_disposeTokens.argtype = [TranslationUnit, POINTER(Token), c_uint]
2474
2475    lib.clang_disposeTranslationUnit.argtypes = [TranslationUnit]
2476
2477    lib.clang_equalCursors.argtypes = [Cursor, Cursor]
2478    lib.clang_equalCursors.restype = bool
2479
2480    lib.clang_equalLocations.argtypes = [SourceLocation, SourceLocation]
2481    lib.clang_equalLocations.restype = bool
2482
2483    lib.clang_equalRanges.argtypes = [SourceRange, SourceRange]
2484    lib.clang_equalRanges.restype = bool
2485
2486    lib.clang_equalTypes.argtypes = [Type, Type]
2487    lib.clang_equalTypes.restype = bool
2488
2489    lib.clang_getArgType.argtypes = [Type, c_uint]
2490    lib.clang_getArgType.restype = Type
2491    lib.clang_getArgType.errcheck = Type.from_result
2492
2493    lib.clang_getArrayElementType.argtypes = [Type]
2494    lib.clang_getArrayElementType.restype = Type
2495    lib.clang_getArrayElementType.errcheck = Type.from_result
2496
2497    lib.clang_getArraySize.argtypes = [Type]
2498    lib.clang_getArraySize.restype = c_longlong
2499
2500    lib.clang_getCanonicalCursor.argtypes = [Cursor]
2501    lib.clang_getCanonicalCursor.restype = Cursor
2502    lib.clang_getCanonicalCursor.errcheck = Cursor.from_cursor_result
2503
2504    lib.clang_getCanonicalType.argtypes = [Type]
2505    lib.clang_getCanonicalType.restype = Type
2506    lib.clang_getCanonicalType.errcheck = Type.from_result
2507
2508    lib.clang_getCompletionAvailability.argtypes = [c_void_p]
2509    lib.clang_getCompletionAvailability.restype = c_int
2510
2511    lib.clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int]
2512    lib.clang_getCompletionChunkCompletionString.restype = c_object_p
2513
2514    lib.clang_getCompletionChunkKind.argtypes = [c_void_p, c_int]
2515    lib.clang_getCompletionChunkKind.restype = c_int
2516
2517    lib.clang_getCompletionChunkText.argtypes = [c_void_p, c_int]
2518    lib.clang_getCompletionChunkText.restype = _CXString
2519
2520    lib.clang_getCompletionPriority.argtypes = [c_void_p]
2521    lib.clang_getCompletionPriority.restype = c_int
2522
2523    lib.clang_getCString.argtypes = [_CXString]
2524    lib.clang_getCString.restype = c_char_p
2525
2526    lib.clang_getCursor.argtypes = [TranslationUnit, SourceLocation]
2527    lib.clang_getCursor.restype = Cursor
2528
2529    lib.clang_getCursorDefinition.argtypes = [Cursor]
2530    lib.clang_getCursorDefinition.restype = Cursor
2531    lib.clang_getCursorDefinition.errcheck = Cursor.from_result
2532
2533    lib.clang_getCursorDisplayName.argtypes = [Cursor]
2534    lib.clang_getCursorDisplayName.restype = _CXString
2535    lib.clang_getCursorDisplayName.errcheck = _CXString.from_result
2536
2537    lib.clang_getCursorExtent.argtypes = [Cursor]
2538    lib.clang_getCursorExtent.restype = SourceRange
2539
2540    lib.clang_getCursorLexicalParent.argtypes = [Cursor]
2541    lib.clang_getCursorLexicalParent.restype = Cursor
2542    lib.clang_getCursorLexicalParent.errcheck = Cursor.from_cursor_result
2543
2544    lib.clang_getCursorLocation.argtypes = [Cursor]
2545    lib.clang_getCursorLocation.restype = SourceLocation
2546
2547    lib.clang_getCursorReferenced.argtypes = [Cursor]
2548    lib.clang_getCursorReferenced.restype = Cursor
2549    lib.clang_getCursorReferenced.errcheck = Cursor.from_result
2550
2551    lib.clang_getCursorReferenceNameRange.argtypes = [Cursor, c_uint, c_uint]
2552    lib.clang_getCursorReferenceNameRange.restype = SourceRange
2553
2554    lib.clang_getCursorSemanticParent.argtypes = [Cursor]
2555    lib.clang_getCursorSemanticParent.restype = Cursor
2556    lib.clang_getCursorSemanticParent.errcheck = Cursor.from_cursor_result
2557
2558    lib.clang_getCursorSpelling.argtypes = [Cursor]
2559    lib.clang_getCursorSpelling.restype = _CXString
2560    lib.clang_getCursorSpelling.errcheck = _CXString.from_result
2561
2562    lib.clang_getCursorType.argtypes = [Cursor]
2563    lib.clang_getCursorType.restype = Type
2564    lib.clang_getCursorType.errcheck = Type.from_result
2565
2566    lib.clang_getCursorUSR.argtypes = [Cursor]
2567    lib.clang_getCursorUSR.restype = _CXString
2568    lib.clang_getCursorUSR.errcheck = _CXString.from_result
2569
2570    #lib.clang_getCXTUResourceUsage.argtypes = [TranslationUnit]
2571    #lib.clang_getCXTUResourceUsage.restype = CXTUResourceUsage
2572
2573    lib.clang_getCXXAccessSpecifier.argtypes = [Cursor]
2574    lib.clang_getCXXAccessSpecifier.restype = c_uint
2575
2576    lib.clang_getDeclObjCTypeEncoding.argtypes = [Cursor]
2577    lib.clang_getDeclObjCTypeEncoding.restype = _CXString
2578    lib.clang_getDeclObjCTypeEncoding.errcheck = _CXString.from_result
2579
2580    lib.clang_getDiagnostic.argtypes = [c_object_p, c_uint]
2581    lib.clang_getDiagnostic.restype = c_object_p
2582
2583    lib.clang_getDiagnosticCategory.argtypes = [Diagnostic]
2584    lib.clang_getDiagnosticCategory.restype = c_uint
2585
2586    lib.clang_getDiagnosticCategoryName.argtypes = [c_uint]
2587    lib.clang_getDiagnosticCategoryName.restype = _CXString
2588    lib.clang_getDiagnosticCategoryName.errcheck = _CXString.from_result
2589
2590    lib.clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint,
2591        POINTER(SourceRange)]
2592    lib.clang_getDiagnosticFixIt.restype = _CXString
2593    lib.clang_getDiagnosticFixIt.errcheck = _CXString.from_result
2594
2595    lib.clang_getDiagnosticLocation.argtypes = [Diagnostic]
2596    lib.clang_getDiagnosticLocation.restype = SourceLocation
2597
2598    lib.clang_getDiagnosticNumFixIts.argtypes = [Diagnostic]
2599    lib.clang_getDiagnosticNumFixIts.restype = c_uint
2600
2601    lib.clang_getDiagnosticNumRanges.argtypes = [Diagnostic]
2602    lib.clang_getDiagnosticNumRanges.restype = c_uint
2603
2604    lib.clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)]
2605    lib.clang_getDiagnosticOption.restype = _CXString
2606    lib.clang_getDiagnosticOption.errcheck = _CXString.from_result
2607
2608    lib.clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint]
2609    lib.clang_getDiagnosticRange.restype = SourceRange
2610
2611    lib.clang_getDiagnosticSeverity.argtypes = [Diagnostic]
2612    lib.clang_getDiagnosticSeverity.restype = c_int
2613
2614    lib.clang_getDiagnosticSpelling.argtypes = [Diagnostic]
2615    lib.clang_getDiagnosticSpelling.restype = _CXString
2616    lib.clang_getDiagnosticSpelling.errcheck = _CXString.from_result
2617
2618    lib.clang_getElementType.argtypes = [Type]
2619    lib.clang_getElementType.restype = Type
2620    lib.clang_getElementType.errcheck = Type.from_result
2621
2622    lib.clang_getEnumConstantDeclUnsignedValue.argtypes = [Cursor]
2623    lib.clang_getEnumConstantDeclUnsignedValue.restype = c_ulonglong
2624
2625    lib.clang_getEnumConstantDeclValue.argtypes = [Cursor]
2626    lib.clang_getEnumConstantDeclValue.restype = c_longlong
2627
2628    lib.clang_getEnumDeclIntegerType.argtypes = [Cursor]
2629    lib.clang_getEnumDeclIntegerType.restype = Type
2630    lib.clang_getEnumDeclIntegerType.errcheck = Type.from_result
2631
2632    lib.clang_getFile.argtypes = [TranslationUnit, c_char_p]
2633    lib.clang_getFile.restype = c_object_p
2634
2635    lib.clang_getFileName.argtypes = [File]
2636    lib.clang_getFileName.restype = _CXString
2637    # TODO go through _CXString.from_result?
2638
2639    lib.clang_getFileTime.argtypes = [File]
2640    lib.clang_getFileTime.restype = c_uint
2641
2642    lib.clang_getIBOutletCollectionType.argtypes = [Cursor]
2643    lib.clang_getIBOutletCollectionType.restype = Type
2644    lib.clang_getIBOutletCollectionType.errcheck = Type.from_result
2645
2646    lib.clang_getIncludedFile.argtypes = [Cursor]
2647    lib.clang_getIncludedFile.restype = File
2648    lib.clang_getIncludedFile.errcheck = File.from_cursor_result
2649
2650    lib.clang_getInclusions.argtypes = [TranslationUnit,
2651        callbacks['translation_unit_includes'], py_object]
2652
2653    lib.clang_getInstantiationLocation.argtypes = [SourceLocation,
2654        POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)]
2655
2656    lib.clang_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint]
2657    lib.clang_getLocation.restype = SourceLocation
2658
2659    lib.clang_getLocationForOffset.argtypes = [TranslationUnit, File, c_uint]
2660    lib.clang_getLocationForOffset.restype = SourceLocation
2661
2662    lib.clang_getNullCursor.restype = Cursor
2663
2664    lib.clang_getNumArgTypes.argtypes = [Type]
2665    lib.clang_getNumArgTypes.restype = c_uint
2666
2667    lib.clang_getNumCompletionChunks.argtypes = [c_void_p]
2668    lib.clang_getNumCompletionChunks.restype = c_int
2669
2670    lib.clang_getNumDiagnostics.argtypes = [c_object_p]
2671    lib.clang_getNumDiagnostics.restype = c_uint
2672
2673    lib.clang_getNumElements.argtypes = [Type]
2674    lib.clang_getNumElements.restype = c_longlong
2675
2676    lib.clang_getNumOverloadedDecls.argtypes = [Cursor]
2677    lib.clang_getNumOverloadedDecls.restyp = c_uint
2678
2679    lib.clang_getOverloadedDecl.argtypes = [Cursor, c_uint]
2680    lib.clang_getOverloadedDecl.restype = Cursor
2681    lib.clang_getOverloadedDecl.errcheck = Cursor.from_cursor_result
2682
2683    lib.clang_getPointeeType.argtypes = [Type]
2684    lib.clang_getPointeeType.restype = Type
2685    lib.clang_getPointeeType.errcheck = Type.from_result
2686
2687    lib.clang_getRange.argtypes = [SourceLocation, SourceLocation]
2688    lib.clang_getRange.restype = SourceRange
2689
2690    lib.clang_getRangeEnd.argtypes = [SourceRange]
2691    lib.clang_getRangeEnd.restype = SourceLocation
2692
2693    lib.clang_getRangeStart.argtypes = [SourceRange]
2694    lib.clang_getRangeStart.restype = SourceLocation
2695
2696    lib.clang_getResultType.argtypes = [Type]
2697    lib.clang_getResultType.restype = Type
2698    lib.clang_getResultType.errcheck = Type.from_result
2699
2700    lib.clang_getSpecializedCursorTemplate.argtypes = [Cursor]
2701    lib.clang_getSpecializedCursorTemplate.restype = Cursor
2702    lib.clang_getSpecializedCursorTemplate.errcheck = Cursor.from_cursor_result
2703
2704    lib.clang_getTemplateCursorKind.argtypes = [Cursor]
2705    lib.clang_getTemplateCursorKind.restype = c_uint
2706
2707    lib.clang_getTokenExtent.argtypes = [TranslationUnit, Token]
2708    lib.clang_getTokenExtent.restype = SourceRange
2709
2710    lib.clang_getTokenKind.argtypes = [Token]
2711    lib.clang_getTokenKind.restype = c_uint
2712
2713    lib.clang_getTokenLocation.argtype = [TranslationUnit, Token]
2714    lib.clang_getTokenLocation.restype = SourceLocation
2715
2716    lib.clang_getTokenSpelling.argtype = [TranslationUnit, Token]
2717    lib.clang_getTokenSpelling.restype = _CXString
2718    lib.clang_getTokenSpelling.errcheck = _CXString.from_result
2719
2720    lib.clang_getTranslationUnitCursor.argtypes = [TranslationUnit]
2721    lib.clang_getTranslationUnitCursor.restype = Cursor
2722    lib.clang_getTranslationUnitCursor.errcheck = Cursor.from_result
2723
2724    lib.clang_getTranslationUnitSpelling.argtypes = [TranslationUnit]
2725    lib.clang_getTranslationUnitSpelling.restype = _CXString
2726    lib.clang_getTranslationUnitSpelling.errcheck = _CXString.from_result
2727
2728    lib.clang_getTUResourceUsageName.argtypes = [c_uint]
2729    lib.clang_getTUResourceUsageName.restype = c_char_p
2730
2731    lib.clang_getTypeDeclaration.argtypes = [Type]
2732    lib.clang_getTypeDeclaration.restype = Cursor
2733    lib.clang_getTypeDeclaration.errcheck = Cursor.from_result
2734
2735    lib.clang_getTypedefDeclUnderlyingType.argtypes = [Cursor]
2736    lib.clang_getTypedefDeclUnderlyingType.restype = Type
2737    lib.clang_getTypedefDeclUnderlyingType.errcheck = Type.from_result
2738
2739    lib.clang_getTypeKindSpelling.argtypes = [c_uint]
2740    lib.clang_getTypeKindSpelling.restype = _CXString
2741    lib.clang_getTypeKindSpelling.errcheck = _CXString.from_result
2742
2743    lib.clang_hashCursor.argtypes = [Cursor]
2744    lib.clang_hashCursor.restype = c_uint
2745
2746    lib.clang_isAttribute.argtypes = [CursorKind]
2747    lib.clang_isAttribute.restype = bool
2748
2749    lib.clang_isConstQualifiedType.argtypes = [Type]
2750    lib.clang_isConstQualifiedType.restype = bool
2751
2752    lib.clang_isCursorDefinition.argtypes = [Cursor]
2753    lib.clang_isCursorDefinition.restype = bool
2754
2755    lib.clang_isDeclaration.argtypes = [CursorKind]
2756    lib.clang_isDeclaration.restype = bool
2757
2758    lib.clang_isExpression.argtypes = [CursorKind]
2759    lib.clang_isExpression.restype = bool
2760
2761    lib.clang_isFileMultipleIncludeGuarded.argtypes = [TranslationUnit, File]
2762    lib.clang_isFileMultipleIncludeGuarded.restype = bool
2763
2764    lib.clang_isFunctionTypeVariadic.argtypes = [Type]
2765    lib.clang_isFunctionTypeVariadic.restype = bool
2766
2767    lib.clang_isInvalid.argtypes = [CursorKind]
2768    lib.clang_isInvalid.restype = bool
2769
2770    lib.clang_isPODType.argtypes = [Type]
2771    lib.clang_isPODType.restype = bool
2772
2773    lib.clang_isPreprocessing.argtypes = [CursorKind]
2774    lib.clang_isPreprocessing.restype = bool
2775
2776    lib.clang_isReference.argtypes = [CursorKind]
2777    lib.clang_isReference.restype = bool
2778
2779    lib.clang_isRestrictQualifiedType.argtypes = [Type]
2780    lib.clang_isRestrictQualifiedType.restype = bool
2781
2782    lib.clang_isStatement.argtypes = [CursorKind]
2783    lib.clang_isStatement.restype = bool
2784
2785    lib.clang_isTranslationUnit.argtypes = [CursorKind]
2786    lib.clang_isTranslationUnit.restype = bool
2787
2788    lib.clang_isUnexposed.argtypes = [CursorKind]
2789    lib.clang_isUnexposed.restype = bool
2790
2791    lib.clang_isVirtualBase.argtypes = [Cursor]
2792    lib.clang_isVirtualBase.restype = bool
2793
2794    lib.clang_isVolatileQualifiedType.argtypes = [Type]
2795    lib.clang_isVolatileQualifiedType.restype = bool
2796
2797    lib.clang_parseTranslationUnit.argypes = [Index, c_char_p, c_void_p, c_int,
2798        c_void_p, c_int, c_int]
2799    lib.clang_parseTranslationUnit.restype = c_object_p
2800
2801    lib.clang_reparseTranslationUnit.argtypes = [TranslationUnit, c_int,
2802        c_void_p, c_int]
2803    lib.clang_reparseTranslationUnit.restype = c_int
2804
2805    lib.clang_saveTranslationUnit.argtypes = [TranslationUnit, c_char_p,
2806        c_uint]
2807    lib.clang_saveTranslationUnit.restype = c_int
2808
2809    lib.clang_tokenize.argtypes = [TranslationUnit, SourceRange,
2810        POINTER(POINTER(Token)), POINTER(c_uint)]
2811
2812    lib.clang_visitChildren.argtypes = [Cursor, callbacks['cursor_visit'],
2813        py_object]
2814    lib.clang_visitChildren.restype = c_uint
2815
2816register_functions(lib)
2817
2818def register_enumerations():
2819    for name, value in clang.enumerations.TokenKinds:
2820        TokenKind.register(value, name)
2821
2822register_enumerations()
2823
2824__all__ = [
2825    'CodeCompletionResults',
2826    'CompilationDatabase',
2827    'CompileCommands',
2828    'CompileCommand',
2829    'CursorKind',
2830    'Cursor',
2831    'Diagnostic',
2832    'File',
2833    'FixIt',
2834    'Index',
2835    'SourceLocation',
2836    'SourceRange',
2837    'TokenKind',
2838    'Token',
2839    'TranslationUnitLoadError',
2840    'TranslationUnit',
2841    'TypeKind',
2842    'Type',
2843]
2844