cindex.py revision bbc2e090996cdf51f0e7a4235f6e0ca65c95d514
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
68def get_cindex_library():
69    # FIXME: It's probably not the case that the library is actually found in
70    # this location. We need a better system of identifying and loading the
71    # CIndex library. It could be on path or elsewhere, or versioned, etc.
72    import platform
73    name = platform.system()
74    if name == 'Darwin':
75        return cdll.LoadLibrary('libclang.dylib')
76    elif name == 'Windows':
77        return cdll.LoadLibrary('libclang.dll')
78    else:
79        return cdll.LoadLibrary('libclang.so')
80
81# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
82# object. This is a problem, because it means that from_parameter will see an
83# integer and pass the wrong value on platforms where int != void*. Work around
84# this by marshalling object arguments as void**.
85c_object_p = POINTER(c_void_p)
86
87lib = get_cindex_library()
88
89### Structures and Utility Classes ###
90
91class _CXString(Structure):
92    """Helper for transforming CXString results."""
93
94    _fields_ = [("spelling", c_char_p), ("free", c_int)]
95
96    def __del__(self):
97        _CXString_dispose(self)
98
99    @staticmethod
100    def from_result(res, fn, args):
101        assert isinstance(res, _CXString)
102        return _CXString_getCString(res)
103
104class SourceLocation(Structure):
105    """
106    A SourceLocation represents a particular location within a source file.
107    """
108    _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
109    _data = None
110
111    def _get_instantiation(self):
112        if self._data is None:
113            f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
114            SourceLocation_loc(self, byref(f), byref(l), byref(c), byref(o))
115            if f:
116                f = File(f)
117            else:
118                f = None
119            self._data = (f, int(l.value), int(c.value), int(o.value))
120        return self._data
121
122    @staticmethod
123    def from_position(tu, file, line, column):
124        """
125        Retrieve the source location associated with a given file/line/column in
126        a particular translation unit.
127        """
128        return SourceLocation_getLocation(tu, file, line, column)
129
130    @property
131    def file(self):
132        """Get the file represented by this source location."""
133        return self._get_instantiation()[0]
134
135    @property
136    def line(self):
137        """Get the line represented by this source location."""
138        return self._get_instantiation()[1]
139
140    @property
141    def column(self):
142        """Get the column represented by this source location."""
143        return self._get_instantiation()[2]
144
145    @property
146    def offset(self):
147        """Get the file offset represented by this source location."""
148        return self._get_instantiation()[3]
149
150    def __eq__(self, other):
151        return SourceLocation_equalLocations(self, other)
152
153    def __ne__(self, other):
154        return not self.__eq__(other)
155
156    def __repr__(self):
157        if self.file:
158            filename = self.file.name
159        else:
160            filename = None
161        return "<SourceLocation file %r, line %r, column %r>" % (
162            filename, self.line, self.column)
163
164class SourceRange(Structure):
165    """
166    A SourceRange describes a range of source locations within the source
167    code.
168    """
169    _fields_ = [
170        ("ptr_data", c_void_p * 2),
171        ("begin_int_data", c_uint),
172        ("end_int_data", c_uint)]
173
174    # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
175    # object.
176    @staticmethod
177    def from_locations(start, end):
178        return SourceRange_getRange(start, end)
179
180    @property
181    def start(self):
182        """
183        Return a SourceLocation representing the first character within a
184        source range.
185        """
186        return SourceRange_start(self)
187
188    @property
189    def end(self):
190        """
191        Return a SourceLocation representing the last character within a
192        source range.
193        """
194        return SourceRange_end(self)
195
196    def __eq__(self, other):
197        return SourceRange_equalRanges(self, other)
198
199    def __ne__(self, other):
200        return not self.__eq__(other)
201
202    def __repr__(self):
203        return "<SourceRange start %r, end %r>" % (self.start, self.end)
204
205class Diagnostic(object):
206    """
207    A Diagnostic is a single instance of a Clang diagnostic. It includes the
208    diagnostic severity, the message, the location the diagnostic occurred, as
209    well as additional source ranges and associated fix-it hints.
210    """
211
212    Ignored = 0
213    Note    = 1
214    Warning = 2
215    Error   = 3
216    Fatal   = 4
217
218    def __init__(self, ptr):
219        self.ptr = ptr
220
221    def __del__(self):
222        _clang_disposeDiagnostic(self)
223
224    @property
225    def severity(self):
226        return _clang_getDiagnosticSeverity(self)
227
228    @property
229    def location(self):
230        return _clang_getDiagnosticLocation(self)
231
232    @property
233    def spelling(self):
234        return _clang_getDiagnosticSpelling(self)
235
236    @property
237    def ranges(self):
238        class RangeIterator:
239            def __init__(self, diag):
240                self.diag = diag
241
242            def __len__(self):
243                return int(_clang_getDiagnosticNumRanges(self.diag))
244
245            def __getitem__(self, key):
246                if (key >= len(self)):
247                    raise IndexError
248                return _clang_getDiagnosticRange(self.diag, key)
249
250        return RangeIterator(self)
251
252    @property
253    def fixits(self):
254        class FixItIterator:
255            def __init__(self, diag):
256                self.diag = diag
257
258            def __len__(self):
259                return int(_clang_getDiagnosticNumFixIts(self.diag))
260
261            def __getitem__(self, key):
262                range = SourceRange()
263                value = _clang_getDiagnosticFixIt(self.diag, key, byref(range))
264                if len(value) == 0:
265                    raise IndexError
266
267                return FixIt(range, value)
268
269        return FixItIterator(self)
270
271    @property
272    def category_number(self):
273        """The category number for this diagnostic."""
274        return _clang_getDiagnosticCategory(self)
275
276    @property
277    def category_name(self):
278        """The string name of the category for this diagnostic."""
279        return _clang_getDiagnosticCategoryName(self.category_number)
280
281    @property
282    def option(self):
283        """The command-line option that enables this diagnostic."""
284        return _clang_getDiagnosticOption(self, None)
285
286    @property
287    def disable_option(self):
288        """The command-line option that disables this diagnostic."""
289        disable = _CXString()
290        _clang_getDiagnosticOption(self, byref(disable))
291
292        return _CXString_getCString(disable)
293
294    def __repr__(self):
295        return "<Diagnostic severity %r, location %r, spelling %r>" % (
296            self.severity, self.location, self.spelling)
297
298    def from_param(self):
299      return self.ptr
300
301class FixIt(object):
302    """
303    A FixIt represents a transformation to be applied to the source to
304    "fix-it". The fix-it shouldbe applied by replacing the given source range
305    with the given value.
306    """
307
308    def __init__(self, range, value):
309        self.range = range
310        self.value = value
311
312    def __repr__(self):
313        return "<FixIt range %r, value %r>" % (self.range, self.value)
314
315### Cursor Kinds ###
316
317class CursorKind(object):
318    """
319    A CursorKind describes the kind of entity that a cursor points to.
320    """
321
322    # The unique kind objects, indexed by id.
323    _kinds = []
324    _name_map = None
325
326    def __init__(self, value):
327        if value >= len(CursorKind._kinds):
328            CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1)
329        if CursorKind._kinds[value] is not None:
330            raise ValueError,'CursorKind already loaded'
331        self.value = value
332        CursorKind._kinds[value] = self
333        CursorKind._name_map = None
334
335    def from_param(self):
336        return self.value
337
338    @property
339    def name(self):
340        """Get the enumeration name of this cursor kind."""
341        if self._name_map is None:
342            self._name_map = {}
343            for key,value in CursorKind.__dict__.items():
344                if isinstance(value,CursorKind):
345                    self._name_map[value] = key
346        return self._name_map[self]
347
348    @staticmethod
349    def from_id(id):
350        if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None:
351            raise ValueError,'Unknown cursor kind'
352        return CursorKind._kinds[id]
353
354    @staticmethod
355    def get_all_kinds():
356        """Return all CursorKind enumeration instances."""
357        return filter(None, CursorKind._kinds)
358
359    def is_declaration(self):
360        """Test if this is a declaration kind."""
361        return CursorKind_is_decl(self)
362
363    def is_reference(self):
364        """Test if this is a reference kind."""
365        return CursorKind_is_ref(self)
366
367    def is_expression(self):
368        """Test if this is an expression kind."""
369        return CursorKind_is_expr(self)
370
371    def is_statement(self):
372        """Test if this is a statement kind."""
373        return CursorKind_is_stmt(self)
374
375    def is_attribute(self):
376        """Test if this is an attribute kind."""
377        return CursorKind_is_attribute(self)
378
379    def is_invalid(self):
380        """Test if this is an invalid kind."""
381        return CursorKind_is_inv(self)
382
383    def is_translation_unit(self):
384        """Test if this is a translation unit kind."""
385        return CursorKind_is_translation_unit(self)
386
387    def is_preprocessing(self):
388        """Test if this is a preprocessing kind."""
389        return CursorKind_is_preprocessing(self)
390
391    def is_unexposed(self):
392        """Test if this is an unexposed kind."""
393        return CursorKind_is_unexposed(self)
394
395    def __repr__(self):
396        return 'CursorKind.%s' % (self.name,)
397
398# FIXME: Is there a nicer way to expose this enumeration? We could potentially
399# represent the nested structure, or even build a class hierarchy. The main
400# things we want for sure are (a) simple external access to kinds, (b) a place
401# to hang a description and name, (c) easy to keep in sync with Index.h.
402
403###
404# Declaration Kinds
405
406# A declaration whose specific kind is not exposed via this interface.
407#
408# Unexposed declarations have the same operations as any other kind of
409# declaration; one can extract their location information, spelling, find their
410# definitions, etc. However, the specific kind of the declaration is not
411# reported.
412CursorKind.UNEXPOSED_DECL = CursorKind(1)
413
414# A C or C++ struct.
415CursorKind.STRUCT_DECL = CursorKind(2)
416
417# A C or C++ union.
418CursorKind.UNION_DECL = CursorKind(3)
419
420# A C++ class.
421CursorKind.CLASS_DECL = CursorKind(4)
422
423# An enumeration.
424CursorKind.ENUM_DECL = CursorKind(5)
425
426# A field (in C) or non-static data member (in C++) in a struct, union, or C++
427# class.
428CursorKind.FIELD_DECL = CursorKind(6)
429
430# An enumerator constant.
431CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
432
433# A function.
434CursorKind.FUNCTION_DECL = CursorKind(8)
435
436# A variable.
437CursorKind.VAR_DECL = CursorKind(9)
438
439# A function or method parameter.
440CursorKind.PARM_DECL = CursorKind(10)
441
442# An Objective-C @interface.
443CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
444
445# An Objective-C @interface for a category.
446CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
447
448# An Objective-C @protocol declaration.
449CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
450
451# An Objective-C @property declaration.
452CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
453
454# An Objective-C instance variable.
455CursorKind.OBJC_IVAR_DECL = CursorKind(15)
456
457# An Objective-C instance method.
458CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
459
460# An Objective-C class method.
461CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
462
463# An Objective-C @implementation.
464CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
465
466# An Objective-C @implementation for a category.
467CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
468
469# A typedef.
470CursorKind.TYPEDEF_DECL = CursorKind(20)
471
472# A C++ class method.
473CursorKind.CXX_METHOD = CursorKind(21)
474
475# A C++ namespace.
476CursorKind.NAMESPACE = CursorKind(22)
477
478# A linkage specification, e.g. 'extern "C"'.
479CursorKind.LINKAGE_SPEC = CursorKind(23)
480
481# A C++ constructor.
482CursorKind.CONSTRUCTOR = CursorKind(24)
483
484# A C++ destructor.
485CursorKind.DESTRUCTOR = CursorKind(25)
486
487# A C++ conversion function.
488CursorKind.CONVERSION_FUNCTION = CursorKind(26)
489
490# A C++ template type parameter
491CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
492
493# A C++ non-type template paramater.
494CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
495
496# A C++ template template parameter.
497CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29)
498
499# A C++ function template.
500CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
501
502# A C++ class template.
503CursorKind.CLASS_TEMPLATE = CursorKind(31)
504
505# A C++ class template partial specialization.
506CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
507
508# A C++ namespace alias declaration.
509CursorKind.NAMESPACE_ALIAS = CursorKind(33)
510
511# A C++ using directive
512CursorKind.USING_DIRECTIVE = CursorKind(34)
513
514# A C++ using declaration
515CursorKind.USING_DECLARATION = CursorKind(35)
516
517# A Type alias decl.
518CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
519
520# A Objective-C synthesize decl
521CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
522
523# A Objective-C dynamic decl
524CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
525
526# A C++ access specifier decl.
527CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
528
529
530###
531# Reference Kinds
532
533CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
534CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
535CursorKind.OBJC_CLASS_REF = CursorKind(42)
536
537# A reference to a type declaration.
538#
539# A type reference occurs anywhere where a type is named but not
540# declared. For example, given:
541#   typedef unsigned size_type;
542#   size_type size;
543#
544# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
545# while the type of the variable "size" is referenced. The cursor
546# referenced by the type of size is the typedef for size_type.
547CursorKind.TYPE_REF = CursorKind(43)
548CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
549
550# A reference to a class template, function template, template
551# template parameter, or class template partial specialization.
552CursorKind.TEMPLATE_REF = CursorKind(45)
553
554# A reference to a namespace or namepsace alias.
555CursorKind.NAMESPACE_REF = CursorKind(46)
556
557# A reference to a member of a struct, union, or class that occurs in
558# some non-expression context, e.g., a designated initializer.
559CursorKind.MEMBER_REF = CursorKind(47)
560
561# A reference to a labeled statement.
562CursorKind.LABEL_REF = CursorKind(48)
563
564# A reference toa a set of overloaded functions or function templates
565# that has not yet been resolved to a specific function or function template.
566CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
567
568###
569# Invalid/Error Kinds
570
571CursorKind.INVALID_FILE = CursorKind(70)
572CursorKind.NO_DECL_FOUND = CursorKind(71)
573CursorKind.NOT_IMPLEMENTED = CursorKind(72)
574CursorKind.INVALID_CODE = CursorKind(73)
575
576###
577# Expression Kinds
578
579# An expression whose specific kind is not exposed via this interface.
580#
581# Unexposed expressions have the same operations as any other kind of
582# expression; one can extract their location information, spelling, children,
583# etc. However, the specific kind of the expression is not reported.
584CursorKind.UNEXPOSED_EXPR = CursorKind(100)
585
586# An expression that refers to some value declaration, such as a function,
587# varible, or enumerator.
588CursorKind.DECL_REF_EXPR = CursorKind(101)
589
590# An expression that refers to a member of a struct, union, class, Objective-C
591# class, etc.
592CursorKind.MEMBER_REF_EXPR = CursorKind(102)
593
594# An expression that calls a function.
595CursorKind.CALL_EXPR = CursorKind(103)
596
597# An expression that sends a message to an Objective-C object or class.
598CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
599
600# An expression that represents a block literal.
601CursorKind.BLOCK_EXPR = CursorKind(105)
602
603# An integer literal.
604CursorKind.INTEGER_LITERAL = CursorKind(106)
605
606# A floating point number literal.
607CursorKind.FLOATING_LITERAL = CursorKind(107)
608
609# An imaginary number literal.
610CursorKind.IMAGINARY_LITERAL = CursorKind(108)
611
612# A string literal.
613CursorKind.STRING_LITERAL = CursorKind(109)
614
615# A character literal.
616CursorKind.CHARACTER_LITERAL = CursorKind(110)
617
618# A parenthesized expression, e.g. "(1)".
619#
620# This AST node is only formed if full location information is requested.
621CursorKind.PAREN_EXPR = CursorKind(111)
622
623# This represents the unary-expression's (except sizeof and
624# alignof).
625CursorKind.UNARY_OPERATOR = CursorKind(112)
626
627# [C99 6.5.2.1] Array Subscripting.
628CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
629
630# A builtin binary operation expression such as "x + y" or
631# "x <= y".
632CursorKind.BINARY_OPERATOR = CursorKind(114)
633
634# Compound assignment such as "+=".
635CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
636
637# The ?: ternary operator.
638CursorKind.CONDITONAL_OPERATOR = CursorKind(116)
639
640# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
641# (C++ [expr.cast]), which uses the syntax (Type)expr.
642#
643# For example: (int)f.
644CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
645
646# [C99 6.5.2.5]
647CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
648
649# Describes an C or C++ initializer list.
650CursorKind.INIT_LIST_EXPR = CursorKind(119)
651
652# The GNU address of label extension, representing &&label.
653CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
654
655# This is the GNU Statement Expression extension: ({int X=4; X;})
656CursorKind.StmtExpr = CursorKind(121)
657
658# Represents a C11 generic selection.
659CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
660
661# Implements the GNU __null extension, which is a name for a null
662# pointer constant that has integral type (e.g., int or long) and is the same
663# size and alignment as a pointer.
664#
665# The __null extension is typically only used by system headers, which define
666# NULL as __null in C++ rather than using 0 (which is an integer that may not
667# match the size of a pointer).
668CursorKind.GNU_NULL_EXPR = CursorKind(123)
669
670# C++'s static_cast<> expression.
671CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
672
673# C++'s dynamic_cast<> expression.
674CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
675
676# C++'s reinterpret_cast<> expression.
677CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
678
679# C++'s const_cast<> expression.
680CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
681
682# Represents an explicit C++ type conversion that uses "functional"
683# notion (C++ [expr.type.conv]).
684#
685# Example:
686# \code
687#   x = int(0.5);
688# \endcode
689CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
690
691# A C++ typeid expression (C++ [expr.typeid]).
692CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
693
694# [C++ 2.13.5] C++ Boolean Literal.
695CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
696
697# [C++0x 2.14.7] C++ Pointer Literal.
698CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
699
700# Represents the "this" expression in C++
701CursorKind.CXX_THIS_EXPR = CursorKind(132)
702
703# [C++ 15] C++ Throw Expression.
704#
705# This handles 'throw' and 'throw' assignment-expression. When
706# assignment-expression isn't present, Op will be null.
707CursorKind.CXX_THROW_EXPR = CursorKind(133)
708
709# A new expression for memory allocation and constructor calls, e.g:
710# "new CXXNewExpr(foo)".
711CursorKind.CXX_NEW_EXPR = CursorKind(134)
712
713# A delete expression for memory deallocation and destructor calls,
714# e.g. "delete[] pArray".
715CursorKind.CXX_DELETE_EXPR = CursorKind(135)
716
717# Represents a unary expression.
718CursorKind.CXX_UNARY_EXPR = CursorKind(136)
719
720# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
721CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
722
723# ObjCEncodeExpr, used for in Objective-C.
724CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
725
726# ObjCSelectorExpr used for in Objective-C.
727CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
728
729# Objective-C's protocol expression.
730CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
731
732# An Objective-C "bridged" cast expression, which casts between
733# Objective-C pointers and C pointers, transferring ownership in the process.
734#
735# \code
736#   NSString *str = (__bridge_transfer NSString *)CFCreateString();
737# \endcode
738CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
739
740# Represents a C++0x pack expansion that produces a sequence of
741# expressions.
742#
743# A pack expansion expression contains a pattern (which itself is an
744# expression) followed by an ellipsis. For example:
745CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
746
747# Represents an expression that computes the length of a parameter
748# pack.
749CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
750
751# A statement whose specific kind is not exposed via this interface.
752#
753# Unexposed statements have the same operations as any other kind of statement;
754# one can extract their location information, spelling, children, etc. However,
755# the specific kind of the statement is not reported.
756CursorKind.UNEXPOSED_STMT = CursorKind(200)
757
758# A labelled statement in a function.
759CursorKind.LABEL_STMT = CursorKind(201)
760
761# A compound statement
762CursorKind.COMPOUND_STMT = CursorKind(202)
763
764# A case statement.
765CursorKind.CASE_STMT = CursorKind(203)
766
767# A default statement.
768CursorKind.DEFAULT_STMT = CursorKind(204)
769
770# An if statement.
771CursorKind.IF_STMT = CursorKind(205)
772
773# A switch statement.
774CursorKind.SWITCH_STMT = CursorKind(206)
775
776# A while statement.
777CursorKind.WHILE_STMT = CursorKind(207)
778
779# A do statement.
780CursorKind.DO_STMT = CursorKind(208)
781
782# A for statement.
783CursorKind.FOR_STMT = CursorKind(209)
784
785# A goto statement.
786CursorKind.GOTO_STMT = CursorKind(210)
787
788# An indirect goto statement.
789CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
790
791# A continue statement.
792CursorKind.CONTINUE_STMT = CursorKind(212)
793
794# A break statement.
795CursorKind.BREAK_STMT = CursorKind(213)
796
797# A return statement.
798CursorKind.RETURN_STMT = CursorKind(214)
799
800# A GNU-style inline assembler statement.
801CursorKind.ASM_STMT = CursorKind(215)
802
803# Objective-C's overall @try-@catch-@finally statement.
804CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
805
806# Objective-C's @catch statement.
807CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
808
809# Objective-C's @finally statement.
810CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
811
812# Objective-C's @throw statement.
813CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
814
815# Objective-C's @synchronized statement.
816CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
817
818# Objective-C's autorealease pool statement.
819CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
820
821# Objective-C's for collection statement.
822CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
823
824# C++'s catch statement.
825CursorKind.CXX_CATCH_STMT = CursorKind(223)
826
827# C++'s try statement.
828CursorKind.CXX_TRY_STMT = CursorKind(224)
829
830# C++'s for (* : *) statement.
831CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
832
833# Windows Structured Exception Handling's try statement.
834CursorKind.SEH_TRY_STMT = CursorKind(226)
835
836# Windows Structured Exception Handling's except statement.
837CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
838
839# Windows Structured Exception Handling's finally statement.
840CursorKind.SEH_FINALLY_STMT = CursorKind(228)
841
842# The null statement.
843CursorKind.NULL_STMT = CursorKind(230)
844
845# Adaptor class for mixing declarations with statements and expressions.
846CursorKind.DECL_STMT = CursorKind(231)
847
848###
849# Other Kinds
850
851# Cursor that represents the translation unit itself.
852#
853# The translation unit cursor exists primarily to act as the root cursor for
854# traversing the contents of a translation unit.
855CursorKind.TRANSLATION_UNIT = CursorKind(300)
856
857###
858# Attributes
859
860# An attribute whoe specific kind is note exposed via this interface
861CursorKind.UNEXPOSED_ATTR = CursorKind(400)
862
863CursorKind.IB_ACTION_ATTR = CursorKind(401)
864CursorKind.IB_OUTLET_ATTR = CursorKind(402)
865CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
866
867CursorKind.CXX_FINAL_ATTR = CursorKind(404)
868CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
869CursorKind.ANNOTATE_ATTR = CursorKind(406)
870CursorKind.ASM_LABEL_ATTR = CursorKind(407)
871
872###
873# Preprocessing
874CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
875CursorKind.MACRO_DEFINITION = CursorKind(501)
876CursorKind.MACRO_INSTANTIATION = CursorKind(502)
877CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
878
879### Cursors ###
880
881class Cursor(Structure):
882    """
883    The Cursor class represents a reference to an element within the AST. It
884    acts as a kind of iterator.
885    """
886    _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
887
888    @staticmethod
889    def from_location(tu, location):
890        return Cursor_get(tu, location)
891
892    def __eq__(self, other):
893        return Cursor_eq(self, other)
894
895    def __ne__(self, other):
896        return not self.__eq__(other)
897
898    def is_definition(self):
899        """
900        Returns true if the declaration pointed at by the cursor is also a
901        definition of that entity.
902        """
903        return Cursor_is_def(self)
904
905    def get_definition(self):
906        """
907        If the cursor is a reference to a declaration or a declaration of
908        some entity, return a cursor that points to the definition of that
909        entity.
910        """
911        # TODO: Should probably check that this is either a reference or
912        # declaration prior to issuing the lookup.
913        return Cursor_def(self)
914
915    def get_usr(self):
916        """Return the Unified Symbol Resultion (USR) for the entity referenced
917        by the given cursor (or None).
918
919        A Unified Symbol Resolution (USR) is a string that identifies a
920        particular entity (function, class, variable, etc.) within a
921        program. USRs can be compared across translation units to determine,
922        e.g., when references in one translation refer to an entity defined in
923        another translation unit."""
924        return Cursor_usr(self)
925
926    @property
927    def kind(self):
928        """Return the kind of this cursor."""
929        return CursorKind.from_id(self._kind_id)
930
931    @property
932    def spelling(self):
933        """Return the spelling of the entity pointed at by the cursor."""
934        if not self.kind.is_declaration():
935            # FIXME: clang_getCursorSpelling should be fixed to not assert on
936            # this, for consistency with clang_getCursorUSR.
937            return None
938        if not hasattr(self, '_spelling'):
939            self._spelling = Cursor_spelling(self)
940        return self._spelling
941
942    @property
943    def displayname(self):
944        """
945        Return the display name for the entity referenced by this cursor.
946
947        The display name contains extra information that helps identify the cursor,
948        such as the parameters of a function or template or the arguments of a
949        class template specialization.
950        """
951        if not hasattr(self, '_displayname'):
952            self._displayname = Cursor_displayname(self)
953        return self._displayname
954
955    @property
956    def location(self):
957        """
958        Return the source location (the starting character) of the entity
959        pointed at by the cursor.
960        """
961        if not hasattr(self, '_loc'):
962            self._loc = Cursor_loc(self)
963        return self._loc
964
965    @property
966    def extent(self):
967        """
968        Return the source range (the range of text) occupied by the entity
969        pointed at by the cursor.
970        """
971        if not hasattr(self, '_extent'):
972            self._extent = Cursor_extent(self)
973        return self._extent
974
975    @property
976    def type(self):
977        """
978        Retrieve the Type (if any) of the entity pointed at by the cursor.
979        """
980        if not hasattr(self, '_type'):
981            self._type = Cursor_type(self)
982        return self._type
983
984    @property
985    def underlying_typedef_type(self):
986        """Return the underlying type of a typedef declaration.
987
988        Returns a Type for the typedef this cursor is a declaration for. If
989        the current cursor is not a typedef, this raises.
990        """
991        if not hasattr(self, '_underlying_type'):
992            assert self.kind.is_declaration()
993            self._underlying_type = Cursor_underlying_type(self)
994
995        return self._underlying_type
996
997    @property
998    def enum_type(self):
999        """Return the integer type of an enum declaration.
1000
1001        Returns a Type corresponding to an integer. If the cursor is not for an
1002        enum, this raises.
1003        """
1004        if not hasattr(self, '_enum_type'):
1005            assert self.kind == CursorKind.ENUM_DECL
1006            self._enum_type = Cursor_enum_type(self)
1007
1008        return self._enum_type
1009
1010    @property
1011    def enum_value(self):
1012        """Return the value of an enum constant."""
1013        if not hasattr(self, '_enum_value'):
1014            assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1015            # Figure out the underlying type of the enum to know if it
1016            # is a signed or unsigned quantity.
1017            underlying_type = self.type
1018            if underlying_type.kind == TypeKind.ENUM:
1019                underlying_type = underlying_type.get_declaration().enum_type
1020            if underlying_type.kind in (TypeKind.CHAR_U,
1021                                        TypeKind.UCHAR,
1022                                        TypeKind.CHAR16,
1023                                        TypeKind.CHAR32,
1024                                        TypeKind.USHORT,
1025                                        TypeKind.UINT,
1026                                        TypeKind.ULONG,
1027                                        TypeKind.ULONGLONG,
1028                                        TypeKind.UINT128):
1029                self._enum_value = Cursor_enum_const_decl_unsigned(self)
1030            else:
1031                self._enum_value = Cursor_enum_const_decl(self)
1032        return self._enum_value
1033
1034    @property
1035    def objc_type_encoding(self):
1036        """Return the Objective-C type encoding as a str."""
1037        if not hasattr(self, '_objc_type_encoding'):
1038            self._objc_type_encoding = Cursor_objc_type_encoding(self)
1039
1040        return self._objc_type_encoding
1041
1042    @property
1043    def hash(self):
1044        """Returns a hash of the cursor as an int."""
1045        if not hasattr(self, '_hash'):
1046            self._hash = Cursor_hash(self)
1047
1048        return self._hash
1049
1050    def get_children(self):
1051        """Return an iterator for accessing the children of this cursor."""
1052
1053        # FIXME: Expose iteration from CIndex, PR6125.
1054        def visitor(child, parent, children):
1055            # FIXME: Document this assertion in API.
1056            # FIXME: There should just be an isNull method.
1057            assert child != Cursor_null()
1058            children.append(child)
1059            return 1 # continue
1060        children = []
1061        Cursor_visit(self, Cursor_visit_callback(visitor), children)
1062        return iter(children)
1063
1064    @staticmethod
1065    def from_result(res, fn, args):
1066        assert isinstance(res, Cursor)
1067        # FIXME: There should just be an isNull method.
1068        if res == Cursor_null():
1069            return None
1070        return res
1071
1072
1073### Type Kinds ###
1074
1075class TypeKind(object):
1076    """
1077    Describes the kind of type.
1078    """
1079
1080    # The unique kind objects, indexed by id.
1081    _kinds = []
1082    _name_map = None
1083
1084    def __init__(self, value):
1085        if value >= len(TypeKind._kinds):
1086            TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
1087        if TypeKind._kinds[value] is not None:
1088            raise ValueError,'TypeKind already loaded'
1089        self.value = value
1090        TypeKind._kinds[value] = self
1091        TypeKind._name_map = None
1092
1093    def from_param(self):
1094        return self.value
1095
1096    @property
1097    def name(self):
1098        """Get the enumeration name of this cursor kind."""
1099        if self._name_map is None:
1100            self._name_map = {}
1101            for key,value in TypeKind.__dict__.items():
1102                if isinstance(value,TypeKind):
1103                    self._name_map[value] = key
1104        return self._name_map[self]
1105
1106    @property
1107    def spelling(self):
1108        """Retrieve the spelling of this TypeKind."""
1109        return TypeKind_spelling(self.value)
1110
1111    @staticmethod
1112    def from_id(id):
1113        if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
1114            raise ValueError,'Unknown type kind %d' % id
1115        return TypeKind._kinds[id]
1116
1117    def __repr__(self):
1118        return 'TypeKind.%s' % (self.name,)
1119
1120TypeKind_spelling = lib.clang_getTypeKindSpelling
1121TypeKind_spelling.argtypes = [c_uint]
1122TypeKind_spelling.restype = _CXString
1123TypeKind_spelling.errcheck = _CXString.from_result
1124
1125
1126TypeKind.INVALID = TypeKind(0)
1127TypeKind.UNEXPOSED = TypeKind(1)
1128TypeKind.VOID = TypeKind(2)
1129TypeKind.BOOL = TypeKind(3)
1130TypeKind.CHAR_U = TypeKind(4)
1131TypeKind.UCHAR = TypeKind(5)
1132TypeKind.CHAR16 = TypeKind(6)
1133TypeKind.CHAR32 = TypeKind(7)
1134TypeKind.USHORT = TypeKind(8)
1135TypeKind.UINT = TypeKind(9)
1136TypeKind.ULONG = TypeKind(10)
1137TypeKind.ULONGLONG = TypeKind(11)
1138TypeKind.UINT128 = TypeKind(12)
1139TypeKind.CHAR_S = TypeKind(13)
1140TypeKind.SCHAR = TypeKind(14)
1141TypeKind.WCHAR = TypeKind(15)
1142TypeKind.SHORT = TypeKind(16)
1143TypeKind.INT = TypeKind(17)
1144TypeKind.LONG = TypeKind(18)
1145TypeKind.LONGLONG = TypeKind(19)
1146TypeKind.INT128 = TypeKind(20)
1147TypeKind.FLOAT = TypeKind(21)
1148TypeKind.DOUBLE = TypeKind(22)
1149TypeKind.LONGDOUBLE = TypeKind(23)
1150TypeKind.NULLPTR = TypeKind(24)
1151TypeKind.OVERLOAD = TypeKind(25)
1152TypeKind.DEPENDENT = TypeKind(26)
1153TypeKind.OBJCID = TypeKind(27)
1154TypeKind.OBJCCLASS = TypeKind(28)
1155TypeKind.OBJCSEL = TypeKind(29)
1156TypeKind.COMPLEX = TypeKind(100)
1157TypeKind.POINTER = TypeKind(101)
1158TypeKind.BLOCKPOINTER = TypeKind(102)
1159TypeKind.LVALUEREFERENCE = TypeKind(103)
1160TypeKind.RVALUEREFERENCE = TypeKind(104)
1161TypeKind.RECORD = TypeKind(105)
1162TypeKind.ENUM = TypeKind(106)
1163TypeKind.TYPEDEF = TypeKind(107)
1164TypeKind.OBJCINTERFACE = TypeKind(108)
1165TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1166TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1167TypeKind.FUNCTIONPROTO = TypeKind(111)
1168TypeKind.CONSTANTARRAY = TypeKind(112)
1169TypeKind.VECTOR = TypeKind(113)
1170
1171class Type(Structure):
1172    """
1173    The type of an element in the abstract syntax tree.
1174    """
1175    _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1176
1177    @property
1178    def kind(self):
1179        """Return the kind of this type."""
1180        return TypeKind.from_id(self._kind_id)
1181
1182    def argument_types(self):
1183        """Retrieve a container for the non-variadic arguments for this type.
1184
1185        The returned object is iterable and indexable. Each item in the
1186        container is a Type instance.
1187        """
1188        class ArgumentsIterator(collections.Sequence):
1189            def __init__(self, parent):
1190                self.parent = parent
1191                self.length = None
1192
1193            def __len__(self):
1194                if self.length is None:
1195                    self.length = Type_get_num_arg_types(self.parent)
1196
1197                return self.length
1198
1199            def __getitem__(self, key):
1200                # FIXME Support slice objects.
1201                if not isinstance(key, int):
1202                    raise TypeError("Must supply a non-negative int.")
1203
1204                if key < 0:
1205                    raise IndexError("Only non-negative indexes are accepted.")
1206
1207                if key >= len(self):
1208                    raise IndexError("Index greater than container length: "
1209                                     "%d > %d" % ( key, len(self) ))
1210
1211                result = Type_get_arg_type(self.parent, key)
1212                if result.kind == TypeKind.INVALID:
1213                    raise IndexError("Argument could not be retrieved.")
1214
1215                return result
1216
1217        assert self.kind == TypeKind.FUNCTIONPROTO
1218        return ArgumentsIterator(self)
1219
1220    @property
1221    def element_type(self):
1222        """Retrieve the Type of elements within this Type.
1223
1224        If accessed on a type that is not an array, complex, or vector type, an
1225        exception will be raised.
1226        """
1227        result = Type_get_element_type(self)
1228        if result.kind == TypeKind.INVALID:
1229            raise Exception('Element type not available on this type.')
1230
1231        return result
1232
1233    @property
1234    def element_count(self):
1235        """Retrieve the number of elements in this type.
1236
1237        Returns an int.
1238
1239        If the Type is not an array or vector, this raises.
1240        """
1241        result = Type_get_num_elements(self)
1242        if result < 0:
1243            raise Exception('Type does not have elements.')
1244
1245        return result
1246
1247    @staticmethod
1248    def from_result(res, fn, args):
1249        assert isinstance(res, Type)
1250        return res
1251
1252    def get_canonical(self):
1253        """
1254        Return the canonical type for a Type.
1255
1256        Clang's type system explicitly models typedefs and all the
1257        ways a specific type can be represented.  The canonical type
1258        is the underlying type with all the "sugar" removed.  For
1259        example, if 'T' is a typedef for 'int', the canonical type for
1260        'T' would be 'int'.
1261        """
1262        return Type_get_canonical(self)
1263
1264    def is_const_qualified(self):
1265        """Determine whether a Type has the "const" qualifier set.
1266
1267        This does not look through typedefs that may have added "const"
1268        at a different level.
1269        """
1270        return Type_is_const_qualified(self)
1271
1272    def is_volatile_qualified(self):
1273        """Determine whether a Type has the "volatile" qualifier set.
1274
1275        This does not look through typedefs that may have added "volatile"
1276        at a different level.
1277        """
1278        return Type_is_volatile_qualified(self)
1279
1280    def is_restrict_qualified(self):
1281        """Determine whether a Type has the "restrict" qualifier set.
1282
1283        This does not look through typedefs that may have added "restrict" at
1284        a different level.
1285        """
1286        return Type_is_restrict_qualified(self)
1287
1288    def is_function_variadic(self):
1289        """Determine whether this function Type is a variadic function type."""
1290        assert self.kind == TypeKind.FUNCTIONPROTO
1291
1292        return Type_is_variadic(self)
1293
1294    def is_pod(self):
1295        """Determine whether this Type represents plain old data (POD)."""
1296        return Type_is_pod(self)
1297
1298    def get_pointee(self):
1299        """
1300        For pointer types, returns the type of the pointee.
1301        """
1302        return Type_get_pointee(self)
1303
1304    def get_declaration(self):
1305        """
1306        Return the cursor for the declaration of the given type.
1307        """
1308        return Type_get_declaration(self)
1309
1310    def get_result(self):
1311        """
1312        Retrieve the result type associated with a function type.
1313        """
1314        return Type_get_result(self)
1315
1316    def get_array_element_type(self):
1317        """
1318        Retrieve the type of the elements of the array type.
1319        """
1320        return Type_get_array_element(self)
1321
1322    def get_array_size(self):
1323        """
1324        Retrieve the size of the constant array.
1325        """
1326        return Type_get_array_size(self)
1327
1328    def __eq__(self, other):
1329        if type(other) != type(self):
1330            return False
1331
1332        return Type_equal(self, other)
1333
1334    def __ne__(self, other):
1335        return not self.__eq__(other)
1336
1337## CIndex Objects ##
1338
1339# CIndex objects (derived from ClangObject) are essentially lightweight
1340# wrappers attached to some underlying object, which is exposed via CIndex as
1341# a void*.
1342
1343class ClangObject(object):
1344    """
1345    A helper for Clang objects. This class helps act as an intermediary for
1346    the ctypes library and the Clang CIndex library.
1347    """
1348    def __init__(self, obj):
1349        assert isinstance(obj, c_object_p) and obj
1350        self.obj = self._as_parameter_ = obj
1351
1352    def from_param(self):
1353        return self._as_parameter_
1354
1355
1356class _CXUnsavedFile(Structure):
1357    """Helper for passing unsaved file arguments."""
1358    _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1359
1360## Diagnostic Conversion ##
1361
1362_clang_getNumDiagnostics = lib.clang_getNumDiagnostics
1363_clang_getNumDiagnostics.argtypes = [c_object_p]
1364_clang_getNumDiagnostics.restype = c_uint
1365
1366_clang_getDiagnostic = lib.clang_getDiagnostic
1367_clang_getDiagnostic.argtypes = [c_object_p, c_uint]
1368_clang_getDiagnostic.restype = c_object_p
1369
1370_clang_disposeDiagnostic = lib.clang_disposeDiagnostic
1371_clang_disposeDiagnostic.argtypes = [Diagnostic]
1372
1373_clang_getDiagnosticSeverity = lib.clang_getDiagnosticSeverity
1374_clang_getDiagnosticSeverity.argtypes = [Diagnostic]
1375_clang_getDiagnosticSeverity.restype = c_int
1376
1377_clang_getDiagnosticLocation = lib.clang_getDiagnosticLocation
1378_clang_getDiagnosticLocation.argtypes = [Diagnostic]
1379_clang_getDiagnosticLocation.restype = SourceLocation
1380
1381_clang_getDiagnosticSpelling = lib.clang_getDiagnosticSpelling
1382_clang_getDiagnosticSpelling.argtypes = [Diagnostic]
1383_clang_getDiagnosticSpelling.restype = _CXString
1384_clang_getDiagnosticSpelling.errcheck = _CXString.from_result
1385
1386_clang_getDiagnosticNumRanges = lib.clang_getDiagnosticNumRanges
1387_clang_getDiagnosticNumRanges.argtypes = [Diagnostic]
1388_clang_getDiagnosticNumRanges.restype = c_uint
1389
1390_clang_getDiagnosticRange = lib.clang_getDiagnosticRange
1391_clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint]
1392_clang_getDiagnosticRange.restype = SourceRange
1393
1394_clang_getDiagnosticNumFixIts = lib.clang_getDiagnosticNumFixIts
1395_clang_getDiagnosticNumFixIts.argtypes = [Diagnostic]
1396_clang_getDiagnosticNumFixIts.restype = c_uint
1397
1398_clang_getDiagnosticFixIt = lib.clang_getDiagnosticFixIt
1399_clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint, POINTER(SourceRange)]
1400_clang_getDiagnosticFixIt.restype = _CXString
1401_clang_getDiagnosticFixIt.errcheck = _CXString.from_result
1402
1403_clang_getDiagnosticCategory = lib.clang_getDiagnosticCategory
1404_clang_getDiagnosticCategory.argtypes = [Diagnostic]
1405_clang_getDiagnosticCategory.restype = c_uint
1406
1407_clang_getDiagnosticCategoryName = lib.clang_getDiagnosticCategoryName
1408_clang_getDiagnosticCategoryName.argtypes = [c_uint]
1409_clang_getDiagnosticCategoryName.restype = _CXString
1410_clang_getDiagnosticCategoryName.errcheck = _CXString.from_result
1411
1412_clang_getDiagnosticOption = lib.clang_getDiagnosticOption
1413_clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)]
1414_clang_getDiagnosticOption.restype = _CXString
1415_clang_getDiagnosticOption.errcheck = _CXString.from_result
1416
1417###
1418
1419class CompletionChunk:
1420    class Kind:
1421        def __init__(self, name):
1422            self.name = name
1423
1424        def __str__(self):
1425            return self.name
1426
1427        def __repr__(self):
1428            return "<ChunkKind: %s>" % self
1429
1430    def __init__(self, completionString, key):
1431        self.cs = completionString
1432        self.key = key
1433
1434    def __repr__(self):
1435        return "{'" + self.spelling + "', " + str(self.kind) + "}"
1436
1437    @property
1438    def spelling(self):
1439        return _clang_getCompletionChunkText(self.cs, self.key).spelling
1440
1441    @property
1442    def kind(self):
1443        res = _clang_getCompletionChunkKind(self.cs, self.key)
1444        return completionChunkKindMap[res]
1445
1446    @property
1447    def string(self):
1448        res = _clang_getCompletionChunkCompletionString(self.cs, self.key)
1449
1450        if (res):
1451          return CompletionString(res)
1452        else:
1453          None
1454
1455    def isKindOptional(self):
1456      return self.kind == completionChunkKindMap[0]
1457
1458    def isKindTypedText(self):
1459      return self.kind == completionChunkKindMap[1]
1460
1461    def isKindPlaceHolder(self):
1462      return self.kind == completionChunkKindMap[3]
1463
1464    def isKindInformative(self):
1465      return self.kind == completionChunkKindMap[4]
1466
1467    def isKindResultType(self):
1468      return self.kind == completionChunkKindMap[15]
1469
1470completionChunkKindMap = {
1471            0: CompletionChunk.Kind("Optional"),
1472            1: CompletionChunk.Kind("TypedText"),
1473            2: CompletionChunk.Kind("Text"),
1474            3: CompletionChunk.Kind("Placeholder"),
1475            4: CompletionChunk.Kind("Informative"),
1476            5: CompletionChunk.Kind("CurrentParameter"),
1477            6: CompletionChunk.Kind("LeftParen"),
1478            7: CompletionChunk.Kind("RightParen"),
1479            8: CompletionChunk.Kind("LeftBracket"),
1480            9: CompletionChunk.Kind("RightBracket"),
1481            10: CompletionChunk.Kind("LeftBrace"),
1482            11: CompletionChunk.Kind("RightBrace"),
1483            12: CompletionChunk.Kind("LeftAngle"),
1484            13: CompletionChunk.Kind("RightAngle"),
1485            14: CompletionChunk.Kind("Comma"),
1486            15: CompletionChunk.Kind("ResultType"),
1487            16: CompletionChunk.Kind("Colon"),
1488            17: CompletionChunk.Kind("SemiColon"),
1489            18: CompletionChunk.Kind("Equal"),
1490            19: CompletionChunk.Kind("HorizontalSpace"),
1491            20: CompletionChunk.Kind("VerticalSpace")}
1492
1493class CompletionString(ClangObject):
1494    class Availability:
1495        def __init__(self, name):
1496            self.name = name
1497
1498        def __str__(self):
1499            return self.name
1500
1501        def __repr__(self):
1502            return "<Availability: %s>" % self
1503
1504    def __len__(self):
1505        return _clang_getNumCompletionChunks(self.obj)
1506
1507    def __getitem__(self, key):
1508        if len(self) <= key:
1509            raise IndexError
1510        return CompletionChunk(self.obj, key)
1511
1512    @property
1513    def priority(self):
1514        return _clang_getCompletionPriority(self.obj)
1515
1516    @property
1517    def availability(self):
1518        res = _clang_getCompletionAvailability(self.obj)
1519        return availabilityKinds[res]
1520
1521    def __repr__(self):
1522        return " | ".join([str(a) for a in self]) \
1523               + " || Priority: " + str(self.priority) \
1524               + " || Availability: " + str(self.availability)
1525
1526availabilityKinds = {
1527            0: CompletionChunk.Kind("Available"),
1528            1: CompletionChunk.Kind("Deprecated"),
1529            2: CompletionChunk.Kind("NotAvailable")}
1530
1531class CodeCompletionResult(Structure):
1532    _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
1533
1534    def __repr__(self):
1535        return str(CompletionString(self.completionString))
1536
1537    @property
1538    def kind(self):
1539        return CursorKind.from_id(self.cursorKind)
1540
1541    @property
1542    def string(self):
1543        return CompletionString(self.completionString)
1544
1545class CCRStructure(Structure):
1546    _fields_ = [('results', POINTER(CodeCompletionResult)),
1547                ('numResults', c_int)]
1548
1549    def __len__(self):
1550        return self.numResults
1551
1552    def __getitem__(self, key):
1553        if len(self) <= key:
1554            raise IndexError
1555
1556        return self.results[key]
1557
1558class CodeCompletionResults(ClangObject):
1559    def __init__(self, ptr):
1560        assert isinstance(ptr, POINTER(CCRStructure)) and ptr
1561        self.ptr = self._as_parameter_ = ptr
1562
1563    def from_param(self):
1564        return self._as_parameter_
1565
1566    def __del__(self):
1567        CodeCompletionResults_dispose(self)
1568
1569    @property
1570    def results(self):
1571        return self.ptr.contents
1572
1573    @property
1574    def diagnostics(self):
1575        class DiagnosticsItr:
1576            def __init__(self, ccr):
1577                self.ccr= ccr
1578
1579            def __len__(self):
1580                return int(_clang_codeCompleteGetNumDiagnostics(self.ccr))
1581
1582            def __getitem__(self, key):
1583                return _clang_codeCompleteGetDiagnostic(self.ccr, key)
1584
1585        return DiagnosticsItr(self)
1586
1587
1588class Index(ClangObject):
1589    """
1590    The Index type provides the primary interface to the Clang CIndex library,
1591    primarily by providing an interface for reading and parsing translation
1592    units.
1593    """
1594
1595    @staticmethod
1596    def create(excludeDecls=False):
1597        """
1598        Create a new Index.
1599        Parameters:
1600        excludeDecls -- Exclude local declarations from translation units.
1601        """
1602        return Index(Index_create(excludeDecls, 0))
1603
1604    def __del__(self):
1605        Index_dispose(self)
1606
1607    def read(self, path):
1608        """Load the translation unit from the given AST file."""
1609        ptr = TranslationUnit_read(self, path)
1610        if ptr:
1611            return TranslationUnit(ptr)
1612        return None
1613
1614    def parse(self, path, args = [], unsaved_files = [], options = 0):
1615        """
1616        Load the translation unit from the given source code file by running
1617        clang and generating the AST before loading. Additional command line
1618        parameters can be passed to clang via the args parameter.
1619
1620        In-memory contents for files can be provided by passing a list of pairs
1621        to as unsaved_files, the first item should be the filenames to be mapped
1622        and the second should be the contents to be substituted for the
1623        file. The contents may be passed as strings or file objects.
1624        """
1625        arg_array = 0
1626        if len(args):
1627            arg_array = (c_char_p * len(args))(* args)
1628        unsaved_files_array = 0
1629        if len(unsaved_files):
1630            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
1631            for i,(name,value) in enumerate(unsaved_files):
1632                if not isinstance(value, str):
1633                    # FIXME: It would be great to support an efficient version
1634                    # of this, one day.
1635                    value = value.read()
1636                    print value
1637                if not isinstance(value, str):
1638                    raise TypeError,'Unexpected unsaved file contents.'
1639                unsaved_files_array[i].name = name
1640                unsaved_files_array[i].contents = value
1641                unsaved_files_array[i].length = len(value)
1642        ptr = TranslationUnit_parse(self, path, arg_array, len(args),
1643                                    unsaved_files_array, len(unsaved_files),
1644                                    options)
1645        if ptr:
1646            return TranslationUnit(ptr)
1647        return None
1648
1649
1650class TranslationUnit(ClangObject):
1651    """
1652    The TranslationUnit class represents a source code translation unit and
1653    provides read-only access to its top-level declarations.
1654    """
1655
1656    def __init__(self, ptr):
1657        ClangObject.__init__(self, ptr)
1658
1659    def __del__(self):
1660        TranslationUnit_dispose(self)
1661
1662    @property
1663    def cursor(self):
1664        """Retrieve the cursor that represents the given translation unit."""
1665        return TranslationUnit_cursor(self)
1666
1667    @property
1668    def spelling(self):
1669        """Get the original translation unit source file name."""
1670        return TranslationUnit_spelling(self)
1671
1672    def get_includes(self):
1673        """
1674        Return an iterable sequence of FileInclusion objects that describe the
1675        sequence of inclusions in a translation unit. The first object in
1676        this sequence is always the input file. Note that this method will not
1677        recursively iterate over header files included through precompiled
1678        headers.
1679        """
1680        def visitor(fobj, lptr, depth, includes):
1681            if depth > 0:
1682                loc = lptr.contents
1683                includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
1684
1685        # Automatically adapt CIndex/ctype pointers to python objects
1686        includes = []
1687        TranslationUnit_includes(self,
1688                                 TranslationUnit_includes_callback(visitor),
1689                                 includes)
1690        return iter(includes)
1691
1692    @property
1693    def diagnostics(self):
1694        """
1695        Return an iterable (and indexable) object containing the diagnostics.
1696        """
1697        class DiagIterator:
1698            def __init__(self, tu):
1699                self.tu = tu
1700
1701            def __len__(self):
1702                return int(_clang_getNumDiagnostics(self.tu))
1703
1704            def __getitem__(self, key):
1705                diag = _clang_getDiagnostic(self.tu, key)
1706                if not diag:
1707                    raise IndexError
1708                return Diagnostic(diag)
1709
1710        return DiagIterator(self)
1711
1712    def reparse(self, unsaved_files = [], options = 0):
1713        """
1714        Reparse an already parsed translation unit.
1715
1716        In-memory contents for files can be provided by passing a list of pairs
1717        as unsaved_files, the first items should be the filenames to be mapped
1718        and the second should be the contents to be substituted for the
1719        file. The contents may be passed as strings or file objects.
1720        """
1721        unsaved_files_array = 0
1722        if len(unsaved_files):
1723            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
1724            for i,(name,value) in enumerate(unsaved_files):
1725                if not isinstance(value, str):
1726                    # FIXME: It would be great to support an efficient version
1727                    # of this, one day.
1728                    value = value.read()
1729                    print value
1730                if not isinstance(value, str):
1731                    raise TypeError,'Unexpected unsaved file contents.'
1732                unsaved_files_array[i].name = name
1733                unsaved_files_array[i].contents = value
1734                unsaved_files_array[i].length = len(value)
1735        ptr = TranslationUnit_reparse(self, len(unsaved_files),
1736                                      unsaved_files_array,
1737                                      options)
1738    def codeComplete(self, path, line, column, unsaved_files = [], options = 0):
1739        """
1740        Code complete in this translation unit.
1741
1742        In-memory contents for files can be provided by passing a list of pairs
1743        as unsaved_files, the first items should be the filenames to be mapped
1744        and the second should be the contents to be substituted for the
1745        file. The contents may be passed as strings or file objects.
1746        """
1747        unsaved_files_array = 0
1748        if len(unsaved_files):
1749            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
1750            for i,(name,value) in enumerate(unsaved_files):
1751                if not isinstance(value, str):
1752                    # FIXME: It would be great to support an efficient version
1753                    # of this, one day.
1754                    value = value.read()
1755                    print value
1756                if not isinstance(value, str):
1757                    raise TypeError,'Unexpected unsaved file contents.'
1758                unsaved_files_array[i].name = name
1759                unsaved_files_array[i].contents = value
1760                unsaved_files_array[i].length = len(value)
1761        ptr = TranslationUnit_codeComplete(self, path,
1762                                           line, column,
1763                                           unsaved_files_array,
1764                                           len(unsaved_files),
1765                                           options)
1766        if ptr:
1767            return CodeCompletionResults(ptr)
1768        return None
1769
1770class File(ClangObject):
1771    """
1772    The File class represents a particular source file that is part of a
1773    translation unit.
1774    """
1775
1776    @staticmethod
1777    def from_name(translation_unit, file_name):
1778        """Retrieve a file handle within the given translation unit."""
1779        return File(File_getFile(translation_unit, file_name))
1780
1781    @property
1782    def name(self):
1783        """Return the complete file and path name of the file."""
1784        return _CXString_getCString(File_name(self))
1785
1786    @property
1787    def time(self):
1788        """Return the last modification time of the file."""
1789        return File_time(self)
1790
1791    def __str__(self):
1792        return self.name
1793
1794    def __repr__(self):
1795        return "<File: %s>" % (self.name)
1796
1797class FileInclusion(object):
1798    """
1799    The FileInclusion class represents the inclusion of one source file by
1800    another via a '#include' directive or as the input file for the translation
1801    unit. This class provides information about the included file, the including
1802    file, the location of the '#include' directive and the depth of the included
1803    file in the stack. Note that the input file has depth 0.
1804    """
1805
1806    def __init__(self, src, tgt, loc, depth):
1807        self.source = src
1808        self.include = tgt
1809        self.location = loc
1810        self.depth = depth
1811
1812    @property
1813    def is_input_file(self):
1814        """True if the included file is the input file."""
1815        return self.depth == 0
1816
1817# Additional Functions and Types
1818
1819# String Functions
1820_CXString_dispose = lib.clang_disposeString
1821_CXString_dispose.argtypes = [_CXString]
1822
1823_CXString_getCString = lib.clang_getCString
1824_CXString_getCString.argtypes = [_CXString]
1825_CXString_getCString.restype = c_char_p
1826
1827# Source Location Functions
1828SourceLocation_loc = lib.clang_getInstantiationLocation
1829SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_object_p),
1830                               POINTER(c_uint), POINTER(c_uint),
1831                               POINTER(c_uint)]
1832
1833SourceLocation_getLocation = lib.clang_getLocation
1834SourceLocation_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint]
1835SourceLocation_getLocation.restype = SourceLocation
1836
1837SourceLocation_equalLocations = lib.clang_equalLocations
1838SourceLocation_equalLocations.argtypes = [SourceLocation, SourceLocation]
1839SourceLocation_equalLocations.restype = bool
1840
1841# Source Range Functions
1842SourceRange_getRange = lib.clang_getRange
1843SourceRange_getRange.argtypes = [SourceLocation, SourceLocation]
1844SourceRange_getRange.restype = SourceRange
1845
1846SourceRange_start = lib.clang_getRangeStart
1847SourceRange_start.argtypes = [SourceRange]
1848SourceRange_start.restype = SourceLocation
1849
1850SourceRange_end = lib.clang_getRangeEnd
1851SourceRange_end.argtypes = [SourceRange]
1852SourceRange_end.restype = SourceLocation
1853
1854SourceRange_equalRanges = lib.clang_equalRanges
1855SourceRange_equalRanges.argtypes = [SourceRange, SourceRange]
1856SourceRange_equalRanges.restype = bool
1857
1858# CursorKind Functions
1859CursorKind_is_decl = lib.clang_isDeclaration
1860CursorKind_is_decl.argtypes = [CursorKind]
1861CursorKind_is_decl.restype = bool
1862
1863CursorKind_is_ref = lib.clang_isReference
1864CursorKind_is_ref.argtypes = [CursorKind]
1865CursorKind_is_ref.restype = bool
1866
1867CursorKind_is_expr = lib.clang_isExpression
1868CursorKind_is_expr.argtypes = [CursorKind]
1869CursorKind_is_expr.restype = bool
1870
1871CursorKind_is_stmt = lib.clang_isStatement
1872CursorKind_is_stmt.argtypes = [CursorKind]
1873CursorKind_is_stmt.restype = bool
1874
1875CursorKind_is_attribute = lib.clang_isAttribute
1876CursorKind_is_attribute.argtypes = [CursorKind]
1877CursorKind_is_attribute.restype = bool
1878
1879CursorKind_is_inv = lib.clang_isInvalid
1880CursorKind_is_inv.argtypes = [CursorKind]
1881CursorKind_is_inv.restype = bool
1882
1883CursorKind_is_translation_unit = lib.clang_isTranslationUnit
1884CursorKind_is_translation_unit.argtypes = [CursorKind]
1885CursorKind_is_translation_unit.restype = bool
1886
1887CursorKind_is_preprocessing = lib.clang_isPreprocessing
1888CursorKind_is_preprocessing.argtypes = [CursorKind]
1889CursorKind_is_preprocessing.restype = bool
1890
1891CursorKind_is_unexposed = lib.clang_isUnexposed
1892CursorKind_is_unexposed.argtypes = [CursorKind]
1893CursorKind_is_unexposed.restype = bool
1894
1895# Cursor Functions
1896# TODO: Implement this function
1897Cursor_get = lib.clang_getCursor
1898Cursor_get.argtypes = [TranslationUnit, SourceLocation]
1899Cursor_get.restype = Cursor
1900
1901Cursor_null = lib.clang_getNullCursor
1902Cursor_null.restype = Cursor
1903
1904Cursor_usr = lib.clang_getCursorUSR
1905Cursor_usr.argtypes = [Cursor]
1906Cursor_usr.restype = _CXString
1907Cursor_usr.errcheck = _CXString.from_result
1908
1909Cursor_is_def = lib.clang_isCursorDefinition
1910Cursor_is_def.argtypes = [Cursor]
1911Cursor_is_def.restype = bool
1912
1913Cursor_def = lib.clang_getCursorDefinition
1914Cursor_def.argtypes = [Cursor]
1915Cursor_def.restype = Cursor
1916Cursor_def.errcheck = Cursor.from_result
1917
1918Cursor_eq = lib.clang_equalCursors
1919Cursor_eq.argtypes = [Cursor, Cursor]
1920Cursor_eq.restype = bool
1921
1922Cursor_hash = lib.clang_hashCursor
1923Cursor_hash.argtypes = [Cursor]
1924Cursor_hash.restype = c_uint
1925
1926Cursor_spelling = lib.clang_getCursorSpelling
1927Cursor_spelling.argtypes = [Cursor]
1928Cursor_spelling.restype = _CXString
1929Cursor_spelling.errcheck = _CXString.from_result
1930
1931Cursor_displayname = lib.clang_getCursorDisplayName
1932Cursor_displayname.argtypes = [Cursor]
1933Cursor_displayname.restype = _CXString
1934Cursor_displayname.errcheck = _CXString.from_result
1935
1936Cursor_loc = lib.clang_getCursorLocation
1937Cursor_loc.argtypes = [Cursor]
1938Cursor_loc.restype = SourceLocation
1939
1940Cursor_extent = lib.clang_getCursorExtent
1941Cursor_extent.argtypes = [Cursor]
1942Cursor_extent.restype = SourceRange
1943
1944Cursor_ref = lib.clang_getCursorReferenced
1945Cursor_ref.argtypes = [Cursor]
1946Cursor_ref.restype = Cursor
1947Cursor_ref.errcheck = Cursor.from_result
1948
1949Cursor_type = lib.clang_getCursorType
1950Cursor_type.argtypes = [Cursor]
1951Cursor_type.restype = Type
1952Cursor_type.errcheck = Type.from_result
1953
1954Cursor_underlying_type = lib.clang_getTypedefDeclUnderlyingType
1955Cursor_underlying_type.argtypes = [Cursor]
1956Cursor_underlying_type.restype = Type
1957Cursor_underlying_type.errcheck = Type.from_result
1958
1959Cursor_enum_type = lib.clang_getEnumDeclIntegerType
1960Cursor_enum_type.argtypes = [Cursor]
1961Cursor_enum_type.restype = Type
1962Cursor_enum_type.errcheck = Type.from_result
1963
1964Cursor_enum_const_decl = lib.clang_getEnumConstantDeclValue
1965Cursor_enum_const_decl.argtypes = [Cursor]
1966Cursor_enum_const_decl.restype = c_longlong
1967
1968Cursor_enum_const_decl_unsigned = lib.clang_getEnumConstantDeclUnsignedValue
1969Cursor_enum_const_decl_unsigned.argtypes = [Cursor]
1970Cursor_enum_const_decl_unsigned.restype = c_ulonglong
1971
1972Cursor_objc_type_encoding = lib.clang_getDeclObjCTypeEncoding
1973Cursor_objc_type_encoding.argtypes = [Cursor]
1974Cursor_objc_type_encoding.restype = _CXString
1975Cursor_objc_type_encoding.errcheck = _CXString.from_result
1976
1977Cursor_visit_callback = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
1978Cursor_visit = lib.clang_visitChildren
1979Cursor_visit.argtypes = [Cursor, Cursor_visit_callback, py_object]
1980Cursor_visit.restype = c_uint
1981
1982# Type Functions
1983Type_get_canonical = lib.clang_getCanonicalType
1984Type_get_canonical.argtypes = [Type]
1985Type_get_canonical.restype = Type
1986Type_get_canonical.errcheck = Type.from_result
1987
1988Type_is_const_qualified = lib.clang_isConstQualifiedType
1989Type_is_const_qualified.argtypes = [Type]
1990Type_is_const_qualified.restype = bool
1991
1992Type_is_volatile_qualified = lib.clang_isVolatileQualifiedType
1993Type_is_volatile_qualified.argtypes = [Type]
1994Type_is_volatile_qualified.restype = bool
1995
1996Type_is_restrict_qualified = lib.clang_isRestrictQualifiedType
1997Type_is_restrict_qualified.argtypes = [Type]
1998Type_is_restrict_qualified.restype = bool
1999
2000Type_is_pod = lib.clang_isPODType
2001Type_is_pod.argtypes = [Type]
2002Type_is_pod.restype = bool
2003
2004Type_is_variadic = lib.clang_isFunctionTypeVariadic
2005Type_is_variadic.argtypes = [Type]
2006Type_is_variadic.restype = bool
2007
2008Type_get_pointee = lib.clang_getPointeeType
2009Type_get_pointee.argtypes = [Type]
2010Type_get_pointee.restype = Type
2011Type_get_pointee.errcheck = Type.from_result
2012
2013Type_get_declaration = lib.clang_getTypeDeclaration
2014Type_get_declaration.argtypes = [Type]
2015Type_get_declaration.restype = Cursor
2016Type_get_declaration.errcheck = Cursor.from_result
2017
2018Type_get_result = lib.clang_getResultType
2019Type_get_result.argtypes = [Type]
2020Type_get_result.restype = Type
2021Type_get_result.errcheck = Type.from_result
2022
2023Type_get_num_arg_types = lib.clang_getNumArgTypes
2024Type_get_num_arg_types.argtypes = [Type]
2025Type_get_num_arg_types.restype = c_uint
2026
2027Type_get_arg_type = lib.clang_getArgType
2028Type_get_arg_type.argtypes = [Type, c_uint]
2029Type_get_arg_type.restype = Type
2030Type_get_arg_type.errcheck = Type.from_result
2031Type_get_element_type = lib.clang_getElementType
2032
2033Type_get_element_type.argtypes = [Type]
2034Type_get_element_type.restype = Type
2035Type_get_element_type.errcheck = Type.from_result
2036
2037Type_get_num_elements = lib.clang_getNumElements
2038Type_get_num_elements.argtypes = [Type]
2039Type_get_num_elements.restype = c_longlong
2040
2041Type_get_array_element = lib.clang_getArrayElementType
2042Type_get_array_element.argtypes = [Type]
2043Type_get_array_element.restype = Type
2044Type_get_array_element.errcheck = Type.from_result
2045
2046Type_get_array_size = lib.clang_getArraySize
2047Type_get_array_size.argtype = [Type]
2048Type_get_array_size.restype = c_longlong
2049
2050Type_equal = lib.clang_equalTypes
2051Type_equal.argtypes = [Type, Type]
2052Type_equal.restype = bool
2053
2054# Index Functions
2055Index_create = lib.clang_createIndex
2056Index_create.argtypes = [c_int, c_int]
2057Index_create.restype = c_object_p
2058
2059Index_dispose = lib.clang_disposeIndex
2060Index_dispose.argtypes = [Index]
2061
2062# Translation Unit Functions
2063TranslationUnit_read = lib.clang_createTranslationUnit
2064TranslationUnit_read.argtypes = [Index, c_char_p]
2065TranslationUnit_read.restype = c_object_p
2066
2067TranslationUnit_parse = lib.clang_parseTranslationUnit
2068TranslationUnit_parse.argtypes = [Index, c_char_p, c_void_p,
2069                                  c_int, c_void_p, c_int, c_int]
2070TranslationUnit_parse.restype = c_object_p
2071
2072TranslationUnit_reparse = lib.clang_reparseTranslationUnit
2073TranslationUnit_reparse.argtypes = [TranslationUnit, c_int, c_void_p, c_int]
2074TranslationUnit_reparse.restype = c_int
2075
2076TranslationUnit_codeComplete = lib.clang_codeCompleteAt
2077TranslationUnit_codeComplete.argtypes = [TranslationUnit, c_char_p, c_int,
2078                                         c_int, c_void_p, c_int, c_int]
2079TranslationUnit_codeComplete.restype = POINTER(CCRStructure)
2080
2081TranslationUnit_cursor = lib.clang_getTranslationUnitCursor
2082TranslationUnit_cursor.argtypes = [TranslationUnit]
2083TranslationUnit_cursor.restype = Cursor
2084TranslationUnit_cursor.errcheck = Cursor.from_result
2085
2086TranslationUnit_spelling = lib.clang_getTranslationUnitSpelling
2087TranslationUnit_spelling.argtypes = [TranslationUnit]
2088TranslationUnit_spelling.restype = _CXString
2089TranslationUnit_spelling.errcheck = _CXString.from_result
2090
2091TranslationUnit_dispose = lib.clang_disposeTranslationUnit
2092TranslationUnit_dispose.argtypes = [TranslationUnit]
2093
2094TranslationUnit_includes_callback = CFUNCTYPE(None,
2095                                              c_object_p,
2096                                              POINTER(SourceLocation),
2097                                              c_uint, py_object)
2098TranslationUnit_includes = lib.clang_getInclusions
2099TranslationUnit_includes.argtypes = [TranslationUnit,
2100                                     TranslationUnit_includes_callback,
2101                                     py_object]
2102
2103# File Functions
2104File_getFile = lib.clang_getFile
2105File_getFile.argtypes = [TranslationUnit, c_char_p]
2106File_getFile.restype = c_object_p
2107
2108File_name = lib.clang_getFileName
2109File_name.argtypes = [File]
2110File_name.restype = _CXString
2111
2112File_time = lib.clang_getFileTime
2113File_time.argtypes = [File]
2114File_time.restype = c_uint
2115
2116# Code completion
2117
2118CodeCompletionResults_dispose = lib.clang_disposeCodeCompleteResults
2119CodeCompletionResults_dispose.argtypes = [CodeCompletionResults]
2120
2121_clang_codeCompleteGetNumDiagnostics = lib.clang_codeCompleteGetNumDiagnostics
2122_clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults]
2123_clang_codeCompleteGetNumDiagnostics.restype = c_int
2124
2125_clang_codeCompleteGetDiagnostic = lib.clang_codeCompleteGetDiagnostic
2126_clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults, c_int]
2127_clang_codeCompleteGetDiagnostic.restype = Diagnostic
2128
2129_clang_getCompletionChunkText = lib.clang_getCompletionChunkText
2130_clang_getCompletionChunkText.argtypes = [c_void_p, c_int]
2131_clang_getCompletionChunkText.restype = _CXString
2132
2133_clang_getCompletionChunkKind = lib.clang_getCompletionChunkKind
2134_clang_getCompletionChunkKind.argtypes = [c_void_p, c_int]
2135_clang_getCompletionChunkKind.restype = c_int
2136
2137_clang_getCompletionChunkCompletionString = lib.clang_getCompletionChunkCompletionString
2138_clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int]
2139_clang_getCompletionChunkCompletionString.restype = c_object_p
2140
2141_clang_getNumCompletionChunks = lib.clang_getNumCompletionChunks
2142_clang_getNumCompletionChunks.argtypes = [c_void_p]
2143_clang_getNumCompletionChunks.restype = c_int
2144
2145_clang_getCompletionAvailability = lib.clang_getCompletionAvailability
2146_clang_getCompletionAvailability.argtypes = [c_void_p]
2147_clang_getCompletionAvailability.restype = c_int
2148
2149_clang_getCompletionPriority = lib.clang_getCompletionPriority
2150_clang_getCompletionPriority.argtypes = [c_void_p]
2151_clang_getCompletionPriority.restype = c_int
2152
2153
2154###
2155
2156__all__ = ['Index', 'TranslationUnit', 'Cursor', 'CursorKind', 'Type', 'TypeKind',
2157           'Diagnostic', 'FixIt', 'CodeCompletionResults', 'SourceRange',
2158           'SourceLocation', 'File']
2159