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