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