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 autorelease 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(350)
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_deleted_method(self):
1477        """Returns True if the cursor refers to a C++ member function or member
1478        function template that is declared '= delete'.
1479        """
1480        return conf.lib.clang_CXXMethod_isDeleted(self)
1481
1482    def is_copy_assignment_operator_method(self):
1483        """Returnrs True if the cursor refers to a copy-assignment operator.
1484
1485        A copy-assignment operator `X::operator=` is a non-static,
1486        non-template member function of _class_ `X` with exactly one
1487        parameter of type `X`, `X&`, `const X&`, `volatile X&` or `const
1488        volatile X&`.
1489
1490
1491        That is, for example, the `operator=` in:
1492
1493           class Foo {
1494               bool operator=(const volatile Foo&);
1495           };
1496
1497        Is a copy-assignment operator, while the `operator=` in:
1498
1499           class Bar {
1500               bool operator=(const int&);
1501           };
1502
1503        Is not.
1504        """
1505        return conf.lib.clang_CXXMethod_isCopyAssignmentOperator(self)
1506
1507    def is_move_assignment_operator_method(self):
1508        """Returnrs True if the cursor refers to a move-assignment operator.
1509
1510        A move-assignment operator `X::operator=` is a non-static,
1511        non-template member function of _class_ `X` with exactly one
1512        parameter of type `X&&`, `const X&&`, `volatile X&&` or `const
1513        volatile X&&`.
1514
1515
1516        That is, for example, the `operator=` in:
1517
1518           class Foo {
1519               bool operator=(const volatile Foo&&);
1520           };
1521
1522        Is a move-assignment operator, while the `operator=` in:
1523
1524           class Bar {
1525               bool operator=(const int&&);
1526           };
1527
1528        Is not.
1529        """
1530        return conf.lib.clang_CXXMethod_isMoveAssignmentOperator(self)
1531
1532    def is_mutable_field(self):
1533        """Returns True if the cursor refers to a C++ field that is declared
1534        'mutable'.
1535        """
1536        return conf.lib.clang_CXXField_isMutable(self)
1537
1538    def is_pure_virtual_method(self):
1539        """Returns True if the cursor refers to a C++ member function or member
1540        function template that is declared pure virtual.
1541        """
1542        return conf.lib.clang_CXXMethod_isPureVirtual(self)
1543
1544    def is_static_method(self):
1545        """Returns True if the cursor refers to a C++ member function or member
1546        function template that is declared 'static'.
1547        """
1548        return conf.lib.clang_CXXMethod_isStatic(self)
1549
1550    def is_virtual_method(self):
1551        """Returns True if the cursor refers to a C++ member function or member
1552        function template that is declared 'virtual'.
1553        """
1554        return conf.lib.clang_CXXMethod_isVirtual(self)
1555
1556    def is_abstract_record(self):
1557        """Returns True if the cursor refers to a C++ record declaration
1558        that has pure virtual member functions.
1559        """
1560        return conf.lib.clang_CXXRecord_isAbstract(self)
1561
1562    def is_scoped_enum(self):
1563        """Returns True if the cursor refers to a scoped enum declaration.
1564        """
1565        return conf.lib.clang_EnumDecl_isScoped(self)
1566
1567    def get_definition(self):
1568        """
1569        If the cursor is a reference to a declaration or a declaration of
1570        some entity, return a cursor that points to the definition of that
1571        entity.
1572        """
1573        # TODO: Should probably check that this is either a reference or
1574        # declaration prior to issuing the lookup.
1575        return conf.lib.clang_getCursorDefinition(self)
1576
1577    def get_usr(self):
1578        """Return the Unified Symbol Resolution (USR) for the entity referenced
1579        by the given cursor (or None).
1580
1581        A Unified Symbol Resolution (USR) is a string that identifies a
1582        particular entity (function, class, variable, etc.) within a
1583        program. USRs can be compared across translation units to determine,
1584        e.g., when references in one translation refer to an entity defined in
1585        another translation unit."""
1586        return conf.lib.clang_getCursorUSR(self)
1587
1588    def get_included_file(self):
1589        """Returns the File that is included by the current inclusion cursor."""
1590        assert self.kind == CursorKind.INCLUSION_DIRECTIVE
1591
1592        return conf.lib.clang_getIncludedFile(self)
1593
1594    @property
1595    def kind(self):
1596        """Return the kind of this cursor."""
1597        return CursorKind.from_id(self._kind_id)
1598
1599    @property
1600    def spelling(self):
1601        """Return the spelling of the entity pointed at by the cursor."""
1602        if not hasattr(self, '_spelling'):
1603            self._spelling = conf.lib.clang_getCursorSpelling(self)
1604
1605        return self._spelling
1606
1607    @property
1608    def displayname(self):
1609        """
1610        Return the display name for the entity referenced by this cursor.
1611
1612        The display name contains extra information that helps identify the
1613        cursor, such as the parameters of a function or template or the
1614        arguments of a class template specialization.
1615        """
1616        if not hasattr(self, '_displayname'):
1617            self._displayname = conf.lib.clang_getCursorDisplayName(self)
1618
1619        return self._displayname
1620
1621    @property
1622    def mangled_name(self):
1623        """Return the mangled name for the entity referenced by this cursor."""
1624        if not hasattr(self, '_mangled_name'):
1625            self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
1626
1627        return self._mangled_name
1628
1629    @property
1630    def location(self):
1631        """
1632        Return the source location (the starting character) of the entity
1633        pointed at by the cursor.
1634        """
1635        if not hasattr(self, '_loc'):
1636            self._loc = conf.lib.clang_getCursorLocation(self)
1637
1638        return self._loc
1639
1640    @property
1641    def linkage(self):
1642        """Return the linkage of this cursor."""
1643        if not hasattr(self, '_linkage'):
1644            self._linkage = conf.lib.clang_getCursorLinkage(self)
1645
1646        return LinkageKind.from_id(self._linkage)
1647
1648    @property
1649    def tls_kind(self):
1650        """Return the thread-local storage (TLS) kind of this cursor."""
1651        if not hasattr(self, '_tls_kind'):
1652            self._tls_kind = conf.lib.clang_getCursorTLSKind(self)
1653
1654        return TLSKind.from_id(self._tls_kind)
1655
1656    @property
1657    def extent(self):
1658        """
1659        Return the source range (the range of text) occupied by the entity
1660        pointed at by the cursor.
1661        """
1662        if not hasattr(self, '_extent'):
1663            self._extent = conf.lib.clang_getCursorExtent(self)
1664
1665        return self._extent
1666
1667    @property
1668    def storage_class(self):
1669        """
1670        Retrieves the storage class (if any) of the entity pointed at by the
1671        cursor.
1672        """
1673        if not hasattr(self, '_storage_class'):
1674            self._storage_class = conf.lib.clang_Cursor_getStorageClass(self)
1675
1676        return StorageClass.from_id(self._storage_class)
1677
1678    @property
1679    def availability(self):
1680        """
1681        Retrieves the availability of the entity pointed at by the cursor.
1682        """
1683        if not hasattr(self, '_availability'):
1684            self._availability = conf.lib.clang_getCursorAvailability(self)
1685
1686        return AvailabilityKind.from_id(self._availability)
1687
1688    @property
1689    def access_specifier(self):
1690        """
1691        Retrieves the access specifier (if any) of the entity pointed at by the
1692        cursor.
1693        """
1694        if not hasattr(self, '_access_specifier'):
1695            self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self)
1696
1697        return AccessSpecifier.from_id(self._access_specifier)
1698
1699    @property
1700    def type(self):
1701        """
1702        Retrieve the Type (if any) of the entity pointed at by the cursor.
1703        """
1704        if not hasattr(self, '_type'):
1705            self._type = conf.lib.clang_getCursorType(self)
1706
1707        return self._type
1708
1709    @property
1710    def canonical(self):
1711        """Return the canonical Cursor corresponding to this Cursor.
1712
1713        The canonical cursor is the cursor which is representative for the
1714        underlying entity. For example, if you have multiple forward
1715        declarations for the same class, the canonical cursor for the forward
1716        declarations will be identical.
1717        """
1718        if not hasattr(self, '_canonical'):
1719            self._canonical = conf.lib.clang_getCanonicalCursor(self)
1720
1721        return self._canonical
1722
1723    @property
1724    def result_type(self):
1725        """Retrieve the Type of the result for this Cursor."""
1726        if not hasattr(self, '_result_type'):
1727            self._result_type = conf.lib.clang_getCursorResultType(self)
1728
1729        return self._result_type
1730
1731    @property
1732    def exception_specification_kind(self):
1733        '''
1734        Retrieve the exception specification kind, which is one of the values
1735        from the ExceptionSpecificationKind enumeration.
1736        '''
1737        if not hasattr(self, '_exception_specification_kind'):
1738            exc_kind = conf.lib.clang_getCursorExceptionSpecificationType(self)
1739            self._exception_specification_kind = ExceptionSpecificationKind.from_id(exc_kind)
1740
1741        return self._exception_specification_kind
1742
1743    @property
1744    def underlying_typedef_type(self):
1745        """Return the underlying type of a typedef declaration.
1746
1747        Returns a Type for the typedef this cursor is a declaration for. If
1748        the current cursor is not a typedef, this raises.
1749        """
1750        if not hasattr(self, '_underlying_type'):
1751            assert self.kind.is_declaration()
1752            self._underlying_type = \
1753              conf.lib.clang_getTypedefDeclUnderlyingType(self)
1754
1755        return self._underlying_type
1756
1757    @property
1758    def enum_type(self):
1759        """Return the integer type of an enum declaration.
1760
1761        Returns a Type corresponding to an integer. If the cursor is not for an
1762        enum, this raises.
1763        """
1764        if not hasattr(self, '_enum_type'):
1765            assert self.kind == CursorKind.ENUM_DECL
1766            self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
1767
1768        return self._enum_type
1769
1770    @property
1771    def enum_value(self):
1772        """Return the value of an enum constant."""
1773        if not hasattr(self, '_enum_value'):
1774            assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1775            # Figure out the underlying type of the enum to know if it
1776            # is a signed or unsigned quantity.
1777            underlying_type = self.type
1778            if underlying_type.kind == TypeKind.ENUM:
1779                underlying_type = underlying_type.get_declaration().enum_type
1780            if underlying_type.kind in (TypeKind.CHAR_U,
1781                                        TypeKind.UCHAR,
1782                                        TypeKind.CHAR16,
1783                                        TypeKind.CHAR32,
1784                                        TypeKind.USHORT,
1785                                        TypeKind.UINT,
1786                                        TypeKind.ULONG,
1787                                        TypeKind.ULONGLONG,
1788                                        TypeKind.UINT128):
1789                self._enum_value = \
1790                  conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
1791            else:
1792                self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
1793        return self._enum_value
1794
1795    @property
1796    def objc_type_encoding(self):
1797        """Return the Objective-C type encoding as a str."""
1798        if not hasattr(self, '_objc_type_encoding'):
1799            self._objc_type_encoding = \
1800              conf.lib.clang_getDeclObjCTypeEncoding(self)
1801
1802        return self._objc_type_encoding
1803
1804    @property
1805    def hash(self):
1806        """Returns a hash of the cursor as an int."""
1807        if not hasattr(self, '_hash'):
1808            self._hash = conf.lib.clang_hashCursor(self)
1809
1810        return self._hash
1811
1812    @property
1813    def semantic_parent(self):
1814        """Return the semantic parent for this cursor."""
1815        if not hasattr(self, '_semantic_parent'):
1816            self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
1817
1818        return self._semantic_parent
1819
1820    @property
1821    def lexical_parent(self):
1822        """Return the lexical parent for this cursor."""
1823        if not hasattr(self, '_lexical_parent'):
1824            self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
1825
1826        return self._lexical_parent
1827
1828    @property
1829    def translation_unit(self):
1830        """Returns the TranslationUnit to which this Cursor belongs."""
1831        # If this triggers an AttributeError, the instance was not properly
1832        # created.
1833        return self._tu
1834
1835    @property
1836    def referenced(self):
1837        """
1838        For a cursor that is a reference, returns a cursor
1839        representing the entity that it references.
1840        """
1841        if not hasattr(self, '_referenced'):
1842            self._referenced = conf.lib.clang_getCursorReferenced(self)
1843
1844        return self._referenced
1845
1846    @property
1847    def brief_comment(self):
1848        """Returns the brief comment text associated with that Cursor"""
1849        return conf.lib.clang_Cursor_getBriefCommentText(self)
1850
1851    @property
1852    def raw_comment(self):
1853        """Returns the raw comment text associated with that Cursor"""
1854        return conf.lib.clang_Cursor_getRawCommentText(self)
1855
1856    def get_arguments(self):
1857        """Return an iterator for accessing the arguments of this cursor."""
1858        num_args = conf.lib.clang_Cursor_getNumArguments(self)
1859        for i in range(0, num_args):
1860            yield conf.lib.clang_Cursor_getArgument(self, i)
1861
1862    def get_num_template_arguments(self):
1863        """Returns the number of template args associated with this cursor."""
1864        return conf.lib.clang_Cursor_getNumTemplateArguments(self)
1865
1866    def get_template_argument_kind(self, num):
1867        """Returns the TemplateArgumentKind for the indicated template
1868        argument."""
1869        return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num)
1870
1871    def get_template_argument_type(self, num):
1872        """Returns the CXType for the indicated template argument."""
1873        return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
1874
1875    def get_template_argument_value(self, num):
1876        """Returns the value of the indicated arg as a signed 64b integer."""
1877        return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num)
1878
1879    def get_template_argument_unsigned_value(self, num):
1880        """Returns the value of the indicated arg as an unsigned 64b integer."""
1881        return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num)
1882
1883    def get_children(self):
1884        """Return an iterator for accessing the children of this cursor."""
1885
1886        # FIXME: Expose iteration from CIndex, PR6125.
1887        def visitor(child, parent, children):
1888            # FIXME: Document this assertion in API.
1889            # FIXME: There should just be an isNull method.
1890            assert child != conf.lib.clang_getNullCursor()
1891
1892            # Create reference to TU so it isn't GC'd before Cursor.
1893            child._tu = self._tu
1894            children.append(child)
1895            return 1 # continue
1896        children = []
1897        conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
1898            children)
1899        return iter(children)
1900
1901    def walk_preorder(self):
1902        """Depth-first preorder walk over the cursor and its descendants.
1903
1904        Yields cursors.
1905        """
1906        yield self
1907        for child in self.get_children():
1908            for descendant in child.walk_preorder():
1909                yield descendant
1910
1911    def get_tokens(self):
1912        """Obtain Token instances formulating that compose this Cursor.
1913
1914        This is a generator for Token instances. It returns all tokens which
1915        occupy the extent this cursor occupies.
1916        """
1917        return TokenGroup.get_tokens(self._tu, self.extent)
1918
1919    def get_field_offsetof(self):
1920        """Returns the offsetof the FIELD_DECL pointed by this Cursor."""
1921        return conf.lib.clang_Cursor_getOffsetOfField(self)
1922
1923    def is_anonymous(self):
1924        """
1925        Check if the record is anonymous.
1926        """
1927        if self.kind == CursorKind.FIELD_DECL:
1928            return self.type.get_declaration().is_anonymous()
1929        return conf.lib.clang_Cursor_isAnonymous(self)
1930
1931    def is_bitfield(self):
1932        """
1933        Check if the field is a bitfield.
1934        """
1935        return conf.lib.clang_Cursor_isBitField(self)
1936
1937    def get_bitfield_width(self):
1938        """
1939        Retrieve the width of a bitfield.
1940        """
1941        return conf.lib.clang_getFieldDeclBitWidth(self)
1942
1943    @staticmethod
1944    def from_result(res, fn, args):
1945        assert isinstance(res, Cursor)
1946        # FIXME: There should just be an isNull method.
1947        if res == conf.lib.clang_getNullCursor():
1948            return None
1949
1950        # Store a reference to the TU in the Python object so it won't get GC'd
1951        # before the Cursor.
1952        tu = None
1953        for arg in args:
1954            if isinstance(arg, TranslationUnit):
1955                tu = arg
1956                break
1957
1958            if hasattr(arg, 'translation_unit'):
1959                tu = arg.translation_unit
1960                break
1961
1962        assert tu is not None
1963
1964        res._tu = tu
1965        return res
1966
1967    @staticmethod
1968    def from_cursor_result(res, fn, args):
1969        assert isinstance(res, Cursor)
1970        if res == conf.lib.clang_getNullCursor():
1971            return None
1972
1973        res._tu = args[0]._tu
1974        return res
1975
1976class StorageClass(object):
1977    """
1978    Describes the storage class of a declaration
1979    """
1980
1981    # The unique kind objects, index by id.
1982    _kinds = []
1983    _name_map = None
1984
1985    def __init__(self, value):
1986        if value >= len(StorageClass._kinds):
1987            StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1)
1988        if StorageClass._kinds[value] is not None:
1989            raise ValueError('StorageClass already loaded')
1990        self.value = value
1991        StorageClass._kinds[value] = self
1992        StorageClass._name_map = None
1993
1994    def from_param(self):
1995        return self.value
1996
1997    @property
1998    def name(self):
1999        """Get the enumeration name of this storage class."""
2000        if self._name_map is None:
2001            self._name_map = {}
2002            for key,value in StorageClass.__dict__.items():
2003                if isinstance(value,StorageClass):
2004                    self._name_map[value] = key
2005        return self._name_map[self]
2006
2007    @staticmethod
2008    def from_id(id):
2009        if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
2010            raise ValueError('Unknown storage class %d' % id)
2011        return StorageClass._kinds[id]
2012
2013    def __repr__(self):
2014        return 'StorageClass.%s' % (self.name,)
2015
2016StorageClass.INVALID = StorageClass(0)
2017StorageClass.NONE = StorageClass(1)
2018StorageClass.EXTERN = StorageClass(2)
2019StorageClass.STATIC = StorageClass(3)
2020StorageClass.PRIVATEEXTERN = StorageClass(4)
2021StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5)
2022StorageClass.AUTO = StorageClass(6)
2023StorageClass.REGISTER = StorageClass(7)
2024
2025### Availability Kinds ###
2026
2027class AvailabilityKind(BaseEnumeration):
2028    """
2029    Describes the availability of an entity.
2030    """
2031
2032    # The unique kind objects, indexed by id.
2033    _kinds = []
2034    _name_map = None
2035
2036    def __repr__(self):
2037        return 'AvailabilityKind.%s' % (self.name,)
2038
2039AvailabilityKind.AVAILABLE = AvailabilityKind(0)
2040AvailabilityKind.DEPRECATED = AvailabilityKind(1)
2041AvailabilityKind.NOT_AVAILABLE = AvailabilityKind(2)
2042AvailabilityKind.NOT_ACCESSIBLE = AvailabilityKind(3)
2043
2044### C++ access specifiers ###
2045
2046class AccessSpecifier(BaseEnumeration):
2047    """
2048    Describes the access of a C++ class member
2049    """
2050
2051    # The unique kind objects, index by id.
2052    _kinds = []
2053    _name_map = None
2054
2055    def from_param(self):
2056        return self.value
2057
2058    def __repr__(self):
2059        return 'AccessSpecifier.%s' % (self.name,)
2060
2061AccessSpecifier.INVALID = AccessSpecifier(0)
2062AccessSpecifier.PUBLIC = AccessSpecifier(1)
2063AccessSpecifier.PROTECTED = AccessSpecifier(2)
2064AccessSpecifier.PRIVATE = AccessSpecifier(3)
2065AccessSpecifier.NONE = AccessSpecifier(4)
2066
2067### Type Kinds ###
2068
2069class TypeKind(BaseEnumeration):
2070    """
2071    Describes the kind of type.
2072    """
2073
2074    # The unique kind objects, indexed by id.
2075    _kinds = []
2076    _name_map = None
2077
2078    @property
2079    def spelling(self):
2080        """Retrieve the spelling of this TypeKind."""
2081        return conf.lib.clang_getTypeKindSpelling(self.value)
2082
2083    def __repr__(self):
2084        return 'TypeKind.%s' % (self.name,)
2085
2086TypeKind.INVALID = TypeKind(0)
2087TypeKind.UNEXPOSED = TypeKind(1)
2088TypeKind.VOID = TypeKind(2)
2089TypeKind.BOOL = TypeKind(3)
2090TypeKind.CHAR_U = TypeKind(4)
2091TypeKind.UCHAR = TypeKind(5)
2092TypeKind.CHAR16 = TypeKind(6)
2093TypeKind.CHAR32 = TypeKind(7)
2094TypeKind.USHORT = TypeKind(8)
2095TypeKind.UINT = TypeKind(9)
2096TypeKind.ULONG = TypeKind(10)
2097TypeKind.ULONGLONG = TypeKind(11)
2098TypeKind.UINT128 = TypeKind(12)
2099TypeKind.CHAR_S = TypeKind(13)
2100TypeKind.SCHAR = TypeKind(14)
2101TypeKind.WCHAR = TypeKind(15)
2102TypeKind.SHORT = TypeKind(16)
2103TypeKind.INT = TypeKind(17)
2104TypeKind.LONG = TypeKind(18)
2105TypeKind.LONGLONG = TypeKind(19)
2106TypeKind.INT128 = TypeKind(20)
2107TypeKind.FLOAT = TypeKind(21)
2108TypeKind.DOUBLE = TypeKind(22)
2109TypeKind.LONGDOUBLE = TypeKind(23)
2110TypeKind.NULLPTR = TypeKind(24)
2111TypeKind.OVERLOAD = TypeKind(25)
2112TypeKind.DEPENDENT = TypeKind(26)
2113TypeKind.OBJCID = TypeKind(27)
2114TypeKind.OBJCCLASS = TypeKind(28)
2115TypeKind.OBJCSEL = TypeKind(29)
2116TypeKind.FLOAT128 = TypeKind(30)
2117TypeKind.HALF = TypeKind(31)
2118TypeKind.IBM128 = TypeKind(40)
2119TypeKind.COMPLEX = TypeKind(100)
2120TypeKind.POINTER = TypeKind(101)
2121TypeKind.BLOCKPOINTER = TypeKind(102)
2122TypeKind.LVALUEREFERENCE = TypeKind(103)
2123TypeKind.RVALUEREFERENCE = TypeKind(104)
2124TypeKind.RECORD = TypeKind(105)
2125TypeKind.ENUM = TypeKind(106)
2126TypeKind.TYPEDEF = TypeKind(107)
2127TypeKind.OBJCINTERFACE = TypeKind(108)
2128TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
2129TypeKind.FUNCTIONNOPROTO = TypeKind(110)
2130TypeKind.FUNCTIONPROTO = TypeKind(111)
2131TypeKind.CONSTANTARRAY = TypeKind(112)
2132TypeKind.VECTOR = TypeKind(113)
2133TypeKind.INCOMPLETEARRAY = TypeKind(114)
2134TypeKind.VARIABLEARRAY = TypeKind(115)
2135TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
2136TypeKind.MEMBERPOINTER = TypeKind(117)
2137TypeKind.AUTO = TypeKind(118)
2138TypeKind.ELABORATED = TypeKind(119)
2139TypeKind.PIPE = TypeKind(120)
2140TypeKind.OCLIMAGE1DRO = TypeKind(121)
2141TypeKind.OCLIMAGE1DARRAYRO = TypeKind(122)
2142TypeKind.OCLIMAGE1DBUFFERRO = TypeKind(123)
2143TypeKind.OCLIMAGE2DRO = TypeKind(124)
2144TypeKind.OCLIMAGE2DARRAYRO = TypeKind(125)
2145TypeKind.OCLIMAGE2DDEPTHRO = TypeKind(126)
2146TypeKind.OCLIMAGE2DARRAYDEPTHRO = TypeKind(127)
2147TypeKind.OCLIMAGE2DMSAARO = TypeKind(128)
2148TypeKind.OCLIMAGE2DARRAYMSAARO = TypeKind(129)
2149TypeKind.OCLIMAGE2DMSAADEPTHRO = TypeKind(130)
2150TypeKind.OCLIMAGE2DARRAYMSAADEPTHRO = TypeKind(131)
2151TypeKind.OCLIMAGE3DRO = TypeKind(132)
2152TypeKind.OCLIMAGE1DWO = TypeKind(133)
2153TypeKind.OCLIMAGE1DARRAYWO = TypeKind(134)
2154TypeKind.OCLIMAGE1DBUFFERWO = TypeKind(135)
2155TypeKind.OCLIMAGE2DWO = TypeKind(136)
2156TypeKind.OCLIMAGE2DARRAYWO = TypeKind(137)
2157TypeKind.OCLIMAGE2DDEPTHWO = TypeKind(138)
2158TypeKind.OCLIMAGE2DARRAYDEPTHWO = TypeKind(139)
2159TypeKind.OCLIMAGE2DMSAAWO = TypeKind(140)
2160TypeKind.OCLIMAGE2DARRAYMSAAWO = TypeKind(141)
2161TypeKind.OCLIMAGE2DMSAADEPTHWO = TypeKind(142)
2162TypeKind.OCLIMAGE2DARRAYMSAADEPTHWO = TypeKind(143)
2163TypeKind.OCLIMAGE3DWO = TypeKind(144)
2164TypeKind.OCLIMAGE1DRW = TypeKind(145)
2165TypeKind.OCLIMAGE1DARRAYRW = TypeKind(146)
2166TypeKind.OCLIMAGE1DBUFFERRW = TypeKind(147)
2167TypeKind.OCLIMAGE2DRW = TypeKind(148)
2168TypeKind.OCLIMAGE2DARRAYRW = TypeKind(149)
2169TypeKind.OCLIMAGE2DDEPTHRW = TypeKind(150)
2170TypeKind.OCLIMAGE2DARRAYDEPTHRW = TypeKind(151)
2171TypeKind.OCLIMAGE2DMSAARW = TypeKind(152)
2172TypeKind.OCLIMAGE2DARRAYMSAARW = TypeKind(153)
2173TypeKind.OCLIMAGE2DMSAADEPTHRW = TypeKind(154)
2174TypeKind.OCLIMAGE2DARRAYMSAADEPTHRW = TypeKind(155)
2175TypeKind.OCLIMAGE3DRW = TypeKind(156)
2176TypeKind.OCLSAMPLER = TypeKind(157)
2177TypeKind.OCLEVENT = TypeKind(158)
2178TypeKind.OCLQUEUE = TypeKind(159)
2179TypeKind.OCLRESERVEID = TypeKind(160)
2180
2181TypeKind.EXTVECTOR = TypeKind(176)
2182TypeKind.ATOMIC = TypeKind(177)
2183
2184class RefQualifierKind(BaseEnumeration):
2185    """Describes a specific ref-qualifier of a type."""
2186
2187    # The unique kind objects, indexed by id.
2188    _kinds = []
2189    _name_map = None
2190
2191    def from_param(self):
2192        return self.value
2193
2194    def __repr__(self):
2195        return 'RefQualifierKind.%s' % (self.name,)
2196
2197RefQualifierKind.NONE = RefQualifierKind(0)
2198RefQualifierKind.LVALUE = RefQualifierKind(1)
2199RefQualifierKind.RVALUE = RefQualifierKind(2)
2200
2201class LinkageKind(BaseEnumeration):
2202    """Describes the kind of linkage of a cursor."""
2203
2204    # The unique kind objects, indexed by id.
2205    _kinds = []
2206    _name_map = None
2207
2208    def from_param(self):
2209        return self.value
2210
2211    def __repr__(self):
2212        return 'LinkageKind.%s' % (self.name,)
2213
2214LinkageKind.INVALID = LinkageKind(0)
2215LinkageKind.NO_LINKAGE = LinkageKind(1)
2216LinkageKind.INTERNAL = LinkageKind(2)
2217LinkageKind.UNIQUE_EXTERNAL = LinkageKind(3)
2218LinkageKind.EXTERNAL = LinkageKind(4)
2219
2220class TLSKind(BaseEnumeration):
2221    """Describes the kind of thread-local storage (TLS) of a cursor."""
2222
2223    # The unique kind objects, indexed by id.
2224    _kinds = []
2225    _name_map = None
2226
2227    def from_param(self):
2228        return self.value
2229
2230    def __repr__(self):
2231        return 'TLSKind.%s' % (self.name,)
2232
2233TLSKind.NONE = TLSKind(0)
2234TLSKind.DYNAMIC = TLSKind(1)
2235TLSKind.STATIC = TLSKind(2)
2236
2237class Type(Structure):
2238    """
2239    The type of an element in the abstract syntax tree.
2240    """
2241    _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
2242
2243    @property
2244    def kind(self):
2245        """Return the kind of this type."""
2246        return TypeKind.from_id(self._kind_id)
2247
2248    def argument_types(self):
2249        """Retrieve a container for the non-variadic arguments for this type.
2250
2251        The returned object is iterable and indexable. Each item in the
2252        container is a Type instance.
2253        """
2254        class ArgumentsIterator(collections_abc.Sequence):
2255            def __init__(self, parent):
2256                self.parent = parent
2257                self.length = None
2258
2259            def __len__(self):
2260                if self.length is None:
2261                    self.length = conf.lib.clang_getNumArgTypes(self.parent)
2262
2263                return self.length
2264
2265            def __getitem__(self, key):
2266                # FIXME Support slice objects.
2267                if not isinstance(key, int):
2268                    raise TypeError("Must supply a non-negative int.")
2269
2270                if key < 0:
2271                    raise IndexError("Only non-negative indexes are accepted.")
2272
2273                if key >= len(self):
2274                    raise IndexError("Index greater than container length: "
2275                                     "%d > %d" % ( key, len(self) ))
2276
2277                result = conf.lib.clang_getArgType(self.parent, key)
2278                if result.kind == TypeKind.INVALID:
2279                    raise IndexError("Argument could not be retrieved.")
2280
2281                return result
2282
2283        assert self.kind == TypeKind.FUNCTIONPROTO
2284        return ArgumentsIterator(self)
2285
2286    @property
2287    def element_type(self):
2288        """Retrieve the Type of elements within this Type.
2289
2290        If accessed on a type that is not an array, complex, or vector type, an
2291        exception will be raised.
2292        """
2293        result = conf.lib.clang_getElementType(self)
2294        if result.kind == TypeKind.INVALID:
2295            raise Exception('Element type not available on this type.')
2296
2297        return result
2298
2299    @property
2300    def element_count(self):
2301        """Retrieve the number of elements in this type.
2302
2303        Returns an int.
2304
2305        If the Type is not an array or vector, this raises.
2306        """
2307        result = conf.lib.clang_getNumElements(self)
2308        if result < 0:
2309            raise Exception('Type does not have elements.')
2310
2311        return result
2312
2313    @property
2314    def translation_unit(self):
2315        """The TranslationUnit to which this Type is associated."""
2316        # If this triggers an AttributeError, the instance was not properly
2317        # instantiated.
2318        return self._tu
2319
2320    @staticmethod
2321    def from_result(res, fn, args):
2322        assert isinstance(res, Type)
2323
2324        tu = None
2325        for arg in args:
2326            if hasattr(arg, 'translation_unit'):
2327                tu = arg.translation_unit
2328                break
2329
2330        assert tu is not None
2331        res._tu = tu
2332
2333        return res
2334
2335    def get_num_template_arguments(self):
2336        return conf.lib.clang_Type_getNumTemplateArguments(self)
2337
2338    def get_template_argument_type(self, num):
2339        return conf.lib.clang_Type_getTemplateArgumentAsType(self, num)
2340
2341    def get_canonical(self):
2342        """
2343        Return the canonical type for a Type.
2344
2345        Clang's type system explicitly models typedefs and all the
2346        ways a specific type can be represented.  The canonical type
2347        is the underlying type with all the "sugar" removed.  For
2348        example, if 'T' is a typedef for 'int', the canonical type for
2349        'T' would be 'int'.
2350        """
2351        return conf.lib.clang_getCanonicalType(self)
2352
2353    def is_const_qualified(self):
2354        """Determine whether a Type has the "const" qualifier set.
2355
2356        This does not look through typedefs that may have added "const"
2357        at a different level.
2358        """
2359        return conf.lib.clang_isConstQualifiedType(self)
2360
2361    def is_volatile_qualified(self):
2362        """Determine whether a Type has the "volatile" qualifier set.
2363
2364        This does not look through typedefs that may have added "volatile"
2365        at a different level.
2366        """
2367        return conf.lib.clang_isVolatileQualifiedType(self)
2368
2369    def is_restrict_qualified(self):
2370        """Determine whether a Type has the "restrict" qualifier set.
2371
2372        This does not look through typedefs that may have added "restrict" at
2373        a different level.
2374        """
2375        return conf.lib.clang_isRestrictQualifiedType(self)
2376
2377    def is_function_variadic(self):
2378        """Determine whether this function Type is a variadic function type."""
2379        assert self.kind == TypeKind.FUNCTIONPROTO
2380
2381        return conf.lib.clang_isFunctionTypeVariadic(self)
2382
2383    def get_address_space(self):
2384        return conf.lib.clang_getAddressSpace(self)
2385
2386    def get_typedef_name(self):
2387        return conf.lib.clang_getTypedefName(self)
2388
2389    def is_pod(self):
2390        """Determine whether this Type represents plain old data (POD)."""
2391        return conf.lib.clang_isPODType(self)
2392
2393    def get_pointee(self):
2394        """
2395        For pointer types, returns the type of the pointee.
2396        """
2397        return conf.lib.clang_getPointeeType(self)
2398
2399    def get_declaration(self):
2400        """
2401        Return the cursor for the declaration of the given type.
2402        """
2403        return conf.lib.clang_getTypeDeclaration(self)
2404
2405    def get_result(self):
2406        """
2407        Retrieve the result type associated with a function type.
2408        """
2409        return conf.lib.clang_getResultType(self)
2410
2411    def get_array_element_type(self):
2412        """
2413        Retrieve the type of the elements of the array type.
2414        """
2415        return conf.lib.clang_getArrayElementType(self)
2416
2417    def get_array_size(self):
2418        """
2419        Retrieve the size of the constant array.
2420        """
2421        return conf.lib.clang_getArraySize(self)
2422
2423    def get_class_type(self):
2424        """
2425        Retrieve the class type of the member pointer type.
2426        """
2427        return conf.lib.clang_Type_getClassType(self)
2428
2429    def get_named_type(self):
2430        """
2431        Retrieve the type named by the qualified-id.
2432        """
2433        return conf.lib.clang_Type_getNamedType(self)
2434
2435    def get_align(self):
2436        """
2437        Retrieve the alignment of the record.
2438        """
2439        return conf.lib.clang_Type_getAlignOf(self)
2440
2441    def get_size(self):
2442        """
2443        Retrieve the size of the record.
2444        """
2445        return conf.lib.clang_Type_getSizeOf(self)
2446
2447    def get_offset(self, fieldname):
2448        """
2449        Retrieve the offset of a field in the record.
2450        """
2451        return conf.lib.clang_Type_getOffsetOf(self, fieldname)
2452
2453    def get_ref_qualifier(self):
2454        """
2455        Retrieve the ref-qualifier of the type.
2456        """
2457        return RefQualifierKind.from_id(
2458                conf.lib.clang_Type_getCXXRefQualifier(self))
2459
2460    def get_fields(self):
2461        """Return an iterator for accessing the fields of this type."""
2462
2463        def visitor(field, children):
2464            assert field != conf.lib.clang_getNullCursor()
2465
2466            # Create reference to TU so it isn't GC'd before Cursor.
2467            field._tu = self._tu
2468            fields.append(field)
2469            return 1 # continue
2470        fields = []
2471        conf.lib.clang_Type_visitFields(self,
2472                            callbacks['fields_visit'](visitor), fields)
2473        return iter(fields)
2474
2475    def get_exception_specification_kind(self):
2476        """
2477        Return the kind of the exception specification; a value from
2478        the ExceptionSpecificationKind enumeration.
2479        """
2480        return ExceptionSpecificationKind.from_id(
2481                conf.lib.clang.getExceptionSpecificationType(self))
2482
2483    @property
2484    def spelling(self):
2485        """Retrieve the spelling of this Type."""
2486        return conf.lib.clang_getTypeSpelling(self)
2487
2488    def __eq__(self, other):
2489        if type(other) != type(self):
2490            return False
2491
2492        return conf.lib.clang_equalTypes(self, other)
2493
2494    def __ne__(self, other):
2495        return not self.__eq__(other)
2496
2497## CIndex Objects ##
2498
2499# CIndex objects (derived from ClangObject) are essentially lightweight
2500# wrappers attached to some underlying object, which is exposed via CIndex as
2501# a void*.
2502
2503class ClangObject(object):
2504    """
2505    A helper for Clang objects. This class helps act as an intermediary for
2506    the ctypes library and the Clang CIndex library.
2507    """
2508    def __init__(self, obj):
2509        assert isinstance(obj, c_object_p) and obj
2510        self.obj = self._as_parameter_ = obj
2511
2512    def from_param(self):
2513        return self._as_parameter_
2514
2515
2516class _CXUnsavedFile(Structure):
2517    """Helper for passing unsaved file arguments."""
2518    _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
2519
2520# Functions calls through the python interface are rather slow. Fortunately,
2521# for most symboles, we do not need to perform a function call. Their spelling
2522# never changes and is consequently provided by this spelling cache.
2523SpellingCache = {
2524            # 0: CompletionChunk.Kind("Optional"),
2525            # 1: CompletionChunk.Kind("TypedText"),
2526            # 2: CompletionChunk.Kind("Text"),
2527            # 3: CompletionChunk.Kind("Placeholder"),
2528            # 4: CompletionChunk.Kind("Informative"),
2529            # 5 : CompletionChunk.Kind("CurrentParameter"),
2530            6: '(',   # CompletionChunk.Kind("LeftParen"),
2531            7: ')',   # CompletionChunk.Kind("RightParen"),
2532            8: '[',   # CompletionChunk.Kind("LeftBracket"),
2533            9: ']',   # CompletionChunk.Kind("RightBracket"),
2534            10: '{',  # CompletionChunk.Kind("LeftBrace"),
2535            11: '}',  # CompletionChunk.Kind("RightBrace"),
2536            12: '<',  # CompletionChunk.Kind("LeftAngle"),
2537            13: '>',  # CompletionChunk.Kind("RightAngle"),
2538            14: ', ', # CompletionChunk.Kind("Comma"),
2539            # 15: CompletionChunk.Kind("ResultType"),
2540            16: ':',  # CompletionChunk.Kind("Colon"),
2541            17: ';',  # CompletionChunk.Kind("SemiColon"),
2542            18: '=',  # CompletionChunk.Kind("Equal"),
2543            19: ' ',  # CompletionChunk.Kind("HorizontalSpace"),
2544            # 20: CompletionChunk.Kind("VerticalSpace")
2545}
2546
2547class CompletionChunk(object):
2548    class Kind(object):
2549        def __init__(self, name):
2550            self.name = name
2551
2552        def __str__(self):
2553            return self.name
2554
2555        def __repr__(self):
2556            return "<ChunkKind: %s>" % self
2557
2558    def __init__(self, completionString, key):
2559        self.cs = completionString
2560        self.key = key
2561        self.__kindNumberCache = -1
2562
2563    def __repr__(self):
2564        return "{'" + self.spelling + "', " + str(self.kind) + "}"
2565
2566    @CachedProperty
2567    def spelling(self):
2568        if self.__kindNumber in SpellingCache:
2569                return SpellingCache[self.__kindNumber]
2570        return conf.lib.clang_getCompletionChunkText(self.cs, self.key)
2571
2572    # We do not use @CachedProperty here, as the manual implementation is
2573    # apparently still significantly faster. Please profile carefully if you
2574    # would like to add CachedProperty back.
2575    @property
2576    def __kindNumber(self):
2577        if self.__kindNumberCache == -1:
2578            self.__kindNumberCache = \
2579                conf.lib.clang_getCompletionChunkKind(self.cs, self.key)
2580        return self.__kindNumberCache
2581
2582    @CachedProperty
2583    def kind(self):
2584        return completionChunkKindMap[self.__kindNumber]
2585
2586    @CachedProperty
2587    def string(self):
2588        res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
2589                                                                self.key)
2590
2591        if (res):
2592          return CompletionString(res)
2593        else:
2594          None
2595
2596    def isKindOptional(self):
2597      return self.__kindNumber == 0
2598
2599    def isKindTypedText(self):
2600      return self.__kindNumber == 1
2601
2602    def isKindPlaceHolder(self):
2603      return self.__kindNumber == 3
2604
2605    def isKindInformative(self):
2606      return self.__kindNumber == 4
2607
2608    def isKindResultType(self):
2609      return self.__kindNumber == 15
2610
2611completionChunkKindMap = {
2612            0: CompletionChunk.Kind("Optional"),
2613            1: CompletionChunk.Kind("TypedText"),
2614            2: CompletionChunk.Kind("Text"),
2615            3: CompletionChunk.Kind("Placeholder"),
2616            4: CompletionChunk.Kind("Informative"),
2617            5: CompletionChunk.Kind("CurrentParameter"),
2618            6: CompletionChunk.Kind("LeftParen"),
2619            7: CompletionChunk.Kind("RightParen"),
2620            8: CompletionChunk.Kind("LeftBracket"),
2621            9: CompletionChunk.Kind("RightBracket"),
2622            10: CompletionChunk.Kind("LeftBrace"),
2623            11: CompletionChunk.Kind("RightBrace"),
2624            12: CompletionChunk.Kind("LeftAngle"),
2625            13: CompletionChunk.Kind("RightAngle"),
2626            14: CompletionChunk.Kind("Comma"),
2627            15: CompletionChunk.Kind("ResultType"),
2628            16: CompletionChunk.Kind("Colon"),
2629            17: CompletionChunk.Kind("SemiColon"),
2630            18: CompletionChunk.Kind("Equal"),
2631            19: CompletionChunk.Kind("HorizontalSpace"),
2632            20: CompletionChunk.Kind("VerticalSpace")}
2633
2634class CompletionString(ClangObject):
2635    class Availability(object):
2636        def __init__(self, name):
2637            self.name = name
2638
2639        def __str__(self):
2640            return self.name
2641
2642        def __repr__(self):
2643            return "<Availability: %s>" % self
2644
2645    def __len__(self):
2646        return self.num_chunks
2647
2648    @CachedProperty
2649    def num_chunks(self):
2650        return conf.lib.clang_getNumCompletionChunks(self.obj)
2651
2652    def __getitem__(self, key):
2653        if self.num_chunks <= key:
2654            raise IndexError
2655        return CompletionChunk(self.obj, key)
2656
2657    @property
2658    def priority(self):
2659        return conf.lib.clang_getCompletionPriority(self.obj)
2660
2661    @property
2662    def availability(self):
2663        res = conf.lib.clang_getCompletionAvailability(self.obj)
2664        return availabilityKinds[res]
2665
2666    @property
2667    def briefComment(self):
2668        if conf.function_exists("clang_getCompletionBriefComment"):
2669            return conf.lib.clang_getCompletionBriefComment(self.obj)
2670        return _CXString()
2671
2672    def __repr__(self):
2673        return " | ".join([str(a) for a in self]) \
2674               + " || Priority: " + str(self.priority) \
2675               + " || Availability: " + str(self.availability) \
2676               + " || Brief comment: " + str(self.briefComment)
2677
2678availabilityKinds = {
2679            0: CompletionChunk.Kind("Available"),
2680            1: CompletionChunk.Kind("Deprecated"),
2681            2: CompletionChunk.Kind("NotAvailable"),
2682            3: CompletionChunk.Kind("NotAccessible")}
2683
2684class CodeCompletionResult(Structure):
2685    _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
2686
2687    def __repr__(self):
2688        return str(CompletionString(self.completionString))
2689
2690    @property
2691    def kind(self):
2692        return CursorKind.from_id(self.cursorKind)
2693
2694    @property
2695    def string(self):
2696        return CompletionString(self.completionString)
2697
2698class CCRStructure(Structure):
2699    _fields_ = [('results', POINTER(CodeCompletionResult)),
2700                ('numResults', c_int)]
2701
2702    def __len__(self):
2703        return self.numResults
2704
2705    def __getitem__(self, key):
2706        if len(self) <= key:
2707            raise IndexError
2708
2709        return self.results[key]
2710
2711class CodeCompletionResults(ClangObject):
2712    def __init__(self, ptr):
2713        assert isinstance(ptr, POINTER(CCRStructure)) and ptr
2714        self.ptr = self._as_parameter_ = ptr
2715
2716    def from_param(self):
2717        return self._as_parameter_
2718
2719    def __del__(self):
2720        conf.lib.clang_disposeCodeCompleteResults(self)
2721
2722    @property
2723    def results(self):
2724        return self.ptr.contents
2725
2726    @property
2727    def diagnostics(self):
2728        class DiagnosticsItr(object):
2729            def __init__(self, ccr):
2730                self.ccr= ccr
2731
2732            def __len__(self):
2733                return int(\
2734                  conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
2735
2736            def __getitem__(self, key):
2737                return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
2738
2739        return DiagnosticsItr(self)
2740
2741
2742class Index(ClangObject):
2743    """
2744    The Index type provides the primary interface to the Clang CIndex library,
2745    primarily by providing an interface for reading and parsing translation
2746    units.
2747    """
2748
2749    @staticmethod
2750    def create(excludeDecls=False):
2751        """
2752        Create a new Index.
2753        Parameters:
2754        excludeDecls -- Exclude local declarations from translation units.
2755        """
2756        return Index(conf.lib.clang_createIndex(excludeDecls, 0))
2757
2758    def __del__(self):
2759        conf.lib.clang_disposeIndex(self)
2760
2761    def read(self, path):
2762        """Load a TranslationUnit from the given AST file."""
2763        return TranslationUnit.from_ast_file(path, self)
2764
2765    def parse(self, path, args=None, unsaved_files=None, options = 0):
2766        """Load the translation unit from the given source code file by running
2767        clang and generating the AST before loading. Additional command line
2768        parameters can be passed to clang via the args parameter.
2769
2770        In-memory contents for files can be provided by passing a list of pairs
2771        to as unsaved_files, the first item should be the filenames to be mapped
2772        and the second should be the contents to be substituted for the
2773        file. The contents may be passed as strings or file objects.
2774
2775        If an error was encountered during parsing, a TranslationUnitLoadError
2776        will be raised.
2777        """
2778        return TranslationUnit.from_source(path, args, unsaved_files, options,
2779                                           self)
2780
2781class TranslationUnit(ClangObject):
2782    """Represents a source code translation unit.
2783
2784    This is one of the main types in the API. Any time you wish to interact
2785    with Clang's representation of a source file, you typically start with a
2786    translation unit.
2787    """
2788
2789    # Default parsing mode.
2790    PARSE_NONE = 0
2791
2792    # Instruct the parser to create a detailed processing record containing
2793    # metadata not normally retained.
2794    PARSE_DETAILED_PROCESSING_RECORD = 1
2795
2796    # Indicates that the translation unit is incomplete. This is typically used
2797    # when parsing headers.
2798    PARSE_INCOMPLETE = 2
2799
2800    # Instruct the parser to create a pre-compiled preamble for the translation
2801    # unit. This caches the preamble (included files at top of source file).
2802    # This is useful if the translation unit will be reparsed and you don't
2803    # want to incur the overhead of reparsing the preamble.
2804    PARSE_PRECOMPILED_PREAMBLE = 4
2805
2806    # Cache code completion information on parse. This adds time to parsing but
2807    # speeds up code completion.
2808    PARSE_CACHE_COMPLETION_RESULTS = 8
2809
2810    # Flags with values 16 and 32 are deprecated and intentionally omitted.
2811
2812    # Do not parse function bodies. This is useful if you only care about
2813    # searching for declarations/definitions.
2814    PARSE_SKIP_FUNCTION_BODIES = 64
2815
2816    # Used to indicate that brief documentation comments should be included
2817    # into the set of code completions returned from this translation unit.
2818    PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
2819
2820    @classmethod
2821    def from_source(cls, filename, args=None, unsaved_files=None, options=0,
2822                    index=None):
2823        """Create a TranslationUnit by parsing source.
2824
2825        This is capable of processing source code both from files on the
2826        filesystem as well as in-memory contents.
2827
2828        Command-line arguments that would be passed to clang are specified as
2829        a list via args. These can be used to specify include paths, warnings,
2830        etc. e.g. ["-Wall", "-I/path/to/include"].
2831
2832        In-memory file content can be provided via unsaved_files. This is an
2833        iterable of 2-tuples. The first element is the filename (str or
2834        PathLike). The second element defines the content. Content can be
2835        provided as str source code or as file objects (anything with a read()
2836        method). If a file object is being used, content will be read until EOF
2837        and the read cursor will not be reset to its original position.
2838
2839        options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
2840        control parsing behavior.
2841
2842        index is an Index instance to utilize. If not provided, a new Index
2843        will be created for this TranslationUnit.
2844
2845        To parse source from the filesystem, the filename of the file to parse
2846        is specified by the filename argument. Or, filename could be None and
2847        the args list would contain the filename(s) to parse.
2848
2849        To parse source from an in-memory buffer, set filename to the virtual
2850        filename you wish to associate with this source (e.g. "test.c"). The
2851        contents of that file are then provided in unsaved_files.
2852
2853        If an error occurs, a TranslationUnitLoadError is raised.
2854
2855        Please note that a TranslationUnit with parser errors may be returned.
2856        It is the caller's responsibility to check tu.diagnostics for errors.
2857
2858        Also note that Clang infers the source language from the extension of
2859        the input filename. If you pass in source code containing a C++ class
2860        declaration with the filename "test.c" parsing will fail.
2861        """
2862        if args is None:
2863            args = []
2864
2865        if unsaved_files is None:
2866            unsaved_files = []
2867
2868        if index is None:
2869            index = Index.create()
2870
2871        args_array = None
2872        if len(args) > 0:
2873            args_array = (c_char_p * len(args))(*[b(x) for x in args])
2874
2875        unsaved_array = None
2876        if len(unsaved_files) > 0:
2877            unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
2878            for i, (name, contents) in enumerate(unsaved_files):
2879                if hasattr(contents, "read"):
2880                    contents = contents.read()
2881                contents = b(contents)
2882                unsaved_array[i].name = b(fspath(name))
2883                unsaved_array[i].contents = contents
2884                unsaved_array[i].length = len(contents)
2885
2886        ptr = conf.lib.clang_parseTranslationUnit(index,
2887                                    fspath(filename) if filename is not None else None,
2888                                    args_array,
2889                                    len(args), unsaved_array,
2890                                    len(unsaved_files), options)
2891
2892        if not ptr:
2893            raise TranslationUnitLoadError("Error parsing translation unit.")
2894
2895        return cls(ptr, index=index)
2896
2897    @classmethod
2898    def from_ast_file(cls, filename, index=None):
2899        """Create a TranslationUnit instance from a saved AST file.
2900
2901        A previously-saved AST file (provided with -emit-ast or
2902        TranslationUnit.save()) is loaded from the filename specified.
2903
2904        If the file cannot be loaded, a TranslationUnitLoadError will be
2905        raised.
2906
2907        index is optional and is the Index instance to use. If not provided,
2908        a default Index will be created.
2909
2910        filename can be str or PathLike.
2911        """
2912        if index is None:
2913            index = Index.create()
2914
2915        ptr = conf.lib.clang_createTranslationUnit(index, fspath(filename))
2916        if not ptr:
2917            raise TranslationUnitLoadError(filename)
2918
2919        return cls(ptr=ptr, index=index)
2920
2921    def __init__(self, ptr, index):
2922        """Create a TranslationUnit instance.
2923
2924        TranslationUnits should be created using one of the from_* @classmethod
2925        functions above. __init__ is only called internally.
2926        """
2927        assert isinstance(index, Index)
2928        self.index = index
2929        ClangObject.__init__(self, ptr)
2930
2931    def __del__(self):
2932        conf.lib.clang_disposeTranslationUnit(self)
2933
2934    @property
2935    def cursor(self):
2936        """Retrieve the cursor that represents the given translation unit."""
2937        return conf.lib.clang_getTranslationUnitCursor(self)
2938
2939    @property
2940    def spelling(self):
2941        """Get the original translation unit source file name."""
2942        return conf.lib.clang_getTranslationUnitSpelling(self)
2943
2944    def get_includes(self):
2945        """
2946        Return an iterable sequence of FileInclusion objects that describe the
2947        sequence of inclusions in a translation unit. The first object in
2948        this sequence is always the input file. Note that this method will not
2949        recursively iterate over header files included through precompiled
2950        headers.
2951        """
2952        def visitor(fobj, lptr, depth, includes):
2953            if depth > 0:
2954                loc = lptr.contents
2955                includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
2956
2957        # Automatically adapt CIndex/ctype pointers to python objects
2958        includes = []
2959        conf.lib.clang_getInclusions(self,
2960                callbacks['translation_unit_includes'](visitor), includes)
2961
2962        return iter(includes)
2963
2964    def get_file(self, filename):
2965        """Obtain a File from this translation unit."""
2966
2967        return File.from_name(self, filename)
2968
2969    def get_location(self, filename, position):
2970        """Obtain a SourceLocation for a file in this translation unit.
2971
2972        The position can be specified by passing:
2973
2974          - Integer file offset. Initial file offset is 0.
2975          - 2-tuple of (line number, column number). Initial file position is
2976            (0, 0)
2977        """
2978        f = self.get_file(filename)
2979
2980        if isinstance(position, int):
2981            return SourceLocation.from_offset(self, f, position)
2982
2983        return SourceLocation.from_position(self, f, position[0], position[1])
2984
2985    def get_extent(self, filename, locations):
2986        """Obtain a SourceRange from this translation unit.
2987
2988        The bounds of the SourceRange must ultimately be defined by a start and
2989        end SourceLocation. For the locations argument, you can pass:
2990
2991          - 2 SourceLocation instances in a 2-tuple or list.
2992          - 2 int file offsets via a 2-tuple or list.
2993          - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
2994
2995        e.g.
2996
2997        get_extent('foo.c', (5, 10))
2998        get_extent('foo.c', ((1, 1), (1, 15)))
2999        """
3000        f = self.get_file(filename)
3001
3002        if len(locations) < 2:
3003            raise Exception('Must pass object with at least 2 elements')
3004
3005        start_location, end_location = locations
3006
3007        if hasattr(start_location, '__len__'):
3008            start_location = SourceLocation.from_position(self, f,
3009                start_location[0], start_location[1])
3010        elif isinstance(start_location, int):
3011            start_location = SourceLocation.from_offset(self, f,
3012                start_location)
3013
3014        if hasattr(end_location, '__len__'):
3015            end_location = SourceLocation.from_position(self, f,
3016                end_location[0], end_location[1])
3017        elif isinstance(end_location, int):
3018            end_location = SourceLocation.from_offset(self, f, end_location)
3019
3020        assert isinstance(start_location, SourceLocation)
3021        assert isinstance(end_location, SourceLocation)
3022
3023        return SourceRange.from_locations(start_location, end_location)
3024
3025    @property
3026    def diagnostics(self):
3027        """
3028        Return an iterable (and indexable) object containing the diagnostics.
3029        """
3030        class DiagIterator(object):
3031            def __init__(self, tu):
3032                self.tu = tu
3033
3034            def __len__(self):
3035                return int(conf.lib.clang_getNumDiagnostics(self.tu))
3036
3037            def __getitem__(self, key):
3038                diag = conf.lib.clang_getDiagnostic(self.tu, key)
3039                if not diag:
3040                    raise IndexError
3041                return Diagnostic(diag)
3042
3043        return DiagIterator(self)
3044
3045    def reparse(self, unsaved_files=None, options=0):
3046        """
3047        Reparse an already parsed translation unit.
3048
3049        In-memory contents for files can be provided by passing a list of pairs
3050        as unsaved_files, the first items should be the filenames to be mapped
3051        and the second should be the contents to be substituted for the
3052        file. The contents may be passed as strings or file objects.
3053        """
3054        if unsaved_files is None:
3055            unsaved_files = []
3056
3057        unsaved_files_array = 0
3058        if len(unsaved_files):
3059            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
3060            for i,(name,contents) in enumerate(unsaved_files):
3061                if hasattr(contents, "read"):
3062                    contents = contents.read()
3063                contents = b(contents)
3064                unsaved_files_array[i].name = b(fspath(name))
3065                unsaved_files_array[i].contents = contents
3066                unsaved_files_array[i].length = len(contents)
3067        ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
3068                unsaved_files_array, options)
3069
3070    def save(self, filename):
3071        """Saves the TranslationUnit to a file.
3072
3073        This is equivalent to passing -emit-ast to the clang frontend. The
3074        saved file can be loaded back into a TranslationUnit. Or, if it
3075        corresponds to a header, it can be used as a pre-compiled header file.
3076
3077        If an error occurs while saving, a TranslationUnitSaveError is raised.
3078        If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
3079        the constructed TranslationUnit was not valid at time of save. In this
3080        case, the reason(s) why should be available via
3081        TranslationUnit.diagnostics().
3082
3083        filename -- The path to save the translation unit to (str or PathLike).
3084        """
3085        options = conf.lib.clang_defaultSaveOptions(self)
3086        result = int(conf.lib.clang_saveTranslationUnit(self, fspath(filename),
3087                                                        options))
3088        if result != 0:
3089            raise TranslationUnitSaveError(result,
3090                'Error saving TranslationUnit.')
3091
3092    def codeComplete(self, path, line, column, unsaved_files=None,
3093                     include_macros=False, include_code_patterns=False,
3094                     include_brief_comments=False):
3095        """
3096        Code complete in this translation unit.
3097
3098        In-memory contents for files can be provided by passing a list of pairs
3099        as unsaved_files, the first items should be the filenames to be mapped
3100        and the second should be the contents to be substituted for the
3101        file. The contents may be passed as strings or file objects.
3102        """
3103        options = 0
3104
3105        if include_macros:
3106            options += 1
3107
3108        if include_code_patterns:
3109            options += 2
3110
3111        if include_brief_comments:
3112            options += 4
3113
3114        if unsaved_files is None:
3115            unsaved_files = []
3116
3117        unsaved_files_array = 0
3118        if len(unsaved_files):
3119            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
3120            for i,(name,contents) in enumerate(unsaved_files):
3121                if hasattr(contents, "read"):
3122                    contents = contents.read()
3123                contents = b(contents)
3124                unsaved_files_array[i].name = b(fspath(name))
3125                unsaved_files_array[i].contents = contents
3126                unsaved_files_array[i].length = len(contents)
3127        ptr = conf.lib.clang_codeCompleteAt(self, fspath(path), line, column,
3128                unsaved_files_array, len(unsaved_files), options)
3129        if ptr:
3130            return CodeCompletionResults(ptr)
3131        return None
3132
3133    def get_tokens(self, locations=None, extent=None):
3134        """Obtain tokens in this translation unit.
3135
3136        This is a generator for Token instances. The caller specifies a range
3137        of source code to obtain tokens for. The range can be specified as a
3138        2-tuple of SourceLocation or as a SourceRange. If both are defined,
3139        behavior is undefined.
3140        """
3141        if locations is not None:
3142            extent = SourceRange(start=locations[0], end=locations[1])
3143
3144        return TokenGroup.get_tokens(self, extent)
3145
3146class File(ClangObject):
3147    """
3148    The File class represents a particular source file that is part of a
3149    translation unit.
3150    """
3151
3152    @staticmethod
3153    def from_name(translation_unit, file_name):
3154        """Retrieve a file handle within the given translation unit."""
3155        return File(conf.lib.clang_getFile(translation_unit, fspath(file_name)))
3156
3157    @property
3158    def name(self):
3159        """Return the complete file and path name of the file."""
3160        return conf.lib.clang_getFileName(self)
3161
3162    @property
3163    def time(self):
3164        """Return the last modification time of the file."""
3165        return conf.lib.clang_getFileTime(self)
3166
3167    def __str__(self):
3168        return self.name
3169
3170    def __repr__(self):
3171        return "<File: %s>" % (self.name)
3172
3173    @staticmethod
3174    def from_result(res, fn, args):
3175        assert isinstance(res, c_object_p)
3176        res = File(res)
3177
3178        # Copy a reference to the TranslationUnit to prevent premature GC.
3179        res._tu = args[0]._tu
3180        return res
3181
3182class FileInclusion(object):
3183    """
3184    The FileInclusion class represents the inclusion of one source file by
3185    another via a '#include' directive or as the input file for the translation
3186    unit. This class provides information about the included file, the including
3187    file, the location of the '#include' directive and the depth of the included
3188    file in the stack. Note that the input file has depth 0.
3189    """
3190
3191    def __init__(self, src, tgt, loc, depth):
3192        self.source = src
3193        self.include = tgt
3194        self.location = loc
3195        self.depth = depth
3196
3197    @property
3198    def is_input_file(self):
3199        """True if the included file is the input file."""
3200        return self.depth == 0
3201
3202class CompilationDatabaseError(Exception):
3203    """Represents an error that occurred when working with a CompilationDatabase
3204
3205    Each error is associated to an enumerated value, accessible under
3206    e.cdb_error. Consumers can compare the value with one of the ERROR_
3207    constants in this class.
3208    """
3209
3210    # An unknown error occurred
3211    ERROR_UNKNOWN = 0
3212
3213    # The database could not be loaded
3214    ERROR_CANNOTLOADDATABASE = 1
3215
3216    def __init__(self, enumeration, message):
3217        assert isinstance(enumeration, int)
3218
3219        if enumeration > 1:
3220            raise Exception("Encountered undefined CompilationDatabase error "
3221                            "constant: %d. Please file a bug to have this "
3222                            "value supported." % enumeration)
3223
3224        self.cdb_error = enumeration
3225        Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
3226
3227class CompileCommand(object):
3228    """Represents the compile command used to build a file"""
3229    def __init__(self, cmd, ccmds):
3230        self.cmd = cmd
3231        # Keep a reference to the originating CompileCommands
3232        # to prevent garbage collection
3233        self.ccmds = ccmds
3234
3235    @property
3236    def directory(self):
3237        """Get the working directory for this CompileCommand"""
3238        return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
3239
3240    @property
3241    def filename(self):
3242        """Get the working filename for this CompileCommand"""
3243        return conf.lib.clang_CompileCommand_getFilename(self.cmd)
3244
3245    @property
3246    def arguments(self):
3247        """
3248        Get an iterable object providing each argument in the
3249        command line for the compiler invocation as a _CXString.
3250
3251        Invariant : the first argument is the compiler executable
3252        """
3253        length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
3254        for i in range(length):
3255            yield conf.lib.clang_CompileCommand_getArg(self.cmd, i)
3256
3257class CompileCommands(object):
3258    """
3259    CompileCommands is an iterable object containing all CompileCommand
3260    that can be used for building a specific file.
3261    """
3262    def __init__(self, ccmds):
3263        self.ccmds = ccmds
3264
3265    def __del__(self):
3266        conf.lib.clang_CompileCommands_dispose(self.ccmds)
3267
3268    def __len__(self):
3269        return int(conf.lib.clang_CompileCommands_getSize(self.ccmds))
3270
3271    def __getitem__(self, i):
3272        cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i)
3273        if not cc:
3274            raise IndexError
3275        return CompileCommand(cc, self)
3276
3277    @staticmethod
3278    def from_result(res, fn, args):
3279        if not res:
3280            return None
3281        return CompileCommands(res)
3282
3283class CompilationDatabase(ClangObject):
3284    """
3285    The CompilationDatabase is a wrapper class around
3286    clang::tooling::CompilationDatabase
3287
3288    It enables querying how a specific source file can be built.
3289    """
3290
3291    def __del__(self):
3292        conf.lib.clang_CompilationDatabase_dispose(self)
3293
3294    @staticmethod
3295    def from_result(res, fn, args):
3296        if not res:
3297            raise CompilationDatabaseError(0,
3298                                           "CompilationDatabase loading failed")
3299        return CompilationDatabase(res)
3300
3301    @staticmethod
3302    def fromDirectory(buildDir):
3303        """Builds a CompilationDatabase from the database found in buildDir"""
3304        errorCode = c_uint()
3305        try:
3306            cdb = conf.lib.clang_CompilationDatabase_fromDirectory(fspath(buildDir),
3307                byref(errorCode))
3308        except CompilationDatabaseError as e:
3309            raise CompilationDatabaseError(int(errorCode.value),
3310                                           "CompilationDatabase loading failed")
3311        return cdb
3312
3313    def getCompileCommands(self, filename):
3314        """
3315        Get an iterable object providing all the CompileCommands available to
3316        build filename. Returns None if filename is not found in the database.
3317        """
3318        return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
3319                                                                     fspath(filename))
3320
3321    def getAllCompileCommands(self):
3322        """
3323        Get an iterable object providing all the CompileCommands available from
3324        the database.
3325        """
3326        return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self)
3327
3328
3329class Token(Structure):
3330    """Represents a single token from the preprocessor.
3331
3332    Tokens are effectively segments of source code. Source code is first parsed
3333    into tokens before being converted into the AST and Cursors.
3334
3335    Tokens are obtained from parsed TranslationUnit instances. You currently
3336    can't create tokens manually.
3337    """
3338    _fields_ = [
3339        ('int_data', c_uint * 4),
3340        ('ptr_data', c_void_p)
3341    ]
3342
3343    @property
3344    def spelling(self):
3345        """The spelling of this token.
3346
3347        This is the textual representation of the token in source.
3348        """
3349        return conf.lib.clang_getTokenSpelling(self._tu, self)
3350
3351    @property
3352    def kind(self):
3353        """Obtain the TokenKind of the current token."""
3354        return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
3355
3356    @property
3357    def location(self):
3358        """The SourceLocation this Token occurs at."""
3359        return conf.lib.clang_getTokenLocation(self._tu, self)
3360
3361    @property
3362    def extent(self):
3363        """The SourceRange this Token occupies."""
3364        return conf.lib.clang_getTokenExtent(self._tu, self)
3365
3366    @property
3367    def cursor(self):
3368        """The Cursor this Token corresponds to."""
3369        cursor = Cursor()
3370        cursor._tu = self._tu
3371
3372        conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
3373
3374        return cursor
3375
3376# Now comes the plumbing to hook up the C library.
3377
3378# Register callback types in common container.
3379callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
3380        POINTER(SourceLocation), c_uint, py_object)
3381callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
3382callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object)
3383
3384# Functions strictly alphabetical order.
3385functionList = [
3386  ("clang_annotateTokens",
3387   [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
3388
3389  ("clang_CompilationDatabase_dispose",
3390   [c_object_p]),
3391
3392  ("clang_CompilationDatabase_fromDirectory",
3393   [c_interop_string, POINTER(c_uint)],
3394   c_object_p,
3395   CompilationDatabase.from_result),
3396
3397  ("clang_CompilationDatabase_getAllCompileCommands",
3398   [c_object_p],
3399   c_object_p,
3400   CompileCommands.from_result),
3401
3402  ("clang_CompilationDatabase_getCompileCommands",
3403   [c_object_p, c_interop_string],
3404   c_object_p,
3405   CompileCommands.from_result),
3406
3407  ("clang_CompileCommands_dispose",
3408   [c_object_p]),
3409
3410  ("clang_CompileCommands_getCommand",
3411   [c_object_p, c_uint],
3412   c_object_p),
3413
3414  ("clang_CompileCommands_getSize",
3415   [c_object_p],
3416   c_uint),
3417
3418  ("clang_CompileCommand_getArg",
3419   [c_object_p, c_uint],
3420   _CXString,
3421   _CXString.from_result),
3422
3423  ("clang_CompileCommand_getDirectory",
3424   [c_object_p],
3425   _CXString,
3426   _CXString.from_result),
3427
3428  ("clang_CompileCommand_getFilename",
3429   [c_object_p],
3430   _CXString,
3431   _CXString.from_result),
3432
3433  ("clang_CompileCommand_getNumArgs",
3434   [c_object_p],
3435   c_uint),
3436
3437  ("clang_codeCompleteAt",
3438   [TranslationUnit, c_interop_string, c_int, c_int, c_void_p, c_int, c_int],
3439   POINTER(CCRStructure)),
3440
3441  ("clang_codeCompleteGetDiagnostic",
3442   [CodeCompletionResults, c_int],
3443   Diagnostic),
3444
3445  ("clang_codeCompleteGetNumDiagnostics",
3446   [CodeCompletionResults],
3447   c_int),
3448
3449  ("clang_createIndex",
3450   [c_int, c_int],
3451   c_object_p),
3452
3453  ("clang_createTranslationUnit",
3454   [Index, c_interop_string],
3455   c_object_p),
3456
3457  ("clang_CXXConstructor_isConvertingConstructor",
3458   [Cursor],
3459   bool),
3460
3461  ("clang_CXXConstructor_isCopyConstructor",
3462   [Cursor],
3463   bool),
3464
3465  ("clang_CXXConstructor_isDefaultConstructor",
3466   [Cursor],
3467   bool),
3468
3469  ("clang_CXXConstructor_isMoveConstructor",
3470   [Cursor],
3471   bool),
3472
3473  ("clang_CXXField_isMutable",
3474   [Cursor],
3475   bool),
3476
3477  ("clang_CXXMethod_isConst",
3478   [Cursor],
3479   bool),
3480
3481  ("clang_CXXMethod_isDefaulted",
3482   [Cursor],
3483   bool),
3484
3485  ("clang_CXXMethod_isDeleted",
3486   [Cursor],
3487   bool),
3488
3489  ("clang_CXXMethod_isCopyAssignmentOperator",
3490   [Cursor],
3491   bool),
3492
3493  ("clang_CXXMethod_isMoveAssignmentOperator",
3494   [Cursor],
3495   bool),
3496
3497  ("clang_CXXMethod_isPureVirtual",
3498   [Cursor],
3499   bool),
3500
3501  ("clang_CXXMethod_isStatic",
3502   [Cursor],
3503   bool),
3504
3505  ("clang_CXXMethod_isVirtual",
3506   [Cursor],
3507   bool),
3508
3509  ("clang_CXXRecord_isAbstract",
3510   [Cursor],
3511   bool),
3512
3513  ("clang_EnumDecl_isScoped",
3514   [Cursor],
3515   bool),
3516
3517  ("clang_defaultDiagnosticDisplayOptions",
3518   [],
3519   c_uint),
3520
3521  ("clang_defaultSaveOptions",
3522   [TranslationUnit],
3523   c_uint),
3524
3525  ("clang_disposeCodeCompleteResults",
3526   [CodeCompletionResults]),
3527
3528# ("clang_disposeCXTUResourceUsage",
3529#  [CXTUResourceUsage]),
3530
3531  ("clang_disposeDiagnostic",
3532   [Diagnostic]),
3533
3534  ("clang_disposeIndex",
3535   [Index]),
3536
3537  ("clang_disposeString",
3538   [_CXString]),
3539
3540  ("clang_disposeTokens",
3541   [TranslationUnit, POINTER(Token), c_uint]),
3542
3543  ("clang_disposeTranslationUnit",
3544   [TranslationUnit]),
3545
3546  ("clang_equalCursors",
3547   [Cursor, Cursor],
3548   bool),
3549
3550  ("clang_equalLocations",
3551   [SourceLocation, SourceLocation],
3552   bool),
3553
3554  ("clang_equalRanges",
3555   [SourceRange, SourceRange],
3556   bool),
3557
3558  ("clang_equalTypes",
3559   [Type, Type],
3560   bool),
3561
3562  ("clang_formatDiagnostic",
3563   [Diagnostic, c_uint],
3564   _CXString,
3565   _CXString.from_result),
3566
3567  ("clang_getArgType",
3568   [Type, c_uint],
3569   Type,
3570   Type.from_result),
3571
3572  ("clang_getArrayElementType",
3573   [Type],
3574   Type,
3575   Type.from_result),
3576
3577  ("clang_getArraySize",
3578   [Type],
3579   c_longlong),
3580
3581  ("clang_getFieldDeclBitWidth",
3582   [Cursor],
3583   c_int),
3584
3585  ("clang_getCanonicalCursor",
3586   [Cursor],
3587   Cursor,
3588   Cursor.from_cursor_result),
3589
3590  ("clang_getCanonicalType",
3591   [Type],
3592   Type,
3593   Type.from_result),
3594
3595  ("clang_getChildDiagnostics",
3596   [Diagnostic],
3597   c_object_p),
3598
3599  ("clang_getCompletionAvailability",
3600   [c_void_p],
3601   c_int),
3602
3603  ("clang_getCompletionBriefComment",
3604   [c_void_p],
3605   _CXString,
3606   _CXString.from_result),
3607
3608  ("clang_getCompletionChunkCompletionString",
3609   [c_void_p, c_int],
3610   c_object_p),
3611
3612  ("clang_getCompletionChunkKind",
3613   [c_void_p, c_int],
3614   c_int),
3615
3616  ("clang_getCompletionChunkText",
3617   [c_void_p, c_int],
3618   _CXString,
3619   _CXString.from_result),
3620
3621  ("clang_getCompletionPriority",
3622   [c_void_p],
3623   c_int),
3624
3625  ("clang_getCString",
3626   [_CXString],
3627   c_interop_string,
3628   c_interop_string.to_python_string),
3629
3630  ("clang_getCursor",
3631   [TranslationUnit, SourceLocation],
3632   Cursor),
3633
3634  ("clang_getCursorAvailability",
3635   [Cursor],
3636   c_int),
3637
3638  ("clang_getCursorDefinition",
3639   [Cursor],
3640   Cursor,
3641   Cursor.from_result),
3642
3643  ("clang_getCursorDisplayName",
3644   [Cursor],
3645   _CXString,
3646   _CXString.from_result),
3647
3648  ("clang_getCursorExtent",
3649   [Cursor],
3650   SourceRange),
3651
3652  ("clang_getCursorLexicalParent",
3653   [Cursor],
3654   Cursor,
3655   Cursor.from_cursor_result),
3656
3657  ("clang_getCursorLocation",
3658   [Cursor],
3659   SourceLocation),
3660
3661  ("clang_getCursorReferenced",
3662   [Cursor],
3663   Cursor,
3664   Cursor.from_result),
3665
3666  ("clang_getCursorReferenceNameRange",
3667   [Cursor, c_uint, c_uint],
3668   SourceRange),
3669
3670  ("clang_getCursorResultType",
3671   [Cursor],
3672   Type,
3673   Type.from_result),
3674
3675  ("clang_getCursorSemanticParent",
3676   [Cursor],
3677   Cursor,
3678   Cursor.from_cursor_result),
3679
3680  ("clang_getCursorSpelling",
3681   [Cursor],
3682   _CXString,
3683   _CXString.from_result),
3684
3685  ("clang_getCursorType",
3686   [Cursor],
3687   Type,
3688   Type.from_result),
3689
3690  ("clang_getCursorUSR",
3691   [Cursor],
3692   _CXString,
3693   _CXString.from_result),
3694
3695  ("clang_Cursor_getMangling",
3696   [Cursor],
3697   _CXString,
3698   _CXString.from_result),
3699
3700# ("clang_getCXTUResourceUsage",
3701#  [TranslationUnit],
3702#  CXTUResourceUsage),
3703
3704  ("clang_getCXXAccessSpecifier",
3705   [Cursor],
3706   c_uint),
3707
3708  ("clang_getDeclObjCTypeEncoding",
3709   [Cursor],
3710   _CXString,
3711   _CXString.from_result),
3712
3713  ("clang_getDiagnostic",
3714   [c_object_p, c_uint],
3715   c_object_p),
3716
3717  ("clang_getDiagnosticCategory",
3718   [Diagnostic],
3719   c_uint),
3720
3721  ("clang_getDiagnosticCategoryText",
3722   [Diagnostic],
3723   _CXString,
3724   _CXString.from_result),
3725
3726  ("clang_getDiagnosticFixIt",
3727   [Diagnostic, c_uint, POINTER(SourceRange)],
3728   _CXString,
3729   _CXString.from_result),
3730
3731  ("clang_getDiagnosticInSet",
3732   [c_object_p, c_uint],
3733   c_object_p),
3734
3735  ("clang_getDiagnosticLocation",
3736   [Diagnostic],
3737   SourceLocation),
3738
3739  ("clang_getDiagnosticNumFixIts",
3740   [Diagnostic],
3741   c_uint),
3742
3743  ("clang_getDiagnosticNumRanges",
3744   [Diagnostic],
3745   c_uint),
3746
3747  ("clang_getDiagnosticOption",
3748   [Diagnostic, POINTER(_CXString)],
3749   _CXString,
3750   _CXString.from_result),
3751
3752  ("clang_getDiagnosticRange",
3753   [Diagnostic, c_uint],
3754   SourceRange),
3755
3756  ("clang_getDiagnosticSeverity",
3757   [Diagnostic],
3758   c_int),
3759
3760  ("clang_getDiagnosticSpelling",
3761   [Diagnostic],
3762   _CXString,
3763   _CXString.from_result),
3764
3765  ("clang_getElementType",
3766   [Type],
3767   Type,
3768   Type.from_result),
3769
3770  ("clang_getEnumConstantDeclUnsignedValue",
3771   [Cursor],
3772   c_ulonglong),
3773
3774  ("clang_getEnumConstantDeclValue",
3775   [Cursor],
3776   c_longlong),
3777
3778  ("clang_getEnumDeclIntegerType",
3779   [Cursor],
3780   Type,
3781   Type.from_result),
3782
3783  ("clang_getFile",
3784   [TranslationUnit, c_interop_string],
3785   c_object_p),
3786
3787  ("clang_getFileName",
3788   [File],
3789   _CXString,
3790   _CXString.from_result),
3791
3792  ("clang_getFileTime",
3793   [File],
3794   c_uint),
3795
3796  ("clang_getIBOutletCollectionType",
3797   [Cursor],
3798   Type,
3799   Type.from_result),
3800
3801  ("clang_getIncludedFile",
3802   [Cursor],
3803   c_object_p,
3804   File.from_result),
3805
3806  ("clang_getInclusions",
3807   [TranslationUnit, callbacks['translation_unit_includes'], py_object]),
3808
3809  ("clang_getInstantiationLocation",
3810   [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
3811    POINTER(c_uint)]),
3812
3813  ("clang_getLocation",
3814   [TranslationUnit, File, c_uint, c_uint],
3815   SourceLocation),
3816
3817  ("clang_getLocationForOffset",
3818   [TranslationUnit, File, c_uint],
3819   SourceLocation),
3820
3821  ("clang_getNullCursor",
3822   None,
3823   Cursor),
3824
3825  ("clang_getNumArgTypes",
3826   [Type],
3827   c_uint),
3828
3829  ("clang_getNumCompletionChunks",
3830   [c_void_p],
3831   c_int),
3832
3833  ("clang_getNumDiagnostics",
3834   [c_object_p],
3835   c_uint),
3836
3837  ("clang_getNumDiagnosticsInSet",
3838   [c_object_p],
3839   c_uint),
3840
3841  ("clang_getNumElements",
3842   [Type],
3843   c_longlong),
3844
3845  ("clang_getNumOverloadedDecls",
3846   [Cursor],
3847   c_uint),
3848
3849  ("clang_getOverloadedDecl",
3850   [Cursor, c_uint],
3851   Cursor,
3852   Cursor.from_cursor_result),
3853
3854  ("clang_getPointeeType",
3855   [Type],
3856   Type,
3857   Type.from_result),
3858
3859  ("clang_getRange",
3860   [SourceLocation, SourceLocation],
3861   SourceRange),
3862
3863  ("clang_getRangeEnd",
3864   [SourceRange],
3865   SourceLocation),
3866
3867  ("clang_getRangeStart",
3868   [SourceRange],
3869   SourceLocation),
3870
3871  ("clang_getResultType",
3872   [Type],
3873   Type,
3874   Type.from_result),
3875
3876  ("clang_getSpecializedCursorTemplate",
3877   [Cursor],
3878   Cursor,
3879   Cursor.from_cursor_result),
3880
3881  ("clang_getTemplateCursorKind",
3882   [Cursor],
3883   c_uint),
3884
3885  ("clang_getTokenExtent",
3886   [TranslationUnit, Token],
3887   SourceRange),
3888
3889  ("clang_getTokenKind",
3890   [Token],
3891   c_uint),
3892
3893  ("clang_getTokenLocation",
3894   [TranslationUnit, Token],
3895   SourceLocation),
3896
3897  ("clang_getTokenSpelling",
3898   [TranslationUnit, Token],
3899   _CXString,
3900   _CXString.from_result),
3901
3902  ("clang_getTranslationUnitCursor",
3903   [TranslationUnit],
3904   Cursor,
3905   Cursor.from_result),
3906
3907  ("clang_getTranslationUnitSpelling",
3908   [TranslationUnit],
3909   _CXString,
3910   _CXString.from_result),
3911
3912  ("clang_getTUResourceUsageName",
3913   [c_uint],
3914   c_interop_string,
3915   c_interop_string.to_python_string),
3916
3917  ("clang_getTypeDeclaration",
3918   [Type],
3919   Cursor,
3920   Cursor.from_result),
3921
3922  ("clang_getTypedefDeclUnderlyingType",
3923   [Cursor],
3924   Type,
3925   Type.from_result),
3926
3927  ("clang_getTypedefName",
3928   [Type],
3929   _CXString,
3930   _CXString.from_result),
3931
3932  ("clang_getTypeKindSpelling",
3933   [c_uint],
3934   _CXString,
3935   _CXString.from_result),
3936
3937  ("clang_getTypeSpelling",
3938   [Type],
3939   _CXString,
3940   _CXString.from_result),
3941
3942  ("clang_hashCursor",
3943   [Cursor],
3944   c_uint),
3945
3946  ("clang_isAttribute",
3947   [CursorKind],
3948   bool),
3949
3950  ("clang_isConstQualifiedType",
3951   [Type],
3952   bool),
3953
3954  ("clang_isCursorDefinition",
3955   [Cursor],
3956   bool),
3957
3958  ("clang_isDeclaration",
3959   [CursorKind],
3960   bool),
3961
3962  ("clang_isExpression",
3963   [CursorKind],
3964   bool),
3965
3966  ("clang_isFileMultipleIncludeGuarded",
3967   [TranslationUnit, File],
3968   bool),
3969
3970  ("clang_isFunctionTypeVariadic",
3971   [Type],
3972   bool),
3973
3974  ("clang_isInvalid",
3975   [CursorKind],
3976   bool),
3977
3978  ("clang_isPODType",
3979   [Type],
3980   bool),
3981
3982  ("clang_isPreprocessing",
3983   [CursorKind],
3984   bool),
3985
3986  ("clang_isReference",
3987   [CursorKind],
3988   bool),
3989
3990  ("clang_isRestrictQualifiedType",
3991   [Type],
3992   bool),
3993
3994  ("clang_isStatement",
3995   [CursorKind],
3996   bool),
3997
3998  ("clang_isTranslationUnit",
3999   [CursorKind],
4000   bool),
4001
4002  ("clang_isUnexposed",
4003   [CursorKind],
4004   bool),
4005
4006  ("clang_isVirtualBase",
4007   [Cursor],
4008   bool),
4009
4010  ("clang_isVolatileQualifiedType",
4011   [Type],
4012   bool),
4013
4014  ("clang_parseTranslationUnit",
4015   [Index, c_interop_string, c_void_p, c_int, c_void_p, c_int, c_int],
4016   c_object_p),
4017
4018  ("clang_reparseTranslationUnit",
4019   [TranslationUnit, c_int, c_void_p, c_int],
4020   c_int),
4021
4022  ("clang_saveTranslationUnit",
4023   [TranslationUnit, c_interop_string, c_uint],
4024   c_int),
4025
4026  ("clang_tokenize",
4027   [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
4028
4029  ("clang_visitChildren",
4030   [Cursor, callbacks['cursor_visit'], py_object],
4031   c_uint),
4032
4033  ("clang_Cursor_getNumArguments",
4034   [Cursor],
4035   c_int),
4036
4037  ("clang_Cursor_getArgument",
4038   [Cursor, c_uint],
4039   Cursor,
4040   Cursor.from_result),
4041
4042  ("clang_Cursor_getNumTemplateArguments",
4043   [Cursor],
4044   c_int),
4045
4046  ("clang_Cursor_getTemplateArgumentKind",
4047   [Cursor, c_uint],
4048   TemplateArgumentKind.from_id),
4049
4050  ("clang_Cursor_getTemplateArgumentType",
4051   [Cursor, c_uint],
4052   Type,
4053   Type.from_result),
4054
4055  ("clang_Cursor_getTemplateArgumentValue",
4056   [Cursor, c_uint],
4057   c_longlong),
4058
4059  ("clang_Cursor_getTemplateArgumentUnsignedValue",
4060   [Cursor, c_uint],
4061   c_ulonglong),
4062
4063  ("clang_Cursor_isAnonymous",
4064   [Cursor],
4065   bool),
4066
4067  ("clang_Cursor_isBitField",
4068   [Cursor],
4069   bool),
4070
4071  ("clang_Cursor_getBriefCommentText",
4072   [Cursor],
4073   _CXString,
4074   _CXString.from_result),
4075
4076  ("clang_Cursor_getRawCommentText",
4077   [Cursor],
4078   _CXString,
4079   _CXString.from_result),
4080
4081  ("clang_Cursor_getOffsetOfField",
4082   [Cursor],
4083   c_longlong),
4084
4085  ("clang_Type_getAlignOf",
4086   [Type],
4087   c_longlong),
4088
4089  ("clang_Type_getClassType",
4090   [Type],
4091   Type,
4092   Type.from_result),
4093
4094  ("clang_Type_getNumTemplateArguments",
4095   [Type],
4096   c_int),
4097
4098  ("clang_Type_getTemplateArgumentAsType",
4099   [Type, c_uint],
4100   Type,
4101   Type.from_result),
4102
4103  ("clang_Type_getOffsetOf",
4104   [Type, c_interop_string],
4105   c_longlong),
4106
4107  ("clang_Type_getSizeOf",
4108   [Type],
4109   c_longlong),
4110
4111  ("clang_Type_getCXXRefQualifier",
4112   [Type],
4113   c_uint),
4114
4115  ("clang_Type_getNamedType",
4116   [Type],
4117   Type,
4118   Type.from_result),
4119
4120  ("clang_Type_visitFields",
4121   [Type, callbacks['fields_visit'], py_object],
4122   c_uint),
4123]
4124
4125class LibclangError(Exception):
4126    def __init__(self, message):
4127        self.m = message
4128
4129    def __str__(self):
4130        return self.m
4131
4132def register_function(lib, item, ignore_errors):
4133    # A function may not exist, if these bindings are used with an older or
4134    # incompatible version of libclang.so.
4135    try:
4136        func = getattr(lib, item[0])
4137    except AttributeError as e:
4138        msg = str(e) + ". Please ensure that your python bindings are "\
4139                       "compatible with your libclang.so version."
4140        if ignore_errors:
4141            return
4142        raise LibclangError(msg)
4143
4144    if len(item) >= 2:
4145        func.argtypes = item[1]
4146
4147    if len(item) >= 3:
4148        func.restype = item[2]
4149
4150    if len(item) == 4:
4151        func.errcheck = item[3]
4152
4153def register_functions(lib, ignore_errors):
4154    """Register function prototypes with a libclang library instance.
4155
4156    This must be called as part of library instantiation so Python knows how
4157    to call out to the shared library.
4158    """
4159
4160    def register(item):
4161        return register_function(lib, item, ignore_errors)
4162
4163    for f in functionList:
4164        register(f)
4165
4166class Config(object):
4167    library_path = None
4168    library_file = None
4169    compatibility_check = True
4170    loaded = False
4171
4172    @staticmethod
4173    def set_library_path(path):
4174        """Set the path in which to search for libclang"""
4175        if Config.loaded:
4176            raise Exception("library path must be set before before using " \
4177                            "any other functionalities in libclang.")
4178
4179        Config.library_path = fspath(path)
4180
4181    @staticmethod
4182    def set_library_file(filename):
4183        """Set the exact location of libclang"""
4184        if Config.loaded:
4185            raise Exception("library file must be set before before using " \
4186                            "any other functionalities in libclang.")
4187
4188        Config.library_file = fspath(filename)
4189
4190    @staticmethod
4191    def set_compatibility_check(check_status):
4192        """ Perform compatibility check when loading libclang
4193
4194        The python bindings are only tested and evaluated with the version of
4195        libclang they are provided with. To ensure correct behavior a (limited)
4196        compatibility check is performed when loading the bindings. This check
4197        will throw an exception, as soon as it fails.
4198
4199        In case these bindings are used with an older version of libclang, parts
4200        that have been stable between releases may still work. Users of the
4201        python bindings can disable the compatibility check. This will cause
4202        the python bindings to load, even though they are written for a newer
4203        version of libclang. Failures now arise if unsupported or incompatible
4204        features are accessed. The user is required to test themselves if the
4205        features they are using are available and compatible between different
4206        libclang versions.
4207        """
4208        if Config.loaded:
4209            raise Exception("compatibility_check must be set before before " \
4210                            "using any other functionalities in libclang.")
4211
4212        Config.compatibility_check = check_status
4213
4214    @CachedProperty
4215    def lib(self):
4216        lib = self.get_cindex_library()
4217        register_functions(lib, not Config.compatibility_check)
4218        Config.loaded = True
4219        return lib
4220
4221    def get_filename(self):
4222        if Config.library_file:
4223            return Config.library_file
4224
4225        import platform
4226        name = platform.system()
4227
4228        if name == 'Darwin':
4229            file = 'libclang.dylib'
4230        elif name == 'Windows':
4231            file = 'libclang.dll'
4232        else:
4233            file = 'libclang.so'
4234
4235        if Config.library_path:
4236            file = Config.library_path + '/' + file
4237
4238        return file
4239
4240    def get_cindex_library(self):
4241        try:
4242            library = cdll.LoadLibrary(self.get_filename())
4243        except OSError as e:
4244            msg = str(e) + ". To provide a path to libclang use " \
4245                           "Config.set_library_path() or " \
4246                           "Config.set_library_file()."
4247            raise LibclangError(msg)
4248
4249        return library
4250
4251    def function_exists(self, name):
4252        try:
4253            getattr(self.lib, name)
4254        except AttributeError:
4255            return False
4256
4257        return True
4258
4259def register_enumerations():
4260    for name, value in clang.enumerations.TokenKinds:
4261        TokenKind.register(value, name)
4262
4263conf = Config()
4264register_enumerations()
4265
4266__all__ = [
4267    'AvailabilityKind',
4268    'Config',
4269    'CodeCompletionResults',
4270    'CompilationDatabase',
4271    'CompileCommands',
4272    'CompileCommand',
4273    'CursorKind',
4274    'Cursor',
4275    'Diagnostic',
4276    'File',
4277    'FixIt',
4278    'Index',
4279    'LinkageKind',
4280    'SourceLocation',
4281    'SourceRange',
4282    'TLSKind',
4283    'TokenKind',
4284    'Token',
4285    'TranslationUnitLoadError',
4286    'TranslationUnit',
4287    'TypeKind',
4288    'Type',
4289]
4290