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