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