1#===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===#
2#
3# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4# See https://llvm.org/LICENSE.txt for license information.
5# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6#
7#===------------------------------------------------------------------------===#
8
9r"""
10Clang Indexing Library Bindings
11===============================
12
13This module provides an interface to the Clang indexing library. It is a
14low-level interface to the indexing library which attempts to match the Clang
15API directly while also being "pythonic". Notable differences from the C API
16are:
17
18 * string results are returned as Python strings, not CXString objects.
19
20 * null cursors are translated to None.
21
22 * access to child cursors is done via iteration, not visitation.
23
24The major indexing objects are:
25
26  Index
27
28    The top-level object which manages some global library state.
29
30  TranslationUnit
31
32    High-level object encapsulating the AST for a single translation unit. These
33    can be loaded from .ast files or parsed on the fly.
34
35  Cursor
36
37    Generic object for representing a node in the AST.
38
39  SourceRange, SourceLocation, and File
40
41    Objects representing information about the input source.
42
43Most object information is exposed using properties, when the underlying API
44call is efficient.
45"""
46from __future__ import absolute_import, division, print_function
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 *
66
67import clang.enumerations
68
69import os
70import sys
71if sys.version_info[0] == 3:
72    # Python 3 strings are unicode, translate them to/from utf8 for C-interop.
73    class c_interop_string(c_char_p):
74
75        def __init__(self, p=None):
76            if p is None:
77                p = ""
78            if isinstance(p, str):
79                p = p.encode("utf8")
80            super(c_char_p, self).__init__(p)
81
82        def __str__(self):
83            return self.value
84
85        @property
86        def value(self):
87            if super(c_char_p, self).value is None:
88                return None
89            return super(c_char_p, self).value.decode("utf8")
90
91        @classmethod
92        def from_param(cls, param):
93            if isinstance(param, str):
94                return cls(param)
95            if isinstance(param, bytes):
96                return cls(param)
97            if param is None:
98                # Support passing null to C functions expecting char arrays
99                return None
100            raise TypeError("Cannot convert '{}' to '{}'".format(type(param).__name__, cls.__name__))
101
102        @staticmethod
103        def to_python_string(x, *args):
104            return x.value
105
106    def b(x):
107        if isinstance(x, bytes):
108            return x
109        return x.encode('utf8')
110
111elif sys.version_info[0] == 2:
112    # Python 2 strings are utf8 byte strings, no translation is needed for
113    # C-interop.
114    c_interop_string = c_char_p
115
116    def _to_python_string(x, *args):
117        return x
118
119    c_interop_string.to_python_string = staticmethod(_to_python_string)
120
121    def b(x):
122        return x
123
124# Importing ABC-s directly from collections is deprecated since Python 3.7,
125# will stop working in Python 3.8.
126# See: https://docs.python.org/dev/whatsnew/3.7.html#id3
127if sys.version_info[:2] >= (3, 7):
128    from collections import abc as collections_abc
129else:
130    import collections as collections_abc
131
132# We only support PathLike objects on Python version with os.fspath present
133# to be consistent with the Python standard library. On older Python versions
134# we only support strings and we have dummy fspath to just pass them through.
135try:
136    fspath = os.fspath
137except AttributeError:
138    def fspath(x):
139        return x
140
141# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
142# object. This is a problem, because it means that from_parameter will see an
143# integer and pass the wrong value on platforms where int != void*. Work around
144# this by marshalling object arguments as void**.
145c_object_p = POINTER(c_void_p)
146
147callbacks = {}
148
149### Exception Classes ###
150
151class TranslationUnitLoadError(Exception):
152    """Represents an error that occurred when loading a TranslationUnit.
153
154    This is raised in the case where a TranslationUnit could not be
155    instantiated due to failure in the libclang library.
156
157    FIXME: Make libclang expose additional error information in this scenario.
158    """
159    pass
160
161class TranslationUnitSaveError(Exception):
162    """Represents an error that occurred when saving a TranslationUnit.
163
164    Each error has associated with it an enumerated value, accessible under
165    e.save_error. Consumers can compare the value with one of the ERROR_
166    constants in this class.
167    """
168
169    # Indicates that an unknown error occurred. This typically indicates that
170    # I/O failed during save.
171    ERROR_UNKNOWN = 1
172
173    # Indicates that errors during translation prevented saving. The errors
174    # should be available via the TranslationUnit's diagnostics.
175    ERROR_TRANSLATION_ERRORS = 2
176
177    # Indicates that the translation unit was somehow invalid.
178    ERROR_INVALID_TU = 3
179
180    def __init__(self, enumeration, message):
181        assert isinstance(enumeration, int)
182
183        if enumeration < 1 or enumeration > 3:
184            raise Exception("Encountered undefined TranslationUnit save error "
185                            "constant: %d. Please file a bug to have this "
186                            "value supported." % enumeration)
187
188        self.save_error = enumeration
189        Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
190
191### Structures and Utility Classes ###
192
193class CachedProperty(object):
194    """Decorator that lazy-loads the value of a property.
195
196    The first time the property is accessed, the original property function is
197    executed. The value it returns is set as the new value of that instance's
198    property, replacing the original method.
199    """
200
201    def __init__(self, wrapped):
202        self.wrapped = wrapped
203        try:
204            self.__doc__ = wrapped.__doc__
205        except:
206            pass
207
208    def __get__(self, instance, instance_type=None):
209        if instance is None:
210            return self
211
212        value = self.wrapped(instance)
213        setattr(instance, self.wrapped.__name__, value)
214
215        return value
216
217
218class _CXString(Structure):
219    """Helper for transforming CXString results."""
220
221    _fields_ = [("spelling", c_char_p), ("free", c_int)]
222
223    def __del__(self):
224        conf.lib.clang_disposeString(self)
225
226    @staticmethod
227    def from_result(res, fn=None, args=None):
228        assert isinstance(res, _CXString)
229        return conf.lib.clang_getCString(res)
230
231
232class SourceLocation(Structure):
233    """
234    A SourceLocation represents a particular location within a source file.
235    """
236    _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
237    _data = None
238
239    def _get_instantiation(self):
240        if self._data is None:
241            f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
242            conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l),
243                    byref(c), byref(o))
244            if f:
245                f = File(f)
246            else:
247                f = None
248            self._data = (f, int(l.value), int(c.value), int(o.value))
249        return self._data
250
251    @staticmethod
252    def from_position(tu, file, line, column):
253        """
254        Retrieve the source location associated with a given file/line/column in
255        a particular translation unit.
256        """
257        return conf.lib.clang_getLocation(tu, file, line, column)
258
259    @staticmethod
260    def from_offset(tu, file, offset):
261        """Retrieve a SourceLocation from a given character offset.
262
263        tu -- TranslationUnit file belongs to
264        file -- File instance to obtain offset from
265        offset -- Integer character offset within file
266        """
267        return conf.lib.clang_getLocationForOffset(tu, file, offset)
268
269    @property
270    def file(self):
271        """Get the file represented by this source location."""
272        return self._get_instantiation()[0]
273
274    @property
275    def line(self):
276        """Get the line represented by this source location."""
277        return self._get_instantiation()[1]
278
279    @property
280    def column(self):
281        """Get the column represented by this source location."""
282        return self._get_instantiation()[2]
283
284    @property
285    def offset(self):
286        """Get the file offset represented by this source location."""
287        return self._get_instantiation()[3]
288
289    def __eq__(self, other):
290        return conf.lib.clang_equalLocations(self, other)
291
292    def __ne__(self, other):
293        return not self.__eq__(other)
294
295    def __repr__(self):
296        if self.file:
297            filename = self.file.name
298        else:
299            filename = None
300        return "<SourceLocation file %r, line %r, column %r>" % (
301            filename, self.line, self.column)
302
303class SourceRange(Structure):
304    """
305    A SourceRange describes a range of source locations within the source
306    code.
307    """
308    _fields_ = [
309        ("ptr_data", c_void_p * 2),
310        ("begin_int_data", c_uint),
311        ("end_int_data", c_uint)]
312
313    # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
314    # object.
315    @staticmethod
316    def from_locations(start, end):
317        return conf.lib.clang_getRange(start, end)
318
319    @property
320    def start(self):
321        """
322        Return a SourceLocation representing the first character within a
323        source range.
324        """
325        return conf.lib.clang_getRangeStart(self)
326
327    @property
328    def end(self):
329        """
330        Return a SourceLocation representing the last character within a
331        source range.
332        """
333        return conf.lib.clang_getRangeEnd(self)
334
335    def __eq__(self, other):
336        return conf.lib.clang_equalRanges(self, other)
337
338    def __ne__(self, other):
339        return not self.__eq__(other)
340
341    def __contains__(self, other):
342        """Useful to detect the Token/Lexer bug"""
343        if not isinstance(other, SourceLocation):
344            return False
345        if other.file is None and self.start.file is None:
346            pass
347        elif ( self.start.file.name != other.file.name or
348               other.file.name != self.end.file.name):
349            # same file name
350            return False
351        # same file, in between lines
352        if self.start.line < other.line < self.end.line:
353            return True
354        elif self.start.line == other.line:
355            # same file first line
356            if self.start.column <= other.column:
357                return True
358        elif other.line == self.end.line:
359            # same file last line
360            if other.column <= self.end.column:
361                return True
362        return False
363
364    def __repr__(self):
365        return "<SourceRange start %r, end %r>" % (self.start, self.end)
366
367class Diagnostic(object):
368    """
369    A Diagnostic is a single instance of a Clang diagnostic. It includes the
370    diagnostic severity, the message, the location the diagnostic occurred, as
371    well as additional source ranges and associated fix-it hints.
372    """
373
374    Ignored = 0
375    Note    = 1
376    Warning = 2
377    Error   = 3
378    Fatal   = 4
379
380    DisplaySourceLocation = 0x01
381    DisplayColumn         = 0x02
382    DisplaySourceRanges   = 0x04
383    DisplayOption         = 0x08
384    DisplayCategoryId     = 0x10
385    DisplayCategoryName   = 0x20
386    _FormatOptionsMask    = 0x3f
387
388    def __init__(self, ptr):
389        self.ptr = ptr
390
391    def __del__(self):
392        conf.lib.clang_disposeDiagnostic(self)
393
394    @property
395    def severity(self):
396        return conf.lib.clang_getDiagnosticSeverity(self)
397
398    @property
399    def location(self):
400        return conf.lib.clang_getDiagnosticLocation(self)
401
402    @property
403    def spelling(self):
404        return conf.lib.clang_getDiagnosticSpelling(self)
405
406    @property
407    def ranges(self):
408        class RangeIterator(object):
409            def __init__(self, diag):
410                self.diag = diag
411
412            def __len__(self):
413                return int(conf.lib.clang_getDiagnosticNumRanges(self.diag))
414
415            def __getitem__(self, key):
416                if (key >= len(self)):
417                    raise IndexError
418                return conf.lib.clang_getDiagnosticRange(self.diag, key)
419
420        return RangeIterator(self)
421
422    @property
423    def fixits(self):
424        class FixItIterator(object):
425            def __init__(self, diag):
426                self.diag = diag
427
428            def __len__(self):
429                return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag))
430
431            def __getitem__(self, key):
432                range = SourceRange()
433                value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
434                        byref(range))
435                if len(value) == 0:
436                    raise IndexError
437
438                return FixIt(range, value)
439
440        return FixItIterator(self)
441
442    @property
443    def children(self):
444        class ChildDiagnosticsIterator(object):
445            def __init__(self, diag):
446                self.diag_set = conf.lib.clang_getChildDiagnostics(diag)
447
448            def __len__(self):
449                return int(conf.lib.clang_getNumDiagnosticsInSet(self.diag_set))
450
451            def __getitem__(self, key):
452                diag = conf.lib.clang_getDiagnosticInSet(self.diag_set, key)
453                if not diag:
454                    raise IndexError
455                return Diagnostic(diag)
456
457        return ChildDiagnosticsIterator(self)
458
459    @property
460    def category_number(self):
461        """The category number for this diagnostic or 0 if unavailable."""
462        return conf.lib.clang_getDiagnosticCategory(self)
463
464    @property
465    def category_name(self):
466        """The string name of the category for this diagnostic."""
467        return conf.lib.clang_getDiagnosticCategoryText(self)
468
469    @property
470    def option(self):
471        """The command-line option that enables this diagnostic."""
472        return conf.lib.clang_getDiagnosticOption(self, None)
473
474    @property
475    def disable_option(self):
476        """The command-line option that disables this diagnostic."""
477        disable = _CXString()
478        conf.lib.clang_getDiagnosticOption(self, byref(disable))
479        return _CXString.from_result(disable)
480
481    def format(self, options=None):
482        """
483        Format this diagnostic for display. The options argument takes
484        Diagnostic.Display* flags, which can be combined using bitwise OR. If
485        the options argument is not provided, the default display options will
486        be used.
487        """
488        if options is None:
489            options = conf.lib.clang_defaultDiagnosticDisplayOptions()
490        if options & ~Diagnostic._FormatOptionsMask:
491            raise ValueError('Invalid format options')
492        return conf.lib.clang_formatDiagnostic(self, options)
493
494    def __repr__(self):
495        return "<Diagnostic severity %r, location %r, spelling %r>" % (
496            self.severity, self.location, self.spelling)
497
498    def __str__(self):
499        return self.format()
500
501    def from_param(self):
502      return self.ptr
503
504class FixIt(object):
505    """
506    A FixIt represents a transformation to be applied to the source to
507    "fix-it". The fix-it shouldbe applied by replacing the given source range
508    with the given value.
509    """
510
511    def __init__(self, range, value):
512        self.range = range
513        self.value = value
514
515    def __repr__(self):
516        return "<FixIt range %r, value %r>" % (self.range, self.value)
517
518class TokenGroup(object):
519    """Helper class to facilitate token management.
520
521    Tokens are allocated from libclang in chunks. They must be disposed of as a
522    collective group.
523
524    One purpose of this class is for instances to represent groups of allocated
525    tokens. Each token in a group contains a reference back to an instance of
526    this class. When all tokens from a group are garbage collected, it allows
527    this class to be garbage collected. When this class is garbage collected,
528    it calls the libclang destructor which invalidates all tokens in the group.
529
530    You should not instantiate this class outside of this module.
531    """
532    def __init__(self, tu, memory, count):
533        self._tu = tu
534        self._memory = memory
535        self._count = count
536
537    def __del__(self):
538        conf.lib.clang_disposeTokens(self._tu, self._memory, self._count)
539
540    @staticmethod
541    def get_tokens(tu, extent):
542        """Helper method to return all tokens in an extent.
543
544        This functionality is needed multiple places in this module. We define
545        it here because it seems like a logical place.
546        """
547        tokens_memory = POINTER(Token)()
548        tokens_count = c_uint()
549
550        conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
551                byref(tokens_count))
552
553        count = int(tokens_count.value)
554
555        # If we get no tokens, no memory was allocated. Be sure not to return
556        # anything and potentially call a destructor on nothing.
557        if count < 1:
558            return
559
560        tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
561
562        token_group = TokenGroup(tu, tokens_memory, tokens_count)
563
564        for i in range(0, count):
565            token = Token()
566            token.int_data = tokens_array[i].int_data
567            token.ptr_data = tokens_array[i].ptr_data
568            token._tu = tu
569            token._group = token_group
570
571            yield token
572
573class TokenKind(object):
574    """Describes a specific type of a Token."""
575
576    _value_map = {} # int -> TokenKind
577
578    def __init__(self, value, name):
579        """Create a new TokenKind instance from a numeric value and a name."""
580        self.value = value
581        self.name = name
582
583    def __repr__(self):
584        return 'TokenKind.%s' % (self.name,)
585
586    @staticmethod
587    def from_value(value):
588        """Obtain a registered TokenKind instance from its value."""
589        result = TokenKind._value_map.get(value, None)
590
591        if result is None:
592            raise ValueError('Unknown TokenKind: %d' % value)
593
594        return result
595
596    @staticmethod
597    def register(value, name):
598        """Register a new TokenKind enumeration.
599
600        This should only be called at module load time by code within this
601        package.
602        """
603        if value in TokenKind._value_map:
604            raise ValueError('TokenKind already registered: %d' % value)
605
606        kind = TokenKind(value, name)
607        TokenKind._value_map[value] = kind
608        setattr(TokenKind, name, kind)
609
610### Cursor Kinds ###
611class BaseEnumeration(object):
612    """
613    Common base class for named enumerations held in sync with Index.h values.
614
615    Subclasses must define their own _kinds and _name_map members, as:
616    _kinds = []
617    _name_map = None
618    These values hold the per-subclass instances and value-to-name mappings,
619    respectively.
620
621    """
622
623    def __init__(self, value):
624        if value >= len(self.__class__._kinds):
625            self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1)
626        if self.__class__._kinds[value] is not None:
627            raise ValueError('{0} value {1} already loaded'.format(
628                str(self.__class__), value))
629        self.value = value
630        self.__class__._kinds[value] = self
631        self.__class__._name_map = None
632
633
634    def from_param(self):
635        return self.value
636
637    @property
638    def name(self):
639        """Get the enumeration name of this cursor kind."""
640        if self._name_map is None:
641            self._name_map = {}
642            for key, value in self.__class__.__dict__.items():
643                if isinstance(value, self.__class__):
644                    self._name_map[value] = key
645        return self._name_map[self]
646
647    @classmethod
648    def from_id(cls, id):
649        if id >= len(cls._kinds) or cls._kinds[id] is None:
650            raise ValueError('Unknown template argument kind %d' % id)
651        return cls._kinds[id]
652
653    def __repr__(self):
654        return '%s.%s' % (self.__class__, self.name,)
655
656
657class CursorKind(BaseEnumeration):
658    """
659    A CursorKind describes the kind of entity that a cursor points to.
660    """
661
662    # The required BaseEnumeration declarations.
663    _kinds = []
664    _name_map = None
665
666    @staticmethod
667    def get_all_kinds():
668        """Return all CursorKind enumeration instances."""
669        return [x for x in CursorKind._kinds if not x is None]
670
671    def is_declaration(self):
672        """Test if this is a declaration kind."""
673        return conf.lib.clang_isDeclaration(self)
674
675    def is_reference(self):
676        """Test if this is a reference kind."""
677        return conf.lib.clang_isReference(self)
678
679    def is_expression(self):
680        """Test if this is an expression kind."""
681        return conf.lib.clang_isExpression(self)
682
683    def is_statement(self):
684        """Test if this is a statement kind."""
685        return conf.lib.clang_isStatement(self)
686
687    def is_attribute(self):
688        """Test if this is an attribute kind."""
689        return conf.lib.clang_isAttribute(self)
690
691    def is_invalid(self):
692        """Test if this is an invalid kind."""
693        return conf.lib.clang_isInvalid(self)
694
695    def is_translation_unit(self):
696        """Test if this is a translation unit kind."""
697        return conf.lib.clang_isTranslationUnit(self)
698
699    def is_preprocessing(self):
700        """Test if this is a preprocessing kind."""
701        return conf.lib.clang_isPreprocessing(self)
702
703    def is_unexposed(self):
704        """Test if this is an unexposed kind."""
705        return conf.lib.clang_isUnexposed(self)
706
707    def __repr__(self):
708        return 'CursorKind.%s' % (self.name,)
709
710###
711# Declaration Kinds
712
713# A declaration whose specific kind is not exposed via this interface.
714#
715# Unexposed declarations have the same operations as any other kind of
716# declaration; one can extract their location information, spelling, find their
717# definitions, etc. However, the specific kind of the declaration is not
718# reported.
719CursorKind.UNEXPOSED_DECL = CursorKind(1)
720
721# A C or C++ struct.
722CursorKind.STRUCT_DECL = CursorKind(2)
723
724# A C or C++ union.
725CursorKind.UNION_DECL = CursorKind(3)
726
727# A C++ class.
728CursorKind.CLASS_DECL = CursorKind(4)
729
730# An enumeration.
731CursorKind.ENUM_DECL = CursorKind(5)
732
733# A field (in C) or non-static data member (in C++) in a struct, union, or C++
734# class.
735CursorKind.FIELD_DECL = CursorKind(6)
736
737# An enumerator constant.
738CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
739
740# A function.
741CursorKind.FUNCTION_DECL = CursorKind(8)
742
743# A variable.
744CursorKind.VAR_DECL = CursorKind(9)
745
746# A function or method parameter.
747CursorKind.PARM_DECL = CursorKind(10)
748
749# An Objective-C @interface.
750CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
751
752# An Objective-C @interface for a category.
753CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
754
755# An Objective-C @protocol declaration.
756CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
757
758# An Objective-C @property declaration.
759CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
760
761# An Objective-C instance variable.
762CursorKind.OBJC_IVAR_DECL = CursorKind(15)
763
764# An Objective-C instance method.
765CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
766
767# An Objective-C class method.
768CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
769
770# An Objective-C @implementation.
771CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
772
773# An Objective-C @implementation for a category.
774CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
775
776# A typedef.
777CursorKind.TYPEDEF_DECL = CursorKind(20)
778
779# A C++ class method.
780CursorKind.CXX_METHOD = CursorKind(21)
781
782# A C++ namespace.
783CursorKind.NAMESPACE = CursorKind(22)
784
785# A linkage specification, e.g. 'extern "C"'.
786CursorKind.LINKAGE_SPEC = CursorKind(23)
787
788# A C++ constructor.
789CursorKind.CONSTRUCTOR = CursorKind(24)
790
791# A C++ destructor.
792CursorKind.DESTRUCTOR = CursorKind(25)
793
794# A C++ conversion function.
795CursorKind.CONVERSION_FUNCTION = CursorKind(26)
796
797# A C++ template type parameter
798CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
799
800# A C++ non-type template parameter.
801CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
802
803# A C++ template template parameter.
804CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29)
805
806# A C++ function template.
807CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
808
809# A C++ class template.
810CursorKind.CLASS_TEMPLATE = CursorKind(31)
811
812# A C++ class template partial specialization.
813CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
814
815# A C++ namespace alias declaration.
816CursorKind.NAMESPACE_ALIAS = CursorKind(33)
817
818# A C++ using directive
819CursorKind.USING_DIRECTIVE = CursorKind(34)
820
821# A C++ using declaration
822CursorKind.USING_DECLARATION = CursorKind(35)
823
824# A Type alias decl.
825CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
826
827# A Objective-C synthesize decl
828CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
829
830# A Objective-C dynamic decl
831CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
832
833# A C++ access specifier decl.
834CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
835
836
837###
838# Reference Kinds
839
840CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
841CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
842CursorKind.OBJC_CLASS_REF = CursorKind(42)
843
844# A reference to a type declaration.
845#
846# A type reference occurs anywhere where a type is named but not
847# declared. For example, given:
848#   typedef unsigned size_type;
849#   size_type size;
850#
851# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
852# while the type of the variable "size" is referenced. The cursor
853# referenced by the type of size is the typedef for size_type.
854CursorKind.TYPE_REF = CursorKind(43)
855CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
856
857# A reference to a class template, function template, template
858# template parameter, or class template partial specialization.
859CursorKind.TEMPLATE_REF = CursorKind(45)
860
861# A reference to a namespace or namepsace alias.
862CursorKind.NAMESPACE_REF = CursorKind(46)
863
864# A reference to a member of a struct, union, or class that occurs in
865# some non-expression context, e.g., a designated initializer.
866CursorKind.MEMBER_REF = CursorKind(47)
867
868# A reference to a labeled statement.
869CursorKind.LABEL_REF = CursorKind(48)
870
871# A reference to a set of overloaded functions or function templates
872# that has not yet been resolved to a specific function or function template.
873CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
874
875# A reference to a variable that occurs in some non-expression
876# context, e.g., a C++ lambda capture list.
877CursorKind.VARIABLE_REF = CursorKind(50)
878
879###
880# Invalid/Error Kinds
881
882CursorKind.INVALID_FILE = CursorKind(70)
883CursorKind.NO_DECL_FOUND = CursorKind(71)
884CursorKind.NOT_IMPLEMENTED = CursorKind(72)
885CursorKind.INVALID_CODE = CursorKind(73)
886
887###
888# Expression Kinds
889
890# An expression whose specific kind is not exposed via this interface.
891#
892# Unexposed expressions have the same operations as any other kind of
893# expression; one can extract their location information, spelling, children,
894# etc. However, the specific kind of the expression is not reported.
895CursorKind.UNEXPOSED_EXPR = CursorKind(100)
896
897# An expression that refers to some value declaration, such as a function,
898# variable, or enumerator.
899CursorKind.DECL_REF_EXPR = CursorKind(101)
900
901# An expression that refers to a member of a struct, union, class, Objective-C
902# class, etc.
903CursorKind.MEMBER_REF_EXPR = CursorKind(102)
904
905# An expression that calls a function.
906CursorKind.CALL_EXPR = CursorKind(103)
907
908# An expression that sends a message to an Objective-C object or class.
909CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
910
911# An expression that represents a block literal.
912CursorKind.BLOCK_EXPR = CursorKind(105)
913
914# An integer literal.
915CursorKind.INTEGER_LITERAL = CursorKind(106)
916
917# A floating point number literal.
918CursorKind.FLOATING_LITERAL = CursorKind(107)
919
920# An imaginary number literal.
921CursorKind.IMAGINARY_LITERAL = CursorKind(108)
922
923# A string literal.
924CursorKind.STRING_LITERAL = CursorKind(109)
925
926# A character literal.
927CursorKind.CHARACTER_LITERAL = CursorKind(110)
928
929# A parenthesized expression, e.g. "(1)".
930#
931# This AST node is only formed if full location information is requested.
932CursorKind.PAREN_EXPR = CursorKind(111)
933
934# This represents the unary-expression's (except sizeof and
935# alignof).
936CursorKind.UNARY_OPERATOR = CursorKind(112)
937
938# [C99 6.5.2.1] Array Subscripting.
939CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
940
941# A builtin binary operation expression such as "x + y" or
942# "x <= y".
943CursorKind.BINARY_OPERATOR = CursorKind(114)
944
945# Compound assignment such as "+=".
946CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
947
948# The ?: ternary operator.
949CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
950
951# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
952# (C++ [expr.cast]), which uses the syntax (Type)expr.
953#
954# For example: (int)f.
955CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
956
957# [C99 6.5.2.5]
958CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
959
960# Describes an C or C++ initializer list.
961CursorKind.INIT_LIST_EXPR = CursorKind(119)
962
963# The GNU address of label extension, representing &&label.
964CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
965
966# This is the GNU Statement Expression extension: ({int X=4; X;})
967CursorKind.StmtExpr = CursorKind(121)
968
969# Represents a C11 generic selection.
970CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
971
972# Implements the GNU __null extension, which is a name for a null
973# pointer constant that has integral type (e.g., int or long) and is the same
974# size and alignment as a pointer.
975#
976# The __null extension is typically only used by system headers, which define
977# NULL as __null in C++ rather than using 0 (which is an integer that may not
978# match the size of a pointer).
979CursorKind.GNU_NULL_EXPR = CursorKind(123)
980
981# C++'s static_cast<> expression.
982CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
983
984# C++'s dynamic_cast<> expression.
985CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
986
987# C++'s reinterpret_cast<> expression.
988CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
989
990# C++'s const_cast<> expression.
991CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
992
993# Represents an explicit C++ type conversion that uses "functional"
994# notion (C++ [expr.type.conv]).
995#
996# Example:
997# \code
998#   x = int(0.5);
999# \endcode
1000CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
1001
1002# A C++ typeid expression (C++ [expr.typeid]).
1003CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
1004
1005# [C++ 2.13.5] C++ Boolean Literal.
1006CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
1007
1008# [C++0x 2.14.7] C++ Pointer Literal.
1009CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
1010
1011# Represents the "this" expression in C++
1012CursorKind.CXX_THIS_EXPR = CursorKind(132)
1013
1014# [C++ 15] C++ Throw Expression.
1015#
1016# This handles 'throw' and 'throw' assignment-expression. When
1017# assignment-expression isn't present, Op will be null.
1018CursorKind.CXX_THROW_EXPR = CursorKind(133)
1019
1020# A new expression for memory allocation and constructor calls, e.g:
1021# "new CXXNewExpr(foo)".
1022CursorKind.CXX_NEW_EXPR = CursorKind(134)
1023
1024# A delete expression for memory deallocation and destructor calls,
1025# e.g. "delete[] pArray".
1026CursorKind.CXX_DELETE_EXPR = CursorKind(135)
1027
1028# Represents a unary expression.
1029CursorKind.CXX_UNARY_EXPR = CursorKind(136)
1030
1031# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
1032CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
1033
1034# ObjCEncodeExpr, used for in Objective-C.
1035CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
1036
1037# ObjCSelectorExpr used for in Objective-C.
1038CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
1039
1040# Objective-C's protocol expression.
1041CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
1042
1043# An Objective-C "bridged" cast expression, which casts between
1044# Objective-C pointers and C pointers, transferring ownership in the process.
1045#
1046# \code
1047#   NSString *str = (__bridge_transfer NSString *)CFCreateString();
1048# \endcode
1049CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
1050
1051# Represents a C++0x pack expansion that produces a sequence of
1052# expressions.
1053#
1054# A pack expansion expression contains a pattern (which itself is an
1055# expression) followed by an ellipsis. For example:
1056CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
1057
1058# Represents an expression that computes the length of a parameter
1059# pack.
1060CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
1061
1062# Represents a C++ lambda expression that produces a local function
1063# object.
1064#
1065#  \code
1066#  void abssort(float *x, unsigned N) {
1067#    std::sort(x, x + N,
1068#              [](float a, float b) {
1069#                return std::abs(a) < std::abs(b);
1070#              });
1071#  }
1072#  \endcode
1073CursorKind.LAMBDA_EXPR = CursorKind(144)
1074
1075# Objective-c Boolean Literal.
1076CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145)
1077
1078# Represents the "self" expression in a ObjC method.
1079CursorKind.OBJ_SELF_EXPR = CursorKind(146)
1080
1081# OpenMP 4.0 [2.4, Array Section].
1082CursorKind.OMP_ARRAY_SECTION_EXPR = CursorKind(147)
1083
1084# Represents an @available(...) check.
1085CursorKind.OBJC_AVAILABILITY_CHECK_EXPR = CursorKind(148)
1086
1087
1088# A statement whose specific kind is not exposed via this interface.
1089#
1090# Unexposed statements have the same operations as any other kind of statement;
1091# one can extract their location information, spelling, children, etc. However,
1092# the specific kind of the statement is not reported.
1093CursorKind.UNEXPOSED_STMT = CursorKind(200)
1094
1095# A labelled statement in a function.
1096CursorKind.LABEL_STMT = CursorKind(201)
1097
1098# A compound statement
1099CursorKind.COMPOUND_STMT = CursorKind(202)
1100
1101# A case statement.
1102CursorKind.CASE_STMT = CursorKind(203)
1103
1104# A default statement.
1105CursorKind.DEFAULT_STMT = CursorKind(204)
1106
1107# An if statement.
1108CursorKind.IF_STMT = CursorKind(205)
1109
1110# A switch statement.
1111CursorKind.SWITCH_STMT = CursorKind(206)
1112
1113# A while statement.
1114CursorKind.WHILE_STMT = CursorKind(207)
1115
1116# A do statement.
1117CursorKind.DO_STMT = CursorKind(208)
1118
1119# A for statement.
1120CursorKind.FOR_STMT = CursorKind(209)
1121
1122# A goto statement.
1123CursorKind.GOTO_STMT = CursorKind(210)
1124
1125# An indirect goto statement.
1126CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
1127
1128# A continue statement.
1129CursorKind.CONTINUE_STMT = CursorKind(212)
1130
1131# A break statement.
1132CursorKind.BREAK_STMT = CursorKind(213)
1133
1134# A return statement.
1135CursorKind.RETURN_STMT = CursorKind(214)
1136
1137# A GNU-style inline assembler statement.
1138CursorKind.ASM_STMT = CursorKind(215)
1139
1140# Objective-C's overall @try-@catch-@finally statement.
1141CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
1142
1143# Objective-C's @catch statement.
1144CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
1145
1146# Objective-C's @finally statement.
1147CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
1148
1149# Objective-C's @throw statement.
1150CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
1151
1152# Objective-C's @synchronized statement.
1153CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
1154
1155# Objective-C's autorealease pool statement.
1156CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
1157
1158# Objective-C's for collection statement.
1159CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
1160
1161# C++'s catch statement.
1162CursorKind.CXX_CATCH_STMT = CursorKind(223)
1163
1164# C++'s try statement.
1165CursorKind.CXX_TRY_STMT = CursorKind(224)
1166
1167# C++'s for (* : *) statement.
1168CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
1169
1170# Windows Structured Exception Handling's try statement.
1171CursorKind.SEH_TRY_STMT = CursorKind(226)
1172
1173# Windows Structured Exception Handling's except statement.
1174CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
1175
1176# Windows Structured Exception Handling's finally statement.
1177CursorKind.SEH_FINALLY_STMT = CursorKind(228)
1178
1179# A MS inline assembly statement extension.
1180CursorKind.MS_ASM_STMT = CursorKind(229)
1181
1182# The null statement.
1183CursorKind.NULL_STMT = CursorKind(230)
1184
1185# Adaptor class for mixing declarations with statements and expressions.
1186CursorKind.DECL_STMT = CursorKind(231)
1187
1188# OpenMP parallel directive.
1189CursorKind.OMP_PARALLEL_DIRECTIVE = CursorKind(232)
1190
1191# OpenMP SIMD directive.
1192CursorKind.OMP_SIMD_DIRECTIVE = CursorKind(233)
1193
1194# OpenMP for directive.
1195CursorKind.OMP_FOR_DIRECTIVE = CursorKind(234)
1196
1197# OpenMP sections directive.
1198CursorKind.OMP_SECTIONS_DIRECTIVE = CursorKind(235)
1199
1200# OpenMP section directive.
1201CursorKind.OMP_SECTION_DIRECTIVE = CursorKind(236)
1202
1203# OpenMP single directive.
1204CursorKind.OMP_SINGLE_DIRECTIVE = CursorKind(237)
1205
1206# OpenMP parallel for directive.
1207CursorKind.OMP_PARALLEL_FOR_DIRECTIVE = CursorKind(238)
1208
1209# OpenMP parallel sections directive.
1210CursorKind.OMP_PARALLEL_SECTIONS_DIRECTIVE = CursorKind(239)
1211
1212# OpenMP task directive.
1213CursorKind.OMP_TASK_DIRECTIVE = CursorKind(240)
1214
1215# OpenMP master directive.
1216CursorKind.OMP_MASTER_DIRECTIVE = CursorKind(241)
1217
1218# OpenMP critical directive.
1219CursorKind.OMP_CRITICAL_DIRECTIVE = CursorKind(242)
1220
1221# OpenMP taskyield directive.
1222CursorKind.OMP_TASKYIELD_DIRECTIVE = CursorKind(243)
1223
1224# OpenMP barrier directive.
1225CursorKind.OMP_BARRIER_DIRECTIVE = CursorKind(244)
1226
1227# OpenMP taskwait directive.
1228CursorKind.OMP_TASKWAIT_DIRECTIVE = CursorKind(245)
1229
1230# OpenMP flush directive.
1231CursorKind.OMP_FLUSH_DIRECTIVE = CursorKind(246)
1232
1233# Windows Structured Exception Handling's leave statement.
1234CursorKind.SEH_LEAVE_STMT = CursorKind(247)
1235
1236# OpenMP ordered directive.
1237CursorKind.OMP_ORDERED_DIRECTIVE = CursorKind(248)
1238
1239# OpenMP atomic directive.
1240CursorKind.OMP_ATOMIC_DIRECTIVE = CursorKind(249)
1241
1242# OpenMP for SIMD directive.
1243CursorKind.OMP_FOR_SIMD_DIRECTIVE = CursorKind(250)
1244
1245# OpenMP parallel for SIMD directive.
1246CursorKind.OMP_PARALLELFORSIMD_DIRECTIVE = CursorKind(251)
1247
1248# OpenMP target directive.
1249CursorKind.OMP_TARGET_DIRECTIVE = CursorKind(252)
1250
1251# OpenMP teams directive.
1252CursorKind.OMP_TEAMS_DIRECTIVE = CursorKind(253)
1253
1254# OpenMP taskgroup directive.
1255CursorKind.OMP_TASKGROUP_DIRECTIVE = CursorKind(254)
1256
1257# OpenMP cancellation point directive.
1258CursorKind.OMP_CANCELLATION_POINT_DIRECTIVE = CursorKind(255)
1259
1260# OpenMP cancel directive.
1261CursorKind.OMP_CANCEL_DIRECTIVE = CursorKind(256)
1262
1263# OpenMP target data directive.
1264CursorKind.OMP_TARGET_DATA_DIRECTIVE = CursorKind(257)
1265
1266# OpenMP taskloop directive.
1267CursorKind.OMP_TASK_LOOP_DIRECTIVE = CursorKind(258)
1268
1269# OpenMP taskloop simd directive.
1270CursorKind.OMP_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(259)
1271
1272# OpenMP distribute directive.
1273CursorKind.OMP_DISTRIBUTE_DIRECTIVE = CursorKind(260)
1274
1275# OpenMP target enter data directive.
1276CursorKind.OMP_TARGET_ENTER_DATA_DIRECTIVE = CursorKind(261)
1277
1278# OpenMP target exit data directive.
1279CursorKind.OMP_TARGET_EXIT_DATA_DIRECTIVE = CursorKind(262)
1280
1281# OpenMP target parallel directive.
1282CursorKind.OMP_TARGET_PARALLEL_DIRECTIVE = CursorKind(263)
1283
1284# OpenMP target parallel for directive.
1285CursorKind.OMP_TARGET_PARALLELFOR_DIRECTIVE = CursorKind(264)
1286
1287# OpenMP target update directive.
1288CursorKind.OMP_TARGET_UPDATE_DIRECTIVE = CursorKind(265)
1289
1290# OpenMP distribute parallel for directive.
1291CursorKind.OMP_DISTRIBUTE_PARALLELFOR_DIRECTIVE = CursorKind(266)
1292
1293# OpenMP distribute parallel for simd directive.
1294CursorKind.OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(267)
1295
1296# OpenMP distribute simd directive.
1297CursorKind.OMP_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(268)
1298
1299# OpenMP target parallel for simd directive.
1300CursorKind.OMP_TARGET_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(269)
1301
1302# OpenMP target simd directive.
1303CursorKind.OMP_TARGET_SIMD_DIRECTIVE = CursorKind(270)
1304
1305# OpenMP teams distribute directive.
1306CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(271)
1307
1308###
1309# Other Kinds
1310
1311# Cursor that represents the translation unit itself.
1312#
1313# The translation unit cursor exists primarily to act as the root cursor for
1314# traversing the contents of a translation unit.
1315CursorKind.TRANSLATION_UNIT = CursorKind(300)
1316
1317###
1318# Attributes
1319
1320# An attribute whoe specific kind is note exposed via this interface
1321CursorKind.UNEXPOSED_ATTR = CursorKind(400)
1322
1323CursorKind.IB_ACTION_ATTR = CursorKind(401)
1324CursorKind.IB_OUTLET_ATTR = CursorKind(402)
1325CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
1326
1327CursorKind.CXX_FINAL_ATTR = CursorKind(404)
1328CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
1329CursorKind.ANNOTATE_ATTR = CursorKind(406)
1330CursorKind.ASM_LABEL_ATTR = CursorKind(407)
1331CursorKind.PACKED_ATTR = CursorKind(408)
1332CursorKind.PURE_ATTR = CursorKind(409)
1333CursorKind.CONST_ATTR = CursorKind(410)
1334CursorKind.NODUPLICATE_ATTR = CursorKind(411)
1335CursorKind.CUDACONSTANT_ATTR = CursorKind(412)
1336CursorKind.CUDADEVICE_ATTR = CursorKind(413)
1337CursorKind.CUDAGLOBAL_ATTR = CursorKind(414)
1338CursorKind.CUDAHOST_ATTR = CursorKind(415)
1339CursorKind.CUDASHARED_ATTR = CursorKind(416)
1340
1341CursorKind.VISIBILITY_ATTR = CursorKind(417)
1342
1343CursorKind.DLLEXPORT_ATTR = CursorKind(418)
1344CursorKind.DLLIMPORT_ATTR = CursorKind(419)
1345CursorKind.CONVERGENT_ATTR = CursorKind(438)
1346CursorKind.WARN_UNUSED_ATTR = CursorKind(439)
1347CursorKind.WARN_UNUSED_RESULT_ATTR = CursorKind(440)
1348CursorKind.ALIGNED_ATTR = CursorKind(441)
1349
1350###
1351# Preprocessing
1352CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
1353CursorKind.MACRO_DEFINITION = CursorKind(501)
1354CursorKind.MACRO_INSTANTIATION = CursorKind(502)
1355CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
1356
1357###
1358# Extra declaration
1359
1360# A module import declaration.
1361CursorKind.MODULE_IMPORT_DECL = CursorKind(600)
1362# A type alias template declaration
1363CursorKind.TYPE_ALIAS_TEMPLATE_DECL = CursorKind(601)
1364# A static_assert or _Static_assert node
1365CursorKind.STATIC_ASSERT = CursorKind(602)
1366# A friend declaration
1367CursorKind.FRIEND_DECL = CursorKind(603)
1368
1369# A code completion overload candidate.
1370CursorKind.OVERLOAD_CANDIDATE = CursorKind(700)
1371
1372### Template Argument Kinds ###
1373class TemplateArgumentKind(BaseEnumeration):
1374    """
1375    A TemplateArgumentKind describes the kind of entity that a template argument
1376    represents.
1377    """
1378
1379    # The required BaseEnumeration declarations.
1380    _kinds = []
1381    _name_map = None
1382
1383TemplateArgumentKind.NULL = TemplateArgumentKind(0)
1384TemplateArgumentKind.TYPE = TemplateArgumentKind(1)
1385TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2)
1386TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3)
1387TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4)
1388
1389### Exception Specification Kinds ###
1390class ExceptionSpecificationKind(BaseEnumeration):
1391    """
1392    An ExceptionSpecificationKind describes the kind of exception specification
1393    that a function has.
1394    """
1395
1396    # The required BaseEnumeration declarations.
1397    _kinds = []
1398    _name_map = None
1399
1400    def __repr__(self):
1401        return 'ExceptionSpecificationKind.{}'.format(self.name)
1402
1403ExceptionSpecificationKind.NONE = ExceptionSpecificationKind(0)
1404ExceptionSpecificationKind.DYNAMIC_NONE = ExceptionSpecificationKind(1)
1405ExceptionSpecificationKind.DYNAMIC = ExceptionSpecificationKind(2)
1406ExceptionSpecificationKind.MS_ANY = ExceptionSpecificationKind(3)
1407ExceptionSpecificationKind.BASIC_NOEXCEPT = ExceptionSpecificationKind(4)
1408ExceptionSpecificationKind.COMPUTED_NOEXCEPT = ExceptionSpecificationKind(5)
1409ExceptionSpecificationKind.UNEVALUATED = ExceptionSpecificationKind(6)
1410ExceptionSpecificationKind.UNINSTANTIATED = ExceptionSpecificationKind(7)
1411ExceptionSpecificationKind.UNPARSED = ExceptionSpecificationKind(8)
1412
1413### Cursors ###
1414
1415class Cursor(Structure):
1416    """
1417    The Cursor class represents a reference to an element within the AST. It
1418    acts as a kind of iterator.
1419    """
1420    _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
1421
1422    @staticmethod
1423    def from_location(tu, location):
1424        # We store a reference to the TU in the instance so the TU won't get
1425        # collected before the cursor.
1426        cursor = conf.lib.clang_getCursor(tu, location)
1427        cursor._tu = tu
1428
1429        return cursor
1430
1431    def __eq__(self, other):
1432        return conf.lib.clang_equalCursors(self, other)
1433
1434    def __ne__(self, other):
1435        return not self.__eq__(other)
1436
1437    def is_definition(self):
1438        """
1439        Returns true if the declaration pointed at by the cursor is also a
1440        definition of that entity.
1441        """
1442        return conf.lib.clang_isCursorDefinition(self)
1443
1444    def is_const_method(self):
1445        """Returns True if the cursor refers to a C++ member function or member
1446        function template that is declared 'const'.
1447        """
1448        return conf.lib.clang_CXXMethod_isConst(self)
1449
1450    def is_converting_constructor(self):
1451        """Returns True if the cursor refers to a C++ converting constructor.
1452        """
1453        return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)
1454
1455    def is_copy_constructor(self):
1456        """Returns True if the cursor refers to a C++ copy constructor.
1457        """
1458        return conf.lib.clang_CXXConstructor_isCopyConstructor(self)
1459
1460    def is_default_constructor(self):
1461        """Returns True if the cursor refers to a C++ default constructor.
1462        """
1463        return conf.lib.clang_CXXConstructor_isDefaultConstructor(self)
1464
1465    def is_move_constructor(self):
1466        """Returns True if the cursor refers to a C++ move constructor.
1467        """
1468        return conf.lib.clang_CXXConstructor_isMoveConstructor(self)
1469
1470    def is_default_method(self):
1471        """Returns True if the cursor refers to a C++ member function or member
1472        function template that is declared '= default'.
1473        """
1474        return conf.lib.clang_CXXMethod_isDefaulted(self)
1475
1476    def is_mutable_field(self):
1477        """Returns True if the cursor refers to a C++ field that is declared
1478        'mutable'.
1479        """
1480        return conf.lib.clang_CXXField_isMutable(self)
1481
1482    def is_pure_virtual_method(self):
1483        """Returns True if the cursor refers to a C++ member function or member
1484        function template that is declared pure virtual.
1485        """
1486        return conf.lib.clang_CXXMethod_isPureVirtual(self)
1487
1488    def is_static_method(self):
1489        """Returns True if the cursor refers to a C++ member function or member
1490        function template that is declared 'static'.
1491        """
1492        return conf.lib.clang_CXXMethod_isStatic(self)
1493
1494    def is_virtual_method(self):
1495        """Returns True if the cursor refers to a C++ member function or member
1496        function template that is declared 'virtual'.
1497        """
1498        return conf.lib.clang_CXXMethod_isVirtual(self)
1499
1500    def is_abstract_record(self):
1501        """Returns True if the cursor refers to a C++ record declaration
1502        that has pure virtual member functions.
1503        """
1504        return conf.lib.clang_CXXRecord_isAbstract(self)
1505
1506    def is_scoped_enum(self):
1507        """Returns True if the cursor refers to a scoped enum declaration.
1508        """
1509        return conf.lib.clang_EnumDecl_isScoped(self)
1510
1511    def get_definition(self):
1512        """
1513        If the cursor is a reference to a declaration or a declaration of
1514        some entity, return a cursor that points to the definition of that
1515        entity.
1516        """
1517        # TODO: Should probably check that this is either a reference or
1518        # declaration prior to issuing the lookup.
1519        return conf.lib.clang_getCursorDefinition(self)
1520
1521    def get_usr(self):
1522        """Return the Unified Symbol Resolution (USR) for the entity referenced
1523        by the given cursor (or None).
1524
1525        A Unified Symbol Resolution (USR) is a string that identifies a
1526        particular entity (function, class, variable, etc.) within a
1527        program. USRs can be compared across translation units to determine,
1528        e.g., when references in one translation refer to an entity defined in
1529        another translation unit."""
1530        return conf.lib.clang_getCursorUSR(self)
1531
1532    def get_included_file(self):
1533        """Returns the File that is included by the current inclusion cursor."""
1534        assert self.kind == CursorKind.INCLUSION_DIRECTIVE
1535
1536        return conf.lib.clang_getIncludedFile(self)
1537
1538    @property
1539    def kind(self):
1540        """Return the kind of this cursor."""
1541        return CursorKind.from_id(self._kind_id)
1542
1543    @property
1544    def spelling(self):
1545        """Return the spelling of the entity pointed at by the cursor."""
1546        if not hasattr(self, '_spelling'):
1547            self._spelling = conf.lib.clang_getCursorSpelling(self)
1548
1549        return self._spelling
1550
1551    @property
1552    def displayname(self):
1553        """
1554        Return the display name for the entity referenced by this cursor.
1555
1556        The display name contains extra information that helps identify the
1557        cursor, such as the parameters of a function or template or the
1558        arguments of a class template specialization.
1559        """
1560        if not hasattr(self, '_displayname'):
1561            self._displayname = conf.lib.clang_getCursorDisplayName(self)
1562
1563        return self._displayname
1564
1565    @property
1566    def mangled_name(self):
1567        """Return the mangled name for the entity referenced by this cursor."""
1568        if not hasattr(self, '_mangled_name'):
1569            self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
1570
1571        return self._mangled_name
1572
1573    @property
1574    def location(self):
1575        """
1576        Return the source location (the starting character) of the entity
1577        pointed at by the cursor.
1578        """
1579        if not hasattr(self, '_loc'):
1580            self._loc = conf.lib.clang_getCursorLocation(self)
1581
1582        return self._loc
1583
1584    @property
1585    def linkage(self):
1586        """Return the linkage of this cursor."""
1587        if not hasattr(self, '_linkage'):
1588            self._linkage = conf.lib.clang_getCursorLinkage(self)
1589
1590        return LinkageKind.from_id(self._linkage)
1591
1592    @property
1593    def tls_kind(self):
1594        """Return the thread-local storage (TLS) kind of this cursor."""
1595        if not hasattr(self, '_tls_kind'):
1596            self._tls_kind = conf.lib.clang_getCursorTLSKind(self)
1597
1598        return TLSKind.from_id(self._tls_kind)
1599
1600    @property
1601    def extent(self):
1602        """
1603        Return the source range (the range of text) occupied by the entity
1604        pointed at by the cursor.
1605        """
1606        if not hasattr(self, '_extent'):
1607            self._extent = conf.lib.clang_getCursorExtent(self)
1608
1609        return self._extent
1610
1611    @property
1612    def storage_class(self):
1613        """
1614        Retrieves the storage class (if any) of the entity pointed at by the
1615        cursor.
1616        """
1617        if not hasattr(self, '_storage_class'):
1618            self._storage_class = conf.lib.clang_Cursor_getStorageClass(self)
1619
1620        return StorageClass.from_id(self._storage_class)
1621
1622    @property
1623    def availability(self):
1624        """
1625        Retrieves the availability of the entity pointed at by the cursor.
1626        """
1627        if not hasattr(self, '_availability'):
1628            self._availability = conf.lib.clang_getCursorAvailability(self)
1629
1630        return AvailabilityKind.from_id(self._availability)
1631
1632    @property
1633    def access_specifier(self):
1634        """
1635        Retrieves the access specifier (if any) of the entity pointed at by the
1636        cursor.
1637        """
1638        if not hasattr(self, '_access_specifier'):
1639            self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self)
1640
1641        return AccessSpecifier.from_id(self._access_specifier)
1642
1643    @property
1644    def type(self):
1645        """
1646        Retrieve the Type (if any) of the entity pointed at by the cursor.
1647        """
1648        if not hasattr(self, '_type'):
1649            self._type = conf.lib.clang_getCursorType(self)
1650
1651        return self._type
1652
1653    @property
1654    def canonical(self):
1655        """Return the canonical Cursor corresponding to this Cursor.
1656
1657        The canonical cursor is the cursor which is representative for the
1658        underlying entity. For example, if you have multiple forward
1659        declarations for the same class, the canonical cursor for the forward
1660        declarations will be identical.
1661        """
1662        if not hasattr(self, '_canonical'):
1663            self._canonical = conf.lib.clang_getCanonicalCursor(self)
1664
1665        return self._canonical
1666
1667    @property
1668    def result_type(self):
1669        """Retrieve the Type of the result for this Cursor."""
1670        if not hasattr(self, '_result_type'):
1671            self._result_type = conf.lib.clang_getCursorResultType(self)
1672
1673        return self._result_type
1674
1675    @property
1676    def exception_specification_kind(self):
1677        '''
1678        Retrieve the exception specification kind, which is one of the values
1679        from the ExceptionSpecificationKind enumeration.
1680        '''
1681        if not hasattr(self, '_exception_specification_kind'):
1682            exc_kind = conf.lib.clang_getCursorExceptionSpecificationType(self)
1683            self._exception_specification_kind = ExceptionSpecificationKind.from_id(exc_kind)
1684
1685        return self._exception_specification_kind
1686
1687    @property
1688    def underlying_typedef_type(self):
1689        """Return the underlying type of a typedef declaration.
1690
1691        Returns a Type for the typedef this cursor is a declaration for. If
1692        the current cursor is not a typedef, this raises.
1693        """
1694        if not hasattr(self, '_underlying_type'):
1695            assert self.kind.is_declaration()
1696            self._underlying_type = \
1697              conf.lib.clang_getTypedefDeclUnderlyingType(self)
1698
1699        return self._underlying_type
1700
1701    @property
1702    def enum_type(self):
1703        """Return the integer type of an enum declaration.
1704
1705        Returns a Type corresponding to an integer. If the cursor is not for an
1706        enum, this raises.
1707        """
1708        if not hasattr(self, '_enum_type'):
1709            assert self.kind == CursorKind.ENUM_DECL
1710            self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
1711
1712        return self._enum_type
1713
1714    @property
1715    def enum_value(self):
1716        """Return the value of an enum constant."""
1717        if not hasattr(self, '_enum_value'):
1718            assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1719            # Figure out the underlying type of the enum to know if it
1720            # is a signed or unsigned quantity.
1721            underlying_type = self.type
1722            if underlying_type.kind == TypeKind.ENUM:
1723                underlying_type = underlying_type.get_declaration().enum_type
1724            if underlying_type.kind in (TypeKind.CHAR_U,
1725                                        TypeKind.UCHAR,
1726                                        TypeKind.CHAR16,
1727                                        TypeKind.CHAR32,
1728                                        TypeKind.USHORT,
1729                                        TypeKind.UINT,
1730                                        TypeKind.ULONG,
1731                                        TypeKind.ULONGLONG,
1732                                        TypeKind.UINT128):
1733                self._enum_value = \
1734                  conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
1735            else:
1736                self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
1737        return self._enum_value
1738
1739    @property
1740    def objc_type_encoding(self):
1741        """Return the Objective-C type encoding as a str."""
1742        if not hasattr(self, '_objc_type_encoding'):
1743            self._objc_type_encoding = \
1744              conf.lib.clang_getDeclObjCTypeEncoding(self)
1745
1746        return self._objc_type_encoding
1747
1748    @property
1749    def hash(self):
1750        """Returns a hash of the cursor as an int."""
1751        if not hasattr(self, '_hash'):
1752            self._hash = conf.lib.clang_hashCursor(self)
1753
1754        return self._hash
1755
1756    @property
1757    def semantic_parent(self):
1758        """Return the semantic parent for this cursor."""
1759        if not hasattr(self, '_semantic_parent'):
1760            self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
1761
1762        return self._semantic_parent
1763
1764    @property
1765    def lexical_parent(self):
1766        """Return the lexical parent for this cursor."""
1767        if not hasattr(self, '_lexical_parent'):
1768            self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
1769
1770        return self._lexical_parent
1771
1772    @property
1773    def translation_unit(self):
1774        """Returns the TranslationUnit to which this Cursor belongs."""
1775        # If this triggers an AttributeError, the instance was not properly
1776        # created.
1777        return self._tu
1778
1779    @property
1780    def referenced(self):
1781        """
1782        For a cursor that is a reference, returns a cursor
1783        representing the entity that it references.
1784        """
1785        if not hasattr(self, '_referenced'):
1786            self._referenced = conf.lib.clang_getCursorReferenced(self)
1787
1788        return self._referenced
1789
1790    @property
1791    def brief_comment(self):
1792        """Returns the brief comment text associated with that Cursor"""
1793        return conf.lib.clang_Cursor_getBriefCommentText(self)
1794
1795    @property
1796    def raw_comment(self):
1797        """Returns the raw comment text associated with that Cursor"""
1798        return conf.lib.clang_Cursor_getRawCommentText(self)
1799
1800    def get_arguments(self):
1801        """Return an iterator for accessing the arguments of this cursor."""
1802        num_args = conf.lib.clang_Cursor_getNumArguments(self)
1803        for i in range(0, num_args):
1804            yield conf.lib.clang_Cursor_getArgument(self, i)
1805
1806    def get_num_template_arguments(self):
1807        """Returns the number of template args associated with this cursor."""
1808        return conf.lib.clang_Cursor_getNumTemplateArguments(self)
1809
1810    def get_template_argument_kind(self, num):
1811        """Returns the TemplateArgumentKind for the indicated template
1812        argument."""
1813        return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num)
1814
1815    def get_template_argument_type(self, num):
1816        """Returns the CXType for the indicated template argument."""
1817        return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
1818
1819    def get_template_argument_value(self, num):
1820        """Returns the value of the indicated arg as a signed 64b integer."""
1821        return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num)
1822
1823    def get_template_argument_unsigned_value(self, num):
1824        """Returns the value of the indicated arg as an unsigned 64b integer."""
1825        return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num)
1826
1827    def get_children(self):
1828        """Return an iterator for accessing the children of this cursor."""
1829
1830        # FIXME: Expose iteration from CIndex, PR6125.
1831        def visitor(child, parent, children):
1832            # FIXME: Document this assertion in API.
1833            # FIXME: There should just be an isNull method.
1834            assert child != conf.lib.clang_getNullCursor()
1835
1836            # Create reference to TU so it isn't GC'd before Cursor.
1837            child._tu = self._tu
1838            children.append(child)
1839            return 1 # continue
1840        children = []
1841        conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
1842            children)
1843        return iter(children)
1844
1845    def walk_preorder(self):
1846        """Depth-first preorder walk over the cursor and its descendants.
1847
1848        Yields cursors.
1849        """
1850        yield self
1851        for child in self.get_children():
1852            for descendant in child.walk_preorder():
1853                yield descendant
1854
1855    def get_tokens(self):
1856        """Obtain Token instances formulating that compose this Cursor.
1857
1858        This is a generator for Token instances. It returns all tokens which
1859        occupy the extent this cursor occupies.
1860        """
1861        return TokenGroup.get_tokens(self._tu, self.extent)
1862
1863    def get_field_offsetof(self):
1864        """Returns the offsetof the FIELD_DECL pointed by this Cursor."""
1865        return conf.lib.clang_Cursor_getOffsetOfField(self)
1866
1867    def is_anonymous(self):
1868        """
1869        Check if the record is anonymous.
1870        """
1871        if self.kind == CursorKind.FIELD_DECL:
1872            return self.type.get_declaration().is_anonymous()
1873        return conf.lib.clang_Cursor_isAnonymous(self)
1874
1875    def is_bitfield(self):
1876        """
1877        Check if the field is a bitfield.
1878        """
1879        return conf.lib.clang_Cursor_isBitField(self)
1880
1881    def get_bitfield_width(self):
1882        """
1883        Retrieve the width of a bitfield.
1884        """
1885        return conf.lib.clang_getFieldDeclBitWidth(self)
1886
1887    @staticmethod
1888    def from_result(res, fn, args):
1889        assert isinstance(res, Cursor)
1890        # FIXME: There should just be an isNull method.
1891        if res == conf.lib.clang_getNullCursor():
1892            return None
1893
1894        # Store a reference to the TU in the Python object so it won't get GC'd
1895        # before the Cursor.
1896        tu = None
1897        for arg in args:
1898            if isinstance(arg, TranslationUnit):
1899                tu = arg
1900                break
1901
1902            if hasattr(arg, 'translation_unit'):
1903                tu = arg.translation_unit
1904                break
1905
1906        assert tu is not None
1907
1908        res._tu = tu
1909        return res
1910
1911    @staticmethod
1912    def from_cursor_result(res, fn, args):
1913        assert isinstance(res, Cursor)
1914        if res == conf.lib.clang_getNullCursor():
1915            return None
1916
1917        res._tu = args[0]._tu
1918        return res
1919
1920class StorageClass(object):
1921    """
1922    Describes the storage class of a declaration
1923    """
1924
1925    # The unique kind objects, index by id.
1926    _kinds = []
1927    _name_map = None
1928
1929    def __init__(self, value):
1930        if value >= len(StorageClass._kinds):
1931            StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1)
1932        if StorageClass._kinds[value] is not None:
1933            raise ValueError('StorageClass already loaded')
1934        self.value = value
1935        StorageClass._kinds[value] = self
1936        StorageClass._name_map = None
1937
1938    def from_param(self):
1939        return self.value
1940
1941    @property
1942    def name(self):
1943        """Get the enumeration name of this storage class."""
1944        if self._name_map is None:
1945            self._name_map = {}
1946            for key,value in StorageClass.__dict__.items():
1947                if isinstance(value,StorageClass):
1948                    self._name_map[value] = key
1949        return self._name_map[self]
1950
1951    @staticmethod
1952    def from_id(id):
1953        if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
1954            raise ValueError('Unknown storage class %d' % id)
1955        return StorageClass._kinds[id]
1956
1957    def __repr__(self):
1958        return 'StorageClass.%s' % (self.name,)
1959
1960StorageClass.INVALID = StorageClass(0)
1961StorageClass.NONE = StorageClass(1)
1962StorageClass.EXTERN = StorageClass(2)
1963StorageClass.STATIC = StorageClass(3)
1964StorageClass.PRIVATEEXTERN = StorageClass(4)
1965StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5)
1966StorageClass.AUTO = StorageClass(6)
1967StorageClass.REGISTER = StorageClass(7)
1968
1969### Availability Kinds ###
1970
1971class AvailabilityKind(BaseEnumeration):
1972    """
1973    Describes the availability of an entity.
1974    """
1975
1976    # The unique kind objects, indexed by id.
1977    _kinds = []
1978    _name_map = None
1979
1980    def __repr__(self):
1981        return 'AvailabilityKind.%s' % (self.name,)
1982
1983AvailabilityKind.AVAILABLE = AvailabilityKind(0)
1984AvailabilityKind.DEPRECATED = AvailabilityKind(1)
1985AvailabilityKind.NOT_AVAILABLE = AvailabilityKind(2)
1986AvailabilityKind.NOT_ACCESSIBLE = AvailabilityKind(3)
1987
1988### C++ access specifiers ###
1989
1990class AccessSpecifier(BaseEnumeration):
1991    """
1992    Describes the access of a C++ class member
1993    """
1994
1995    # The unique kind objects, index by id.
1996    _kinds = []
1997    _name_map = None
1998
1999    def from_param(self):
2000        return self.value
2001
2002    def __repr__(self):
2003        return 'AccessSpecifier.%s' % (self.name,)
2004
2005AccessSpecifier.INVALID = AccessSpecifier(0)
2006AccessSpecifier.PUBLIC = AccessSpecifier(1)
2007AccessSpecifier.PROTECTED = AccessSpecifier(2)
2008AccessSpecifier.PRIVATE = AccessSpecifier(3)
2009AccessSpecifier.NONE = AccessSpecifier(4)
2010
2011### Type Kinds ###
2012
2013class TypeKind(BaseEnumeration):
2014    """
2015    Describes the kind of type.
2016    """
2017
2018    # The unique kind objects, indexed by id.
2019    _kinds = []
2020    _name_map = None
2021
2022    @property
2023    def spelling(self):
2024        """Retrieve the spelling of this TypeKind."""
2025        return conf.lib.clang_getTypeKindSpelling(self.value)
2026
2027    def __repr__(self):
2028        return 'TypeKind.%s' % (self.name,)
2029
2030TypeKind.INVALID = TypeKind(0)
2031TypeKind.UNEXPOSED = TypeKind(1)
2032TypeKind.VOID = TypeKind(2)
2033TypeKind.BOOL = TypeKind(3)
2034TypeKind.CHAR_U = TypeKind(4)
2035TypeKind.UCHAR = TypeKind(5)
2036TypeKind.CHAR16 = TypeKind(6)
2037TypeKind.CHAR32 = TypeKind(7)
2038TypeKind.USHORT = TypeKind(8)
2039TypeKind.UINT = TypeKind(9)
2040TypeKind.ULONG = TypeKind(10)
2041TypeKind.ULONGLONG = TypeKind(11)
2042TypeKind.UINT128 = TypeKind(12)
2043TypeKind.CHAR_S = TypeKind(13)
2044TypeKind.SCHAR = TypeKind(14)
2045TypeKind.WCHAR = TypeKind(15)
2046TypeKind.SHORT = TypeKind(16)
2047TypeKind.INT = TypeKind(17)
2048TypeKind.LONG = TypeKind(18)
2049TypeKind.LONGLONG = TypeKind(19)
2050TypeKind.INT128 = TypeKind(20)
2051TypeKind.FLOAT = TypeKind(21)
2052TypeKind.DOUBLE = TypeKind(22)
2053TypeKind.LONGDOUBLE = TypeKind(23)
2054TypeKind.NULLPTR = TypeKind(24)
2055TypeKind.OVERLOAD = TypeKind(25)
2056TypeKind.DEPENDENT = TypeKind(26)
2057TypeKind.OBJCID = TypeKind(27)
2058TypeKind.OBJCCLASS = TypeKind(28)
2059TypeKind.OBJCSEL = TypeKind(29)
2060TypeKind.FLOAT128 = TypeKind(30)
2061TypeKind.HALF = TypeKind(31)
2062TypeKind.COMPLEX = TypeKind(100)
2063TypeKind.POINTER = TypeKind(101)
2064TypeKind.BLOCKPOINTER = TypeKind(102)
2065TypeKind.LVALUEREFERENCE = TypeKind(103)
2066TypeKind.RVALUEREFERENCE = TypeKind(104)
2067TypeKind.RECORD = TypeKind(105)
2068TypeKind.ENUM = TypeKind(106)
2069TypeKind.TYPEDEF = TypeKind(107)
2070TypeKind.OBJCINTERFACE = TypeKind(108)
2071TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
2072TypeKind.FUNCTIONNOPROTO = TypeKind(110)
2073TypeKind.FUNCTIONPROTO = TypeKind(111)
2074TypeKind.CONSTANTARRAY = TypeKind(112)
2075TypeKind.VECTOR = TypeKind(113)
2076TypeKind.INCOMPLETEARRAY = TypeKind(114)
2077TypeKind.VARIABLEARRAY = TypeKind(115)
2078TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
2079TypeKind.MEMBERPOINTER = TypeKind(117)
2080TypeKind.AUTO = TypeKind(118)
2081TypeKind.ELABORATED = TypeKind(119)
2082TypeKind.PIPE = TypeKind(120)
2083TypeKind.OCLIMAGE1DRO = TypeKind(121)
2084TypeKind.OCLIMAGE1DARRAYRO = TypeKind(122)
2085TypeKind.OCLIMAGE1DBUFFERRO = TypeKind(123)
2086TypeKind.OCLIMAGE2DRO = TypeKind(124)
2087TypeKind.OCLIMAGE2DARRAYRO = TypeKind(125)
2088TypeKind.OCLIMAGE2DDEPTHRO = TypeKind(126)
2089TypeKind.OCLIMAGE2DARRAYDEPTHRO = TypeKind(127)
2090TypeKind.OCLIMAGE2DMSAARO = TypeKind(128)
2091TypeKind.OCLIMAGE2DARRAYMSAARO = TypeKind(129)
2092TypeKind.OCLIMAGE2DMSAADEPTHRO = TypeKind(130)
2093TypeKind.OCLIMAGE2DARRAYMSAADEPTHRO = TypeKind(131)
2094TypeKind.OCLIMAGE3DRO = TypeKind(132)
2095TypeKind.OCLIMAGE1DWO = TypeKind(133)
2096TypeKind.OCLIMAGE1DARRAYWO = TypeKind(134)
2097TypeKind.OCLIMAGE1DBUFFERWO = TypeKind(135)
2098TypeKind.OCLIMAGE2DWO = TypeKind(136)
2099TypeKind.OCLIMAGE2DARRAYWO = TypeKind(137)
2100TypeKind.OCLIMAGE2DDEPTHWO = TypeKind(138)
2101TypeKind.OCLIMAGE2DARRAYDEPTHWO = TypeKind(139)
2102TypeKind.OCLIMAGE2DMSAAWO = TypeKind(140)
2103TypeKind.OCLIMAGE2DARRAYMSAAWO = TypeKind(141)
2104TypeKind.OCLIMAGE2DMSAADEPTHWO = TypeKind(142)
2105TypeKind.OCLIMAGE2DARRAYMSAADEPTHWO = TypeKind(143)
2106TypeKind.OCLIMAGE3DWO = TypeKind(144)
2107TypeKind.OCLIMAGE1DRW = TypeKind(145)
2108TypeKind.OCLIMAGE1DARRAYRW = TypeKind(146)
2109TypeKind.OCLIMAGE1DBUFFERRW = TypeKind(147)
2110TypeKind.OCLIMAGE2DRW = TypeKind(148)
2111TypeKind.OCLIMAGE2DARRAYRW = TypeKind(149)
2112TypeKind.OCLIMAGE2DDEPTHRW = TypeKind(150)
2113TypeKind.OCLIMAGE2DARRAYDEPTHRW = TypeKind(151)
2114TypeKind.OCLIMAGE2DMSAARW = TypeKind(152)
2115TypeKind.OCLIMAGE2DARRAYMSAARW = TypeKind(153)
2116TypeKind.OCLIMAGE2DMSAADEPTHRW = TypeKind(154)
2117TypeKind.OCLIMAGE2DARRAYMSAADEPTHRW = TypeKind(155)
2118TypeKind.OCLIMAGE3DRW = TypeKind(156)
2119TypeKind.OCLSAMPLER = TypeKind(157)
2120TypeKind.OCLEVENT = TypeKind(158)
2121TypeKind.OCLQUEUE = TypeKind(159)
2122TypeKind.OCLRESERVEID = TypeKind(160)
2123
2124TypeKind.EXTVECTOR = TypeKind(176)
2125TypeKind.ATOMIC = TypeKind(177)
2126
2127class RefQualifierKind(BaseEnumeration):
2128    """Describes a specific ref-qualifier of a type."""
2129
2130    # The unique kind objects, indexed by id.
2131    _kinds = []
2132    _name_map = None
2133
2134    def from_param(self):
2135        return self.value
2136
2137    def __repr__(self):
2138        return 'RefQualifierKind.%s' % (self.name,)
2139
2140RefQualifierKind.NONE = RefQualifierKind(0)
2141RefQualifierKind.LVALUE = RefQualifierKind(1)
2142RefQualifierKind.RVALUE = RefQualifierKind(2)
2143
2144class LinkageKind(BaseEnumeration):
2145    """Describes the kind of linkage of a cursor."""
2146
2147    # The unique kind objects, indexed by id.
2148    _kinds = []
2149    _name_map = None
2150
2151    def from_param(self):
2152        return self.value
2153
2154    def __repr__(self):
2155        return 'LinkageKind.%s' % (self.name,)
2156
2157LinkageKind.INVALID = LinkageKind(0)
2158LinkageKind.NO_LINKAGE = LinkageKind(1)
2159LinkageKind.INTERNAL = LinkageKind(2)
2160LinkageKind.UNIQUE_EXTERNAL = LinkageKind(3)
2161LinkageKind.EXTERNAL = LinkageKind(4)
2162
2163class TLSKind(BaseEnumeration):
2164    """Describes the kind of thread-local storage (TLS) of a cursor."""
2165
2166    # The unique kind objects, indexed by id.
2167    _kinds = []
2168    _name_map = None
2169
2170    def from_param(self):
2171        return self.value
2172
2173    def __repr__(self):
2174        return 'TLSKind.%s' % (self.name,)
2175
2176TLSKind.NONE = TLSKind(0)
2177TLSKind.DYNAMIC = TLSKind(1)
2178TLSKind.STATIC = TLSKind(2)
2179
2180class Type(Structure):
2181    """
2182    The type of an element in the abstract syntax tree.
2183    """
2184    _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
2185
2186    @property
2187    def kind(self):
2188        """Return the kind of this type."""
2189        return TypeKind.from_id(self._kind_id)
2190
2191    def argument_types(self):
2192        """Retrieve a container for the non-variadic arguments for this type.
2193
2194        The returned object is iterable and indexable. Each item in the
2195        container is a Type instance.
2196        """
2197        class ArgumentsIterator(collections_abc.Sequence):
2198            def __init__(self, parent):
2199                self.parent = parent
2200                self.length = None
2201
2202            def __len__(self):
2203                if self.length is None:
2204                    self.length = conf.lib.clang_getNumArgTypes(self.parent)
2205
2206                return self.length
2207
2208            def __getitem__(self, key):
2209                # FIXME Support slice objects.
2210                if not isinstance(key, int):
2211                    raise TypeError("Must supply a non-negative int.")
2212
2213                if key < 0:
2214                    raise IndexError("Only non-negative indexes are accepted.")
2215
2216                if key >= len(self):
2217                    raise IndexError("Index greater than container length: "
2218                                     "%d > %d" % ( key, len(self) ))
2219
2220                result = conf.lib.clang_getArgType(self.parent, key)
2221                if result.kind == TypeKind.INVALID:
2222                    raise IndexError("Argument could not be retrieved.")
2223
2224                return result
2225
2226        assert self.kind == TypeKind.FUNCTIONPROTO
2227        return ArgumentsIterator(self)
2228
2229    @property
2230    def element_type(self):
2231        """Retrieve the Type of elements within this Type.
2232
2233        If accessed on a type that is not an array, complex, or vector type, an
2234        exception will be raised.
2235        """
2236        result = conf.lib.clang_getElementType(self)
2237        if result.kind == TypeKind.INVALID:
2238            raise Exception('Element type not available on this type.')
2239
2240        return result
2241
2242    @property
2243    def element_count(self):
2244        """Retrieve the number of elements in this type.
2245
2246        Returns an int.
2247
2248        If the Type is not an array or vector, this raises.
2249        """
2250        result = conf.lib.clang_getNumElements(self)
2251        if result < 0:
2252            raise Exception('Type does not have elements.')
2253
2254        return result
2255
2256    @property
2257    def translation_unit(self):
2258        """The TranslationUnit to which this Type is associated."""
2259        # If this triggers an AttributeError, the instance was not properly
2260        # instantiated.
2261        return self._tu
2262
2263    @staticmethod
2264    def from_result(res, fn, args):
2265        assert isinstance(res, Type)
2266
2267        tu = None
2268        for arg in args:
2269            if hasattr(arg, 'translation_unit'):
2270                tu = arg.translation_unit
2271                break
2272
2273        assert tu is not None
2274        res._tu = tu
2275
2276        return res
2277
2278    def get_num_template_arguments(self):
2279        return conf.lib.clang_Type_getNumTemplateArguments(self)
2280
2281    def get_template_argument_type(self, num):
2282        return conf.lib.clang_Type_getTemplateArgumentAsType(self, num)
2283
2284    def get_canonical(self):
2285        """
2286        Return the canonical type for a Type.
2287
2288        Clang's type system explicitly models typedefs and all the
2289        ways a specific type can be represented.  The canonical type
2290        is the underlying type with all the "sugar" removed.  For
2291        example, if 'T' is a typedef for 'int', the canonical type for
2292        'T' would be 'int'.
2293        """
2294        return conf.lib.clang_getCanonicalType(self)
2295
2296    def is_const_qualified(self):
2297        """Determine whether a Type has the "const" qualifier set.
2298
2299        This does not look through typedefs that may have added "const"
2300        at a different level.
2301        """
2302        return conf.lib.clang_isConstQualifiedType(self)
2303
2304    def is_volatile_qualified(self):
2305        """Determine whether a Type has the "volatile" qualifier set.
2306
2307        This does not look through typedefs that may have added "volatile"
2308        at a different level.
2309        """
2310        return conf.lib.clang_isVolatileQualifiedType(self)
2311
2312    def is_restrict_qualified(self):
2313        """Determine whether a Type has the "restrict" qualifier set.
2314
2315        This does not look through typedefs that may have added "restrict" at
2316        a different level.
2317        """
2318        return conf.lib.clang_isRestrictQualifiedType(self)
2319
2320    def is_function_variadic(self):
2321        """Determine whether this function Type is a variadic function type."""
2322        assert self.kind == TypeKind.FUNCTIONPROTO
2323
2324        return conf.lib.clang_isFunctionTypeVariadic(self)
2325
2326    def get_address_space(self):
2327        return conf.lib.clang_getAddressSpace(self)
2328
2329    def get_typedef_name(self):
2330        return conf.lib.clang_getTypedefName(self)
2331
2332    def is_pod(self):
2333        """Determine whether this Type represents plain old data (POD)."""
2334        return conf.lib.clang_isPODType(self)
2335
2336    def get_pointee(self):
2337        """
2338        For pointer types, returns the type of the pointee.
2339        """
2340        return conf.lib.clang_getPointeeType(self)
2341
2342    def get_declaration(self):
2343        """
2344        Return the cursor for the declaration of the given type.
2345        """
2346        return conf.lib.clang_getTypeDeclaration(self)
2347
2348    def get_result(self):
2349        """
2350        Retrieve the result type associated with a function type.
2351        """
2352        return conf.lib.clang_getResultType(self)
2353
2354    def get_array_element_type(self):
2355        """
2356        Retrieve the type of the elements of the array type.
2357        """
2358        return conf.lib.clang_getArrayElementType(self)
2359
2360    def get_array_size(self):
2361        """
2362        Retrieve the size of the constant array.
2363        """
2364        return conf.lib.clang_getArraySize(self)
2365
2366    def get_class_type(self):
2367        """
2368        Retrieve the class type of the member pointer type.
2369        """
2370        return conf.lib.clang_Type_getClassType(self)
2371
2372    def get_named_type(self):
2373        """
2374        Retrieve the type named by the qualified-id.
2375        """
2376        return conf.lib.clang_Type_getNamedType(self)
2377
2378    def get_align(self):
2379        """
2380        Retrieve the alignment of the record.
2381        """
2382        return conf.lib.clang_Type_getAlignOf(self)
2383
2384    def get_size(self):
2385        """
2386        Retrieve the size of the record.
2387        """
2388        return conf.lib.clang_Type_getSizeOf(self)
2389
2390    def get_offset(self, fieldname):
2391        """
2392        Retrieve the offset of a field in the record.
2393        """
2394        return conf.lib.clang_Type_getOffsetOf(self, fieldname)
2395
2396    def get_ref_qualifier(self):
2397        """
2398        Retrieve the ref-qualifier of the type.
2399        """
2400        return RefQualifierKind.from_id(
2401                conf.lib.clang_Type_getCXXRefQualifier(self))
2402
2403    def get_fields(self):
2404        """Return an iterator for accessing the fields of this type."""
2405
2406        def visitor(field, children):
2407            assert field != conf.lib.clang_getNullCursor()
2408
2409            # Create reference to TU so it isn't GC'd before Cursor.
2410            field._tu = self._tu
2411            fields.append(field)
2412            return 1 # continue
2413        fields = []
2414        conf.lib.clang_Type_visitFields(self,
2415                            callbacks['fields_visit'](visitor), fields)
2416        return iter(fields)
2417
2418    def get_exception_specification_kind(self):
2419        """
2420        Return the kind of the exception specification; a value from
2421        the ExceptionSpecificationKind enumeration.
2422        """
2423        return ExceptionSpecificationKind.from_id(
2424                conf.lib.clang.getExceptionSpecificationType(self))
2425
2426    @property
2427    def spelling(self):
2428        """Retrieve the spelling of this Type."""
2429        return conf.lib.clang_getTypeSpelling(self)
2430
2431    def __eq__(self, other):
2432        if type(other) != type(self):
2433            return False
2434
2435        return conf.lib.clang_equalTypes(self, other)
2436
2437    def __ne__(self, other):
2438        return not self.__eq__(other)
2439
2440## CIndex Objects ##
2441
2442# CIndex objects (derived from ClangObject) are essentially lightweight
2443# wrappers attached to some underlying object, which is exposed via CIndex as
2444# a void*.
2445
2446class ClangObject(object):
2447    """
2448    A helper for Clang objects. This class helps act as an intermediary for
2449    the ctypes library and the Clang CIndex library.
2450    """
2451    def __init__(self, obj):
2452        assert isinstance(obj, c_object_p) and obj
2453        self.obj = self._as_parameter_ = obj
2454
2455    def from_param(self):
2456        return self._as_parameter_
2457
2458
2459class _CXUnsavedFile(Structure):
2460    """Helper for passing unsaved file arguments."""
2461    _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
2462
2463# Functions calls through the python interface are rather slow. Fortunately,
2464# for most symboles, we do not need to perform a function call. Their spelling
2465# never changes and is consequently provided by this spelling cache.
2466SpellingCache = {
2467            # 0: CompletionChunk.Kind("Optional"),
2468            # 1: CompletionChunk.Kind("TypedText"),
2469            # 2: CompletionChunk.Kind("Text"),
2470            # 3: CompletionChunk.Kind("Placeholder"),
2471            # 4: CompletionChunk.Kind("Informative"),
2472            # 5 : CompletionChunk.Kind("CurrentParameter"),
2473            6: '(',   # CompletionChunk.Kind("LeftParen"),
2474            7: ')',   # CompletionChunk.Kind("RightParen"),
2475            8: '[',   # CompletionChunk.Kind("LeftBracket"),
2476            9: ']',   # CompletionChunk.Kind("RightBracket"),
2477            10: '{',  # CompletionChunk.Kind("LeftBrace"),
2478            11: '}',  # CompletionChunk.Kind("RightBrace"),
2479            12: '<',  # CompletionChunk.Kind("LeftAngle"),
2480            13: '>',  # CompletionChunk.Kind("RightAngle"),
2481            14: ', ', # CompletionChunk.Kind("Comma"),
2482            # 15: CompletionChunk.Kind("ResultType"),
2483            16: ':',  # CompletionChunk.Kind("Colon"),
2484            17: ';',  # CompletionChunk.Kind("SemiColon"),
2485            18: '=',  # CompletionChunk.Kind("Equal"),
2486            19: ' ',  # CompletionChunk.Kind("HorizontalSpace"),
2487            # 20: CompletionChunk.Kind("VerticalSpace")
2488}
2489
2490class CompletionChunk(object):
2491    class Kind(object):
2492        def __init__(self, name):
2493            self.name = name
2494
2495        def __str__(self):
2496            return self.name
2497
2498        def __repr__(self):
2499            return "<ChunkKind: %s>" % self
2500
2501    def __init__(self, completionString, key):
2502        self.cs = completionString
2503        self.key = key
2504        self.__kindNumberCache = -1
2505
2506    def __repr__(self):
2507        return "{'" + self.spelling + "', " + str(self.kind) + "}"
2508
2509    @CachedProperty
2510    def spelling(self):
2511        if self.__kindNumber in SpellingCache:
2512                return SpellingCache[self.__kindNumber]
2513        return conf.lib.clang_getCompletionChunkText(self.cs, self.key)
2514
2515    # We do not use @CachedProperty here, as the manual implementation is
2516    # apparently still significantly faster. Please profile carefully if you
2517    # would like to add CachedProperty back.
2518    @property
2519    def __kindNumber(self):
2520        if self.__kindNumberCache == -1:
2521            self.__kindNumberCache = \
2522                conf.lib.clang_getCompletionChunkKind(self.cs, self.key)
2523        return self.__kindNumberCache
2524
2525    @CachedProperty
2526    def kind(self):
2527        return completionChunkKindMap[self.__kindNumber]
2528
2529    @CachedProperty
2530    def string(self):
2531        res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
2532                                                                self.key)
2533
2534        if (res):
2535          return CompletionString(res)
2536        else:
2537          None
2538
2539    def isKindOptional(self):
2540      return self.__kindNumber == 0
2541
2542    def isKindTypedText(self):
2543      return self.__kindNumber == 1
2544
2545    def isKindPlaceHolder(self):
2546      return self.__kindNumber == 3
2547
2548    def isKindInformative(self):
2549      return self.__kindNumber == 4
2550
2551    def isKindResultType(self):
2552      return self.__kindNumber == 15
2553
2554completionChunkKindMap = {
2555            0: CompletionChunk.Kind("Optional"),
2556            1: CompletionChunk.Kind("TypedText"),
2557            2: CompletionChunk.Kind("Text"),
2558            3: CompletionChunk.Kind("Placeholder"),
2559            4: CompletionChunk.Kind("Informative"),
2560            5: CompletionChunk.Kind("CurrentParameter"),
2561            6: CompletionChunk.Kind("LeftParen"),
2562            7: CompletionChunk.Kind("RightParen"),
2563            8: CompletionChunk.Kind("LeftBracket"),
2564            9: CompletionChunk.Kind("RightBracket"),
2565            10: CompletionChunk.Kind("LeftBrace"),
2566            11: CompletionChunk.Kind("RightBrace"),
2567            12: CompletionChunk.Kind("LeftAngle"),
2568            13: CompletionChunk.Kind("RightAngle"),
2569            14: CompletionChunk.Kind("Comma"),
2570            15: CompletionChunk.Kind("ResultType"),
2571            16: CompletionChunk.Kind("Colon"),
2572            17: CompletionChunk.Kind("SemiColon"),
2573            18: CompletionChunk.Kind("Equal"),
2574            19: CompletionChunk.Kind("HorizontalSpace"),
2575            20: CompletionChunk.Kind("VerticalSpace")}
2576
2577class CompletionString(ClangObject):
2578    class Availability(object):
2579        def __init__(self, name):
2580            self.name = name
2581
2582        def __str__(self):
2583            return self.name
2584
2585        def __repr__(self):
2586            return "<Availability: %s>" % self
2587
2588    def __len__(self):
2589        return self.num_chunks
2590
2591    @CachedProperty
2592    def num_chunks(self):
2593        return conf.lib.clang_getNumCompletionChunks(self.obj)
2594
2595    def __getitem__(self, key):
2596        if self.num_chunks <= key:
2597            raise IndexError
2598        return CompletionChunk(self.obj, key)
2599
2600    @property
2601    def priority(self):
2602        return conf.lib.clang_getCompletionPriority(self.obj)
2603
2604    @property
2605    def availability(self):
2606        res = conf.lib.clang_getCompletionAvailability(self.obj)
2607        return availabilityKinds[res]
2608
2609    @property
2610    def briefComment(self):
2611        if conf.function_exists("clang_getCompletionBriefComment"):
2612            return conf.lib.clang_getCompletionBriefComment(self.obj)
2613        return _CXString()
2614
2615    def __repr__(self):
2616        return " | ".join([str(a) for a in self]) \
2617               + " || Priority: " + str(self.priority) \
2618               + " || Availability: " + str(self.availability) \
2619               + " || Brief comment: " + str(self.briefComment)
2620
2621availabilityKinds = {
2622            0: CompletionChunk.Kind("Available"),
2623            1: CompletionChunk.Kind("Deprecated"),
2624            2: CompletionChunk.Kind("NotAvailable"),
2625            3: CompletionChunk.Kind("NotAccessible")}
2626
2627class CodeCompletionResult(Structure):
2628    _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
2629
2630    def __repr__(self):
2631        return str(CompletionString(self.completionString))
2632
2633    @property
2634    def kind(self):
2635        return CursorKind.from_id(self.cursorKind)
2636
2637    @property
2638    def string(self):
2639        return CompletionString(self.completionString)
2640
2641class CCRStructure(Structure):
2642    _fields_ = [('results', POINTER(CodeCompletionResult)),
2643                ('numResults', c_int)]
2644
2645    def __len__(self):
2646        return self.numResults
2647
2648    def __getitem__(self, key):
2649        if len(self) <= key:
2650            raise IndexError
2651
2652        return self.results[key]
2653
2654class CodeCompletionResults(ClangObject):
2655    def __init__(self, ptr):
2656        assert isinstance(ptr, POINTER(CCRStructure)) and ptr
2657        self.ptr = self._as_parameter_ = ptr
2658
2659    def from_param(self):
2660        return self._as_parameter_
2661
2662    def __del__(self):
2663        conf.lib.clang_disposeCodeCompleteResults(self)
2664
2665    @property
2666    def results(self):
2667        return self.ptr.contents
2668
2669    @property
2670    def diagnostics(self):
2671        class DiagnosticsItr(object):
2672            def __init__(self, ccr):
2673                self.ccr= ccr
2674
2675            def __len__(self):
2676                return int(\
2677                  conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
2678
2679            def __getitem__(self, key):
2680                return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
2681
2682        return DiagnosticsItr(self)
2683
2684
2685class Index(ClangObject):
2686    """
2687    The Index type provides the primary interface to the Clang CIndex library,
2688    primarily by providing an interface for reading and parsing translation
2689    units.
2690    """
2691
2692    @staticmethod
2693    def create(excludeDecls=False):
2694        """
2695        Create a new Index.
2696        Parameters:
2697        excludeDecls -- Exclude local declarations from translation units.
2698        """
2699        return Index(conf.lib.clang_createIndex(excludeDecls, 0))
2700
2701    def __del__(self):
2702        conf.lib.clang_disposeIndex(self)
2703
2704    def read(self, path):
2705        """Load a TranslationUnit from the given AST file."""
2706        return TranslationUnit.from_ast_file(path, self)
2707
2708    def parse(self, path, args=None, unsaved_files=None, options = 0):
2709        """Load the translation unit from the given source code file by running
2710        clang and generating the AST before loading. Additional command line
2711        parameters can be passed to clang via the args parameter.
2712
2713        In-memory contents for files can be provided by passing a list of pairs
2714        to as unsaved_files, the first item should be the filenames to be mapped
2715        and the second should be the contents to be substituted for the
2716        file. The contents may be passed as strings or file objects.
2717
2718        If an error was encountered during parsing, a TranslationUnitLoadError
2719        will be raised.
2720        """
2721        return TranslationUnit.from_source(path, args, unsaved_files, options,
2722                                           self)
2723
2724class TranslationUnit(ClangObject):
2725    """Represents a source code translation unit.
2726
2727    This is one of the main types in the API. Any time you wish to interact
2728    with Clang's representation of a source file, you typically start with a
2729    translation unit.
2730    """
2731
2732    # Default parsing mode.
2733    PARSE_NONE = 0
2734
2735    # Instruct the parser to create a detailed processing record containing
2736    # metadata not normally retained.
2737    PARSE_DETAILED_PROCESSING_RECORD = 1
2738
2739    # Indicates that the translation unit is incomplete. This is typically used
2740    # when parsing headers.
2741    PARSE_INCOMPLETE = 2
2742
2743    # Instruct the parser to create a pre-compiled preamble for the translation
2744    # unit. This caches the preamble (included files at top of source file).
2745    # This is useful if the translation unit will be reparsed and you don't
2746    # want to incur the overhead of reparsing the preamble.
2747    PARSE_PRECOMPILED_PREAMBLE = 4
2748
2749    # Cache code completion information on parse. This adds time to parsing but
2750    # speeds up code completion.
2751    PARSE_CACHE_COMPLETION_RESULTS = 8
2752
2753    # Flags with values 16 and 32 are deprecated and intentionally omitted.
2754
2755    # Do not parse function bodies. This is useful if you only care about
2756    # searching for declarations/definitions.
2757    PARSE_SKIP_FUNCTION_BODIES = 64
2758
2759    # Used to indicate that brief documentation comments should be included
2760    # into the set of code completions returned from this translation unit.
2761    PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
2762
2763    @classmethod
2764    def from_source(cls, filename, args=None, unsaved_files=None, options=0,
2765                    index=None):
2766        """Create a TranslationUnit by parsing source.
2767
2768        This is capable of processing source code both from files on the
2769        filesystem as well as in-memory contents.
2770
2771        Command-line arguments that would be passed to clang are specified as
2772        a list via args. These can be used to specify include paths, warnings,
2773        etc. e.g. ["-Wall", "-I/path/to/include"].
2774
2775        In-memory file content can be provided via unsaved_files. This is an
2776        iterable of 2-tuples. The first element is the filename (str or
2777        PathLike). The second element defines the content. Content can be
2778        provided as str source code or as file objects (anything with a read()
2779        method). If a file object is being used, content will be read until EOF
2780        and the read cursor will not be reset to its original position.
2781
2782        options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
2783        control parsing behavior.
2784
2785        index is an Index instance to utilize. If not provided, a new Index
2786        will be created for this TranslationUnit.
2787
2788        To parse source from the filesystem, the filename of the file to parse
2789        is specified by the filename argument. Or, filename could be None and
2790        the args list would contain the filename(s) to parse.
2791
2792        To parse source from an in-memory buffer, set filename to the virtual
2793        filename you wish to associate with this source (e.g. "test.c"). The
2794        contents of that file are then provided in unsaved_files.
2795
2796        If an error occurs, a TranslationUnitLoadError is raised.
2797
2798        Please note that a TranslationUnit with parser errors may be returned.
2799        It is the caller's responsibility to check tu.diagnostics for errors.
2800
2801        Also note that Clang infers the source language from the extension of
2802        the input filename. If you pass in source code containing a C++ class
2803        declaration with the filename "test.c" parsing will fail.
2804        """
2805        if args is None:
2806            args = []
2807
2808        if unsaved_files is None:
2809            unsaved_files = []
2810
2811        if index is None:
2812            index = Index.create()
2813
2814        args_array = None
2815        if len(args) > 0:
2816            args_array = (c_char_p * len(args))(*[b(x) for x in args])
2817
2818        unsaved_array = None
2819        if len(unsaved_files) > 0:
2820            unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
2821            for i, (name, contents) in enumerate(unsaved_files):
2822                if hasattr(contents, "read"):
2823                    contents = contents.read()
2824                contents = b(contents)
2825                unsaved_array[i].name = b(fspath(name))
2826                unsaved_array[i].contents = contents
2827                unsaved_array[i].length = len(contents)
2828
2829        ptr = conf.lib.clang_parseTranslationUnit(index,
2830                                    fspath(filename) if filename is not None else None,
2831                                    args_array,
2832                                    len(args), unsaved_array,
2833                                    len(unsaved_files), options)
2834
2835        if not ptr:
2836            raise TranslationUnitLoadError("Error parsing translation unit.")
2837
2838        return cls(ptr, index=index)
2839
2840    @classmethod
2841    def from_ast_file(cls, filename, index=None):
2842        """Create a TranslationUnit instance from a saved AST file.
2843
2844        A previously-saved AST file (provided with -emit-ast or
2845        TranslationUnit.save()) is loaded from the filename specified.
2846
2847        If the file cannot be loaded, a TranslationUnitLoadError will be
2848        raised.
2849
2850        index is optional and is the Index instance to use. If not provided,
2851        a default Index will be created.
2852
2853        filename can be str or PathLike.
2854        """
2855        if index is None:
2856            index = Index.create()
2857
2858        ptr = conf.lib.clang_createTranslationUnit(index, fspath(filename))
2859        if not ptr:
2860            raise TranslationUnitLoadError(filename)
2861
2862        return cls(ptr=ptr, index=index)
2863
2864    def __init__(self, ptr, index):
2865        """Create a TranslationUnit instance.
2866
2867        TranslationUnits should be created using one of the from_* @classmethod
2868        functions above. __init__ is only called internally.
2869        """
2870        assert isinstance(index, Index)
2871        self.index = index
2872        ClangObject.__init__(self, ptr)
2873
2874    def __del__(self):
2875        conf.lib.clang_disposeTranslationUnit(self)
2876
2877    @property
2878    def cursor(self):
2879        """Retrieve the cursor that represents the given translation unit."""
2880        return conf.lib.clang_getTranslationUnitCursor(self)
2881
2882    @property
2883    def spelling(self):
2884        """Get the original translation unit source file name."""
2885        return conf.lib.clang_getTranslationUnitSpelling(self)
2886
2887    def get_includes(self):
2888        """
2889        Return an iterable sequence of FileInclusion objects that describe the
2890        sequence of inclusions in a translation unit. The first object in
2891        this sequence is always the input file. Note that this method will not
2892        recursively iterate over header files included through precompiled
2893        headers.
2894        """
2895        def visitor(fobj, lptr, depth, includes):
2896            if depth > 0:
2897                loc = lptr.contents
2898                includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
2899
2900        # Automatically adapt CIndex/ctype pointers to python objects
2901        includes = []
2902        conf.lib.clang_getInclusions(self,
2903                callbacks['translation_unit_includes'](visitor), includes)
2904
2905        return iter(includes)
2906
2907    def get_file(self, filename):
2908        """Obtain a File from this translation unit."""
2909
2910        return File.from_name(self, filename)
2911
2912    def get_location(self, filename, position):
2913        """Obtain a SourceLocation for a file in this translation unit.
2914
2915        The position can be specified by passing:
2916
2917          - Integer file offset. Initial file offset is 0.
2918          - 2-tuple of (line number, column number). Initial file position is
2919            (0, 0)
2920        """
2921        f = self.get_file(filename)
2922
2923        if isinstance(position, int):
2924            return SourceLocation.from_offset(self, f, position)
2925
2926        return SourceLocation.from_position(self, f, position[0], position[1])
2927
2928    def get_extent(self, filename, locations):
2929        """Obtain a SourceRange from this translation unit.
2930
2931        The bounds of the SourceRange must ultimately be defined by a start and
2932        end SourceLocation. For the locations argument, you can pass:
2933
2934          - 2 SourceLocation instances in a 2-tuple or list.
2935          - 2 int file offsets via a 2-tuple or list.
2936          - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
2937
2938        e.g.
2939
2940        get_extent('foo.c', (5, 10))
2941        get_extent('foo.c', ((1, 1), (1, 15)))
2942        """
2943        f = self.get_file(filename)
2944
2945        if len(locations) < 2:
2946            raise Exception('Must pass object with at least 2 elements')
2947
2948        start_location, end_location = locations
2949
2950        if hasattr(start_location, '__len__'):
2951            start_location = SourceLocation.from_position(self, f,
2952                start_location[0], start_location[1])
2953        elif isinstance(start_location, int):
2954            start_location = SourceLocation.from_offset(self, f,
2955                start_location)
2956
2957        if hasattr(end_location, '__len__'):
2958            end_location = SourceLocation.from_position(self, f,
2959                end_location[0], end_location[1])
2960        elif isinstance(end_location, int):
2961            end_location = SourceLocation.from_offset(self, f, end_location)
2962
2963        assert isinstance(start_location, SourceLocation)
2964        assert isinstance(end_location, SourceLocation)
2965
2966        return SourceRange.from_locations(start_location, end_location)
2967
2968    @property
2969    def diagnostics(self):
2970        """
2971        Return an iterable (and indexable) object containing the diagnostics.
2972        """
2973        class DiagIterator(object):
2974            def __init__(self, tu):
2975                self.tu = tu
2976
2977            def __len__(self):
2978                return int(conf.lib.clang_getNumDiagnostics(self.tu))
2979
2980            def __getitem__(self, key):
2981                diag = conf.lib.clang_getDiagnostic(self.tu, key)
2982                if not diag:
2983                    raise IndexError
2984                return Diagnostic(diag)
2985
2986        return DiagIterator(self)
2987
2988    def reparse(self, unsaved_files=None, options=0):
2989        """
2990        Reparse an already parsed translation unit.
2991
2992        In-memory contents for files can be provided by passing a list of pairs
2993        as unsaved_files, the first items should be the filenames to be mapped
2994        and the second should be the contents to be substituted for the
2995        file. The contents may be passed as strings or file objects.
2996        """
2997        if unsaved_files is None:
2998            unsaved_files = []
2999
3000        unsaved_files_array = 0
3001        if len(unsaved_files):
3002            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
3003            for i,(name,contents) in enumerate(unsaved_files):
3004                if hasattr(contents, "read"):
3005                    contents = contents.read()
3006                contents = b(contents)
3007                unsaved_files_array[i].name = b(fspath(name))
3008                unsaved_files_array[i].contents = contents
3009                unsaved_files_array[i].length = len(contents)
3010        ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
3011                unsaved_files_array, options)
3012
3013    def save(self, filename):
3014        """Saves the TranslationUnit to a file.
3015
3016        This is equivalent to passing -emit-ast to the clang frontend. The
3017        saved file can be loaded back into a TranslationUnit. Or, if it
3018        corresponds to a header, it can be used as a pre-compiled header file.
3019
3020        If an error occurs while saving, a TranslationUnitSaveError is raised.
3021        If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
3022        the constructed TranslationUnit was not valid at time of save. In this
3023        case, the reason(s) why should be available via
3024        TranslationUnit.diagnostics().
3025
3026        filename -- The path to save the translation unit to (str or PathLike).
3027        """
3028        options = conf.lib.clang_defaultSaveOptions(self)
3029        result = int(conf.lib.clang_saveTranslationUnit(self, fspath(filename),
3030                                                        options))
3031        if result != 0:
3032            raise TranslationUnitSaveError(result,
3033                'Error saving TranslationUnit.')
3034
3035    def codeComplete(self, path, line, column, unsaved_files=None,
3036                     include_macros=False, include_code_patterns=False,
3037                     include_brief_comments=False):
3038        """
3039        Code complete in this translation unit.
3040
3041        In-memory contents for files can be provided by passing a list of pairs
3042        as unsaved_files, the first items should be the filenames to be mapped
3043        and the second should be the contents to be substituted for the
3044        file. The contents may be passed as strings or file objects.
3045        """
3046        options = 0
3047
3048        if include_macros:
3049            options += 1
3050
3051        if include_code_patterns:
3052            options += 2
3053
3054        if include_brief_comments:
3055            options += 4
3056
3057        if unsaved_files is None:
3058            unsaved_files = []
3059
3060        unsaved_files_array = 0
3061        if len(unsaved_files):
3062            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
3063            for i,(name,contents) in enumerate(unsaved_files):
3064                if hasattr(contents, "read"):
3065                    contents = contents.read()
3066                contents = b(contents)
3067                unsaved_files_array[i].name = b(fspath(name))
3068                unsaved_files_array[i].contents = contents
3069                unsaved_files_array[i].length = len(contents)
3070        ptr = conf.lib.clang_codeCompleteAt(self, fspath(path), line, column,
3071                unsaved_files_array, len(unsaved_files), options)
3072        if ptr:
3073            return CodeCompletionResults(ptr)
3074        return None
3075
3076    def get_tokens(self, locations=None, extent=None):
3077        """Obtain tokens in this translation unit.
3078
3079        This is a generator for Token instances. The caller specifies a range
3080        of source code to obtain tokens for. The range can be specified as a
3081        2-tuple of SourceLocation or as a SourceRange. If both are defined,
3082        behavior is undefined.
3083        """
3084        if locations is not None:
3085            extent = SourceRange(start=locations[0], end=locations[1])
3086
3087        return TokenGroup.get_tokens(self, extent)
3088
3089class File(ClangObject):
3090    """
3091    The File class represents a particular source file that is part of a
3092    translation unit.
3093    """
3094
3095    @staticmethod
3096    def from_name(translation_unit, file_name):
3097        """Retrieve a file handle within the given translation unit."""
3098        return File(conf.lib.clang_getFile(translation_unit, fspath(file_name)))
3099
3100    @property
3101    def name(self):
3102        """Return the complete file and path name of the file."""
3103        return conf.lib.clang_getFileName(self)
3104
3105    @property
3106    def time(self):
3107        """Return the last modification time of the file."""
3108        return conf.lib.clang_getFileTime(self)
3109
3110    def __str__(self):
3111        return self.name
3112
3113    def __repr__(self):
3114        return "<File: %s>" % (self.name)
3115
3116    @staticmethod
3117    def from_result(res, fn, args):
3118        assert isinstance(res, c_object_p)
3119        res = File(res)
3120
3121        # Copy a reference to the TranslationUnit to prevent premature GC.
3122        res._tu = args[0]._tu
3123        return res
3124
3125class FileInclusion(object):
3126    """
3127    The FileInclusion class represents the inclusion of one source file by
3128    another via a '#include' directive or as the input file for the translation
3129    unit. This class provides information about the included file, the including
3130    file, the location of the '#include' directive and the depth of the included
3131    file in the stack. Note that the input file has depth 0.
3132    """
3133
3134    def __init__(self, src, tgt, loc, depth):
3135        self.source = src
3136        self.include = tgt
3137        self.location = loc
3138        self.depth = depth
3139
3140    @property
3141    def is_input_file(self):
3142        """True if the included file is the input file."""
3143        return self.depth == 0
3144
3145class CompilationDatabaseError(Exception):
3146    """Represents an error that occurred when working with a CompilationDatabase
3147
3148    Each error is associated to an enumerated value, accessible under
3149    e.cdb_error. Consumers can compare the value with one of the ERROR_
3150    constants in this class.
3151    """
3152
3153    # An unknown error occurred
3154    ERROR_UNKNOWN = 0
3155
3156    # The database could not be loaded
3157    ERROR_CANNOTLOADDATABASE = 1
3158
3159    def __init__(self, enumeration, message):
3160        assert isinstance(enumeration, int)
3161
3162        if enumeration > 1:
3163            raise Exception("Encountered undefined CompilationDatabase error "
3164                            "constant: %d. Please file a bug to have this "
3165                            "value supported." % enumeration)
3166
3167        self.cdb_error = enumeration
3168        Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
3169
3170class CompileCommand(object):
3171    """Represents the compile command used to build a file"""
3172    def __init__(self, cmd, ccmds):
3173        self.cmd = cmd
3174        # Keep a reference to the originating CompileCommands
3175        # to prevent garbage collection
3176        self.ccmds = ccmds
3177
3178    @property
3179    def directory(self):
3180        """Get the working directory for this CompileCommand"""
3181        return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
3182
3183    @property
3184    def filename(self):
3185        """Get the working filename for this CompileCommand"""
3186        return conf.lib.clang_CompileCommand_getFilename(self.cmd)
3187
3188    @property
3189    def arguments(self):
3190        """
3191        Get an iterable object providing each argument in the
3192        command line for the compiler invocation as a _CXString.
3193
3194        Invariant : the first argument is the compiler executable
3195        """
3196        length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
3197        for i in range(length):
3198            yield conf.lib.clang_CompileCommand_getArg(self.cmd, i)
3199
3200class CompileCommands(object):
3201    """
3202    CompileCommands is an iterable object containing all CompileCommand
3203    that can be used for building a specific file.
3204    """
3205    def __init__(self, ccmds):
3206        self.ccmds = ccmds
3207
3208    def __del__(self):
3209        conf.lib.clang_CompileCommands_dispose(self.ccmds)
3210
3211    def __len__(self):
3212        return int(conf.lib.clang_CompileCommands_getSize(self.ccmds))
3213
3214    def __getitem__(self, i):
3215        cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i)
3216        if not cc:
3217            raise IndexError
3218        return CompileCommand(cc, self)
3219
3220    @staticmethod
3221    def from_result(res, fn, args):
3222        if not res:
3223            return None
3224        return CompileCommands(res)
3225
3226class CompilationDatabase(ClangObject):
3227    """
3228    The CompilationDatabase is a wrapper class around
3229    clang::tooling::CompilationDatabase
3230
3231    It enables querying how a specific source file can be built.
3232    """
3233
3234    def __del__(self):
3235        conf.lib.clang_CompilationDatabase_dispose(self)
3236
3237    @staticmethod
3238    def from_result(res, fn, args):
3239        if not res:
3240            raise CompilationDatabaseError(0,
3241                                           "CompilationDatabase loading failed")
3242        return CompilationDatabase(res)
3243
3244    @staticmethod
3245    def fromDirectory(buildDir):
3246        """Builds a CompilationDatabase from the database found in buildDir"""
3247        errorCode = c_uint()
3248        try:
3249            cdb = conf.lib.clang_CompilationDatabase_fromDirectory(fspath(buildDir),
3250                byref(errorCode))
3251        except CompilationDatabaseError as e:
3252            raise CompilationDatabaseError(int(errorCode.value),
3253                                           "CompilationDatabase loading failed")
3254        return cdb
3255
3256    def getCompileCommands(self, filename):
3257        """
3258        Get an iterable object providing all the CompileCommands available to
3259        build filename. Returns None if filename is not found in the database.
3260        """
3261        return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
3262                                                                     fspath(filename))
3263
3264    def getAllCompileCommands(self):
3265        """
3266        Get an iterable object providing all the CompileCommands available from
3267        the database.
3268        """
3269        return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self)
3270
3271
3272class Token(Structure):
3273    """Represents a single token from the preprocessor.
3274
3275    Tokens are effectively segments of source code. Source code is first parsed
3276    into tokens before being converted into the AST and Cursors.
3277
3278    Tokens are obtained from parsed TranslationUnit instances. You currently
3279    can't create tokens manually.
3280    """
3281    _fields_ = [
3282        ('int_data', c_uint * 4),
3283        ('ptr_data', c_void_p)
3284    ]
3285
3286    @property
3287    def spelling(self):
3288        """The spelling of this token.
3289
3290        This is the textual representation of the token in source.
3291        """
3292        return conf.lib.clang_getTokenSpelling(self._tu, self)
3293
3294    @property
3295    def kind(self):
3296        """Obtain the TokenKind of the current token."""
3297        return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
3298
3299    @property
3300    def location(self):
3301        """The SourceLocation this Token occurs at."""
3302        return conf.lib.clang_getTokenLocation(self._tu, self)
3303
3304    @property
3305    def extent(self):
3306        """The SourceRange this Token occupies."""
3307        return conf.lib.clang_getTokenExtent(self._tu, self)
3308
3309    @property
3310    def cursor(self):
3311        """The Cursor this Token corresponds to."""
3312        cursor = Cursor()
3313        cursor._tu = self._tu
3314
3315        conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
3316
3317        return cursor
3318
3319# Now comes the plumbing to hook up the C library.
3320
3321# Register callback types in common container.
3322callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
3323        POINTER(SourceLocation), c_uint, py_object)
3324callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
3325callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object)
3326
3327# Functions strictly alphabetical order.
3328functionList = [
3329  ("clang_annotateTokens",
3330   [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
3331
3332  ("clang_CompilationDatabase_dispose",
3333   [c_object_p]),
3334
3335  ("clang_CompilationDatabase_fromDirectory",
3336   [c_interop_string, POINTER(c_uint)],
3337   c_object_p,
3338   CompilationDatabase.from_result),
3339
3340  ("clang_CompilationDatabase_getAllCompileCommands",
3341   [c_object_p],
3342   c_object_p,
3343   CompileCommands.from_result),
3344
3345  ("clang_CompilationDatabase_getCompileCommands",
3346   [c_object_p, c_interop_string],
3347   c_object_p,
3348   CompileCommands.from_result),
3349
3350  ("clang_CompileCommands_dispose",
3351   [c_object_p]),
3352
3353  ("clang_CompileCommands_getCommand",
3354   [c_object_p, c_uint],
3355   c_object_p),
3356
3357  ("clang_CompileCommands_getSize",
3358   [c_object_p],
3359   c_uint),
3360
3361  ("clang_CompileCommand_getArg",
3362   [c_object_p, c_uint],
3363   _CXString,
3364   _CXString.from_result),
3365
3366  ("clang_CompileCommand_getDirectory",
3367   [c_object_p],
3368   _CXString,
3369   _CXString.from_result),
3370
3371  ("clang_CompileCommand_getFilename",
3372   [c_object_p],
3373   _CXString,
3374   _CXString.from_result),
3375
3376  ("clang_CompileCommand_getNumArgs",
3377   [c_object_p],
3378   c_uint),
3379
3380  ("clang_codeCompleteAt",
3381   [TranslationUnit, c_interop_string, c_int, c_int, c_void_p, c_int, c_int],
3382   POINTER(CCRStructure)),
3383
3384  ("clang_codeCompleteGetDiagnostic",
3385   [CodeCompletionResults, c_int],
3386   Diagnostic),
3387
3388  ("clang_codeCompleteGetNumDiagnostics",
3389   [CodeCompletionResults],
3390   c_int),
3391
3392  ("clang_createIndex",
3393   [c_int, c_int],
3394   c_object_p),
3395
3396  ("clang_createTranslationUnit",
3397   [Index, c_interop_string],
3398   c_object_p),
3399
3400  ("clang_CXXConstructor_isConvertingConstructor",
3401   [Cursor],
3402   bool),
3403
3404  ("clang_CXXConstructor_isCopyConstructor",
3405   [Cursor],
3406   bool),
3407
3408  ("clang_CXXConstructor_isDefaultConstructor",
3409   [Cursor],
3410   bool),
3411
3412  ("clang_CXXConstructor_isMoveConstructor",
3413   [Cursor],
3414   bool),
3415
3416  ("clang_CXXField_isMutable",
3417   [Cursor],
3418   bool),
3419
3420  ("clang_CXXMethod_isConst",
3421   [Cursor],
3422   bool),
3423
3424  ("clang_CXXMethod_isDefaulted",
3425   [Cursor],
3426   bool),
3427
3428  ("clang_CXXMethod_isPureVirtual",
3429   [Cursor],
3430   bool),
3431
3432  ("clang_CXXMethod_isStatic",
3433   [Cursor],
3434   bool),
3435
3436  ("clang_CXXMethod_isVirtual",
3437   [Cursor],
3438   bool),
3439
3440  ("clang_CXXRecord_isAbstract",
3441   [Cursor],
3442   bool),
3443
3444  ("clang_EnumDecl_isScoped",
3445   [Cursor],
3446   bool),
3447
3448  ("clang_defaultDiagnosticDisplayOptions",
3449   [],
3450   c_uint),
3451
3452  ("clang_defaultSaveOptions",
3453   [TranslationUnit],
3454   c_uint),
3455
3456  ("clang_disposeCodeCompleteResults",
3457   [CodeCompletionResults]),
3458
3459# ("clang_disposeCXTUResourceUsage",
3460#  [CXTUResourceUsage]),
3461
3462  ("clang_disposeDiagnostic",
3463   [Diagnostic]),
3464
3465  ("clang_disposeIndex",
3466   [Index]),
3467
3468  ("clang_disposeString",
3469   [_CXString]),
3470
3471  ("clang_disposeTokens",
3472   [TranslationUnit, POINTER(Token), c_uint]),
3473
3474  ("clang_disposeTranslationUnit",
3475   [TranslationUnit]),
3476
3477  ("clang_equalCursors",
3478   [Cursor, Cursor],
3479   bool),
3480
3481  ("clang_equalLocations",
3482   [SourceLocation, SourceLocation],
3483   bool),
3484
3485  ("clang_equalRanges",
3486   [SourceRange, SourceRange],
3487   bool),
3488
3489  ("clang_equalTypes",
3490   [Type, Type],
3491   bool),
3492
3493  ("clang_formatDiagnostic",
3494   [Diagnostic, c_uint],
3495   _CXString,
3496   _CXString.from_result),
3497
3498  ("clang_getArgType",
3499   [Type, c_uint],
3500   Type,
3501   Type.from_result),
3502
3503  ("clang_getArrayElementType",
3504   [Type],
3505   Type,
3506   Type.from_result),
3507
3508  ("clang_getArraySize",
3509   [Type],
3510   c_longlong),
3511
3512  ("clang_getFieldDeclBitWidth",
3513   [Cursor],
3514   c_int),
3515
3516  ("clang_getCanonicalCursor",
3517   [Cursor],
3518   Cursor,
3519   Cursor.from_cursor_result),
3520
3521  ("clang_getCanonicalType",
3522   [Type],
3523   Type,
3524   Type.from_result),
3525
3526  ("clang_getChildDiagnostics",
3527   [Diagnostic],
3528   c_object_p),
3529
3530  ("clang_getCompletionAvailability",
3531   [c_void_p],
3532   c_int),
3533
3534  ("clang_getCompletionBriefComment",
3535   [c_void_p],
3536   _CXString,
3537   _CXString.from_result),
3538
3539  ("clang_getCompletionChunkCompletionString",
3540   [c_void_p, c_int],
3541   c_object_p),
3542
3543  ("clang_getCompletionChunkKind",
3544   [c_void_p, c_int],
3545   c_int),
3546
3547  ("clang_getCompletionChunkText",
3548   [c_void_p, c_int],
3549   _CXString,
3550   _CXString.from_result),
3551
3552  ("clang_getCompletionPriority",
3553   [c_void_p],
3554   c_int),
3555
3556  ("clang_getCString",
3557   [_CXString],
3558   c_interop_string,
3559   c_interop_string.to_python_string),
3560
3561  ("clang_getCursor",
3562   [TranslationUnit, SourceLocation],
3563   Cursor),
3564
3565  ("clang_getCursorAvailability",
3566   [Cursor],
3567   c_int),
3568
3569  ("clang_getCursorDefinition",
3570   [Cursor],
3571   Cursor,
3572   Cursor.from_result),
3573
3574  ("clang_getCursorDisplayName",
3575   [Cursor],
3576   _CXString,
3577   _CXString.from_result),
3578
3579  ("clang_getCursorExtent",
3580   [Cursor],
3581   SourceRange),
3582
3583  ("clang_getCursorLexicalParent",
3584   [Cursor],
3585   Cursor,
3586   Cursor.from_cursor_result),
3587
3588  ("clang_getCursorLocation",
3589   [Cursor],
3590   SourceLocation),
3591
3592  ("clang_getCursorReferenced",
3593   [Cursor],
3594   Cursor,
3595   Cursor.from_result),
3596
3597  ("clang_getCursorReferenceNameRange",
3598   [Cursor, c_uint, c_uint],
3599   SourceRange),
3600
3601  ("clang_getCursorResultType",
3602   [Cursor],
3603   Type,
3604   Type.from_result),
3605
3606  ("clang_getCursorSemanticParent",
3607   [Cursor],
3608   Cursor,
3609   Cursor.from_cursor_result),
3610
3611  ("clang_getCursorSpelling",
3612   [Cursor],
3613   _CXString,
3614   _CXString.from_result),
3615
3616  ("clang_getCursorType",
3617   [Cursor],
3618   Type,
3619   Type.from_result),
3620
3621  ("clang_getCursorUSR",
3622   [Cursor],
3623   _CXString,
3624   _CXString.from_result),
3625
3626  ("clang_Cursor_getMangling",
3627   [Cursor],
3628   _CXString,
3629   _CXString.from_result),
3630
3631# ("clang_getCXTUResourceUsage",
3632#  [TranslationUnit],
3633#  CXTUResourceUsage),
3634
3635  ("clang_getCXXAccessSpecifier",
3636   [Cursor],
3637   c_uint),
3638
3639  ("clang_getDeclObjCTypeEncoding",
3640   [Cursor],
3641   _CXString,
3642   _CXString.from_result),
3643
3644  ("clang_getDiagnostic",
3645   [c_object_p, c_uint],
3646   c_object_p),
3647
3648  ("clang_getDiagnosticCategory",
3649   [Diagnostic],
3650   c_uint),
3651
3652  ("clang_getDiagnosticCategoryText",
3653   [Diagnostic],
3654   _CXString,
3655   _CXString.from_result),
3656
3657  ("clang_getDiagnosticFixIt",
3658   [Diagnostic, c_uint, POINTER(SourceRange)],
3659   _CXString,
3660   _CXString.from_result),
3661
3662  ("clang_getDiagnosticInSet",
3663   [c_object_p, c_uint],
3664   c_object_p),
3665
3666  ("clang_getDiagnosticLocation",
3667   [Diagnostic],
3668   SourceLocation),
3669
3670  ("clang_getDiagnosticNumFixIts",
3671   [Diagnostic],
3672   c_uint),
3673
3674  ("clang_getDiagnosticNumRanges",
3675   [Diagnostic],
3676   c_uint),
3677
3678  ("clang_getDiagnosticOption",
3679   [Diagnostic, POINTER(_CXString)],
3680   _CXString,
3681   _CXString.from_result),
3682
3683  ("clang_getDiagnosticRange",
3684   [Diagnostic, c_uint],
3685   SourceRange),
3686
3687  ("clang_getDiagnosticSeverity",
3688   [Diagnostic],
3689   c_int),
3690
3691  ("clang_getDiagnosticSpelling",
3692   [Diagnostic],
3693   _CXString,
3694   _CXString.from_result),
3695
3696  ("clang_getElementType",
3697   [Type],
3698   Type,
3699   Type.from_result),
3700
3701  ("clang_getEnumConstantDeclUnsignedValue",
3702   [Cursor],
3703   c_ulonglong),
3704
3705  ("clang_getEnumConstantDeclValue",
3706   [Cursor],
3707   c_longlong),
3708
3709  ("clang_getEnumDeclIntegerType",
3710   [Cursor],
3711   Type,
3712   Type.from_result),
3713
3714  ("clang_getFile",
3715   [TranslationUnit, c_interop_string],
3716   c_object_p),
3717
3718  ("clang_getFileName",
3719   [File],
3720   _CXString,
3721   _CXString.from_result),
3722
3723  ("clang_getFileTime",
3724   [File],
3725   c_uint),
3726
3727  ("clang_getIBOutletCollectionType",
3728   [Cursor],
3729   Type,
3730   Type.from_result),
3731
3732  ("clang_getIncludedFile",
3733   [Cursor],
3734   c_object_p,
3735   File.from_result),
3736
3737  ("clang_getInclusions",
3738   [TranslationUnit, callbacks['translation_unit_includes'], py_object]),
3739
3740  ("clang_getInstantiationLocation",
3741   [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
3742    POINTER(c_uint)]),
3743
3744  ("clang_getLocation",
3745   [TranslationUnit, File, c_uint, c_uint],
3746   SourceLocation),
3747
3748  ("clang_getLocationForOffset",
3749   [TranslationUnit, File, c_uint],
3750   SourceLocation),
3751
3752  ("clang_getNullCursor",
3753   None,
3754   Cursor),
3755
3756  ("clang_getNumArgTypes",
3757   [Type],
3758   c_uint),
3759
3760  ("clang_getNumCompletionChunks",
3761   [c_void_p],
3762   c_int),
3763
3764  ("clang_getNumDiagnostics",
3765   [c_object_p],
3766   c_uint),
3767
3768  ("clang_getNumDiagnosticsInSet",
3769   [c_object_p],
3770   c_uint),
3771
3772  ("clang_getNumElements",
3773   [Type],
3774   c_longlong),
3775
3776  ("clang_getNumOverloadedDecls",
3777   [Cursor],
3778   c_uint),
3779
3780  ("clang_getOverloadedDecl",
3781   [Cursor, c_uint],
3782   Cursor,
3783   Cursor.from_cursor_result),
3784
3785  ("clang_getPointeeType",
3786   [Type],
3787   Type,
3788   Type.from_result),
3789
3790  ("clang_getRange",
3791   [SourceLocation, SourceLocation],
3792   SourceRange),
3793
3794  ("clang_getRangeEnd",
3795   [SourceRange],
3796   SourceLocation),
3797
3798  ("clang_getRangeStart",
3799   [SourceRange],
3800   SourceLocation),
3801
3802  ("clang_getResultType",
3803   [Type],
3804   Type,
3805   Type.from_result),
3806
3807  ("clang_getSpecializedCursorTemplate",
3808   [Cursor],
3809   Cursor,
3810   Cursor.from_cursor_result),
3811
3812  ("clang_getTemplateCursorKind",
3813   [Cursor],
3814   c_uint),
3815
3816  ("clang_getTokenExtent",
3817   [TranslationUnit, Token],
3818   SourceRange),
3819
3820  ("clang_getTokenKind",
3821   [Token],
3822   c_uint),
3823
3824  ("clang_getTokenLocation",
3825   [TranslationUnit, Token],
3826   SourceLocation),
3827
3828  ("clang_getTokenSpelling",
3829   [TranslationUnit, Token],
3830   _CXString,
3831   _CXString.from_result),
3832
3833  ("clang_getTranslationUnitCursor",
3834   [TranslationUnit],
3835   Cursor,
3836   Cursor.from_result),
3837
3838  ("clang_getTranslationUnitSpelling",
3839   [TranslationUnit],
3840   _CXString,
3841   _CXString.from_result),
3842
3843  ("clang_getTUResourceUsageName",
3844   [c_uint],
3845   c_interop_string,
3846   c_interop_string.to_python_string),
3847
3848  ("clang_getTypeDeclaration",
3849   [Type],
3850   Cursor,
3851   Cursor.from_result),
3852
3853  ("clang_getTypedefDeclUnderlyingType",
3854   [Cursor],
3855   Type,
3856   Type.from_result),
3857
3858  ("clang_getTypedefName",
3859   [Type],
3860   _CXString,
3861   _CXString.from_result),
3862
3863  ("clang_getTypeKindSpelling",
3864   [c_uint],
3865   _CXString,
3866   _CXString.from_result),
3867
3868  ("clang_getTypeSpelling",
3869   [Type],
3870   _CXString,
3871   _CXString.from_result),
3872
3873  ("clang_hashCursor",
3874   [Cursor],
3875   c_uint),
3876
3877  ("clang_isAttribute",
3878   [CursorKind],
3879   bool),
3880
3881  ("clang_isConstQualifiedType",
3882   [Type],
3883   bool),
3884
3885  ("clang_isCursorDefinition",
3886   [Cursor],
3887   bool),
3888
3889  ("clang_isDeclaration",
3890   [CursorKind],
3891   bool),
3892
3893  ("clang_isExpression",
3894   [CursorKind],
3895   bool),
3896
3897  ("clang_isFileMultipleIncludeGuarded",
3898   [TranslationUnit, File],
3899   bool),
3900
3901  ("clang_isFunctionTypeVariadic",
3902   [Type],
3903   bool),
3904
3905  ("clang_isInvalid",
3906   [CursorKind],
3907   bool),
3908
3909  ("clang_isPODType",
3910   [Type],
3911   bool),
3912
3913  ("clang_isPreprocessing",
3914   [CursorKind],
3915   bool),
3916
3917  ("clang_isReference",
3918   [CursorKind],
3919   bool),
3920
3921  ("clang_isRestrictQualifiedType",
3922   [Type],
3923   bool),
3924
3925  ("clang_isStatement",
3926   [CursorKind],
3927   bool),
3928
3929  ("clang_isTranslationUnit",
3930   [CursorKind],
3931   bool),
3932
3933  ("clang_isUnexposed",
3934   [CursorKind],
3935   bool),
3936
3937  ("clang_isVirtualBase",
3938   [Cursor],
3939   bool),
3940
3941  ("clang_isVolatileQualifiedType",
3942   [Type],
3943   bool),
3944
3945  ("clang_parseTranslationUnit",
3946   [Index, c_interop_string, c_void_p, c_int, c_void_p, c_int, c_int],
3947   c_object_p),
3948
3949  ("clang_reparseTranslationUnit",
3950   [TranslationUnit, c_int, c_void_p, c_int],
3951   c_int),
3952
3953  ("clang_saveTranslationUnit",
3954   [TranslationUnit, c_interop_string, c_uint],
3955   c_int),
3956
3957  ("clang_tokenize",
3958   [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
3959
3960  ("clang_visitChildren",
3961   [Cursor, callbacks['cursor_visit'], py_object],
3962   c_uint),
3963
3964  ("clang_Cursor_getNumArguments",
3965   [Cursor],
3966   c_int),
3967
3968  ("clang_Cursor_getArgument",
3969   [Cursor, c_uint],
3970   Cursor,
3971   Cursor.from_result),
3972
3973  ("clang_Cursor_getNumTemplateArguments",
3974   [Cursor],
3975   c_int),
3976
3977  ("clang_Cursor_getTemplateArgumentKind",
3978   [Cursor, c_uint],
3979   TemplateArgumentKind.from_id),
3980
3981  ("clang_Cursor_getTemplateArgumentType",
3982   [Cursor, c_uint],
3983   Type,
3984   Type.from_result),
3985
3986  ("clang_Cursor_getTemplateArgumentValue",
3987   [Cursor, c_uint],
3988   c_longlong),
3989
3990  ("clang_Cursor_getTemplateArgumentUnsignedValue",
3991   [Cursor, c_uint],
3992   c_ulonglong),
3993
3994  ("clang_Cursor_isAnonymous",
3995   [Cursor],
3996   bool),
3997
3998  ("clang_Cursor_isBitField",
3999   [Cursor],
4000   bool),
4001
4002  ("clang_Cursor_getBriefCommentText",
4003   [Cursor],
4004   _CXString,
4005   _CXString.from_result),
4006
4007  ("clang_Cursor_getRawCommentText",
4008   [Cursor],
4009   _CXString,
4010   _CXString.from_result),
4011
4012  ("clang_Cursor_getOffsetOfField",
4013   [Cursor],
4014   c_longlong),
4015
4016  ("clang_Type_getAlignOf",
4017   [Type],
4018   c_longlong),
4019
4020  ("clang_Type_getClassType",
4021   [Type],
4022   Type,
4023   Type.from_result),
4024
4025  ("clang_Type_getNumTemplateArguments",
4026   [Type],
4027   c_int),
4028
4029  ("clang_Type_getTemplateArgumentAsType",
4030   [Type, c_uint],
4031   Type,
4032   Type.from_result),
4033
4034  ("clang_Type_getOffsetOf",
4035   [Type, c_interop_string],
4036   c_longlong),
4037
4038  ("clang_Type_getSizeOf",
4039   [Type],
4040   c_longlong),
4041
4042  ("clang_Type_getCXXRefQualifier",
4043   [Type],
4044   c_uint),
4045
4046  ("clang_Type_getNamedType",
4047   [Type],
4048   Type,
4049   Type.from_result),
4050
4051  ("clang_Type_visitFields",
4052   [Type, callbacks['fields_visit'], py_object],
4053   c_uint),
4054]
4055
4056class LibclangError(Exception):
4057    def __init__(self, message):
4058        self.m = message
4059
4060    def __str__(self):
4061        return self.m
4062
4063def register_function(lib, item, ignore_errors):
4064    # A function may not exist, if these bindings are used with an older or
4065    # incompatible version of libclang.so.
4066    try:
4067        func = getattr(lib, item[0])
4068    except AttributeError as e:
4069        msg = str(e) + ". Please ensure that your python bindings are "\
4070                       "compatible with your libclang.so version."
4071        if ignore_errors:
4072            return
4073        raise LibclangError(msg)
4074
4075    if len(item) >= 2:
4076        func.argtypes = item[1]
4077
4078    if len(item) >= 3:
4079        func.restype = item[2]
4080
4081    if len(item) == 4:
4082        func.errcheck = item[3]
4083
4084def register_functions(lib, ignore_errors):
4085    """Register function prototypes with a libclang library instance.
4086
4087    This must be called as part of library instantiation so Python knows how
4088    to call out to the shared library.
4089    """
4090
4091    def register(item):
4092        return register_function(lib, item, ignore_errors)
4093
4094    for f in functionList:
4095        register(f)
4096
4097class Config(object):
4098    library_path = None
4099    library_file = None
4100    compatibility_check = True
4101    loaded = False
4102
4103    @staticmethod
4104    def set_library_path(path):
4105        """Set the path in which to search for libclang"""
4106        if Config.loaded:
4107            raise Exception("library path must be set before before using " \
4108                            "any other functionalities in libclang.")
4109
4110        Config.library_path = fspath(path)
4111
4112    @staticmethod
4113    def set_library_file(filename):
4114        """Set the exact location of libclang"""
4115        if Config.loaded:
4116            raise Exception("library file must be set before before using " \
4117                            "any other functionalities in libclang.")
4118
4119        Config.library_file = fspath(filename)
4120
4121    @staticmethod
4122    def set_compatibility_check(check_status):
4123        """ Perform compatibility check when loading libclang
4124
4125        The python bindings are only tested and evaluated with the version of
4126        libclang they are provided with. To ensure correct behavior a (limited)
4127        compatibility check is performed when loading the bindings. This check
4128        will throw an exception, as soon as it fails.
4129
4130        In case these bindings are used with an older version of libclang, parts
4131        that have been stable between releases may still work. Users of the
4132        python bindings can disable the compatibility check. This will cause
4133        the python bindings to load, even though they are written for a newer
4134        version of libclang. Failures now arise if unsupported or incompatible
4135        features are accessed. The user is required to test themselves if the
4136        features they are using are available and compatible between different
4137        libclang versions.
4138        """
4139        if Config.loaded:
4140            raise Exception("compatibility_check must be set before before " \
4141                            "using any other functionalities in libclang.")
4142
4143        Config.compatibility_check = check_status
4144
4145    @CachedProperty
4146    def lib(self):
4147        lib = self.get_cindex_library()
4148        register_functions(lib, not Config.compatibility_check)
4149        Config.loaded = True
4150        return lib
4151
4152    def get_filename(self):
4153        if Config.library_file:
4154            return Config.library_file
4155
4156        import platform
4157        name = platform.system()
4158
4159        if name == 'Darwin':
4160            file = 'libclang.dylib'
4161        elif name == 'Windows':
4162            file = 'libclang.dll'
4163        else:
4164            file = 'libclang.so'
4165
4166        if Config.library_path:
4167            file = Config.library_path + '/' + file
4168
4169        return file
4170
4171    def get_cindex_library(self):
4172        try:
4173            library = cdll.LoadLibrary(self.get_filename())
4174        except OSError as e:
4175            msg = str(e) + ". To provide a path to libclang use " \
4176                           "Config.set_library_path() or " \
4177                           "Config.set_library_file()."
4178            raise LibclangError(msg)
4179
4180        return library
4181
4182    def function_exists(self, name):
4183        try:
4184            getattr(self.lib, name)
4185        except AttributeError:
4186            return False
4187
4188        return True
4189
4190def register_enumerations():
4191    for name, value in clang.enumerations.TokenKinds:
4192        TokenKind.register(value, name)
4193
4194conf = Config()
4195register_enumerations()
4196
4197__all__ = [
4198    'AvailabilityKind',
4199    'Config',
4200    'CodeCompletionResults',
4201    'CompilationDatabase',
4202    'CompileCommands',
4203    'CompileCommand',
4204    'CursorKind',
4205    'Cursor',
4206    'Diagnostic',
4207    'File',
4208    'FixIt',
4209    'Index',
4210    'LinkageKind',
4211    'SourceLocation',
4212    'SourceRange',
4213    'TLSKind',
4214    'TokenKind',
4215    'Token',
4216    'TranslationUnitLoadError',
4217    'TranslationUnit',
4218    'TypeKind',
4219    'Type',
4220]
4221