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