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