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