cindex.py revision ba5d10b82b3cc00b4d71b273a18c051a1f38f22f
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 *
66
67def get_cindex_library():
68    # FIXME: It's probably not the case that the library is actually found in
69    # this location. We need a better system of identifying and loading the
70    # CIndex library. It could be on path or elsewhere, or versioned, etc.
71    import platform
72    name = platform.system()
73    if name == 'Darwin':
74        return cdll.LoadLibrary('libclang.dylib')
75    elif name == 'Windows':
76        return cdll.LoadLibrary('libclang.dll')
77    else:
78        return cdll.LoadLibrary('libclang.so')
79
80# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
81# object. This is a problem, because it means that from_parameter will see an
82# integer and pass the wrong value on platforms where int != void*. Work around
83# this by marshalling object arguments as void**.
84c_object_p = POINTER(c_void_p)
85
86lib = get_cindex_library()
87
88### Structures and Utility Classes ###
89
90class _CXString(Structure):
91    """Helper for transforming CXString results."""
92
93    _fields_ = [("spelling", c_char_p), ("free", c_int)]
94
95    def __del__(self):
96        _CXString_dispose(self)
97
98    @staticmethod
99    def from_result(res, fn, args):
100        assert isinstance(res, _CXString)
101        return _CXString_getCString(res)
102
103class SourceLocation(Structure):
104    """
105    A SourceLocation represents a particular location within a source file.
106    """
107    _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
108    _data = None
109
110    def _get_instantiation(self):
111        if self._data is None:
112            f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
113            SourceLocation_loc(self, byref(f), byref(l), byref(c), byref(o))
114            if f:
115                f = File(f)
116            else:
117                f = None
118            self._data = (f, int(l.value), int(c.value), int(o.value))
119        return self._data
120
121    @staticmethod
122    def from_position(tu, file, line, column):
123        """
124        Retrieve the source location associated with a given file/line/column in
125        a particular translation unit.
126        """
127        return SourceLocation_getLocation(tu, file, line, column)
128
129    @property
130    def file(self):
131        """Get the file represented by this source location."""
132        return self._get_instantiation()[0]
133
134    @property
135    def line(self):
136        """Get the line represented by this source location."""
137        return self._get_instantiation()[1]
138
139    @property
140    def column(self):
141        """Get the column represented by this source location."""
142        return self._get_instantiation()[2]
143
144    @property
145    def offset(self):
146        """Get the file offset represented by this source location."""
147        return self._get_instantiation()[3]
148
149    def __repr__(self):
150        if self.file:
151            filename = self.file.name
152        else:
153            filename = None
154        return "<SourceLocation file %r, line %r, column %r>" % (
155            filename, self.line, self.column)
156
157class SourceRange(Structure):
158    """
159    A SourceRange describes a range of source locations within the source
160    code.
161    """
162    _fields_ = [
163        ("ptr_data", c_void_p * 2),
164        ("begin_int_data", c_uint),
165        ("end_int_data", c_uint)]
166
167    # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
168    # object.
169    @staticmethod
170    def from_locations(start, end):
171        return SourceRange_getRange(start, end)
172
173    @property
174    def start(self):
175        """
176        Return a SourceLocation representing the first character within a
177        source range.
178        """
179        return SourceRange_start(self)
180
181    @property
182    def end(self):
183        """
184        Return a SourceLocation representing the last character within a
185        source range.
186        """
187        return SourceRange_end(self)
188
189    def __repr__(self):
190        return "<SourceRange start %r, end %r>" % (self.start, self.end)
191
192class Diagnostic(object):
193    """
194    A Diagnostic is a single instance of a Clang diagnostic. It includes the
195    diagnostic severity, the message, the location the diagnostic occurred, as
196    well as additional source ranges and associated fix-it hints.
197    """
198
199    Ignored = 0
200    Note    = 1
201    Warning = 2
202    Error   = 3
203    Fatal   = 4
204
205    def __init__(self, ptr):
206        self.ptr = ptr
207
208    def __del__(self):
209        _clang_disposeDiagnostic(self)
210
211    @property
212    def severity(self):
213        return _clang_getDiagnosticSeverity(self)
214
215    @property
216    def location(self):
217        return _clang_getDiagnosticLocation(self)
218
219    @property
220    def spelling(self):
221        return _clang_getDiagnosticSpelling(self)
222
223    @property
224    def ranges(self):
225        class RangeIterator:
226            def __init__(self, diag):
227                self.diag = diag
228
229            def __len__(self):
230                return int(_clang_getDiagnosticNumRanges(self.diag))
231
232            def __getitem__(self, key):
233                if (key >= len(self)):
234                    raise IndexError
235                return _clang_getDiagnosticRange(self.diag, key)
236
237        return RangeIterator(self)
238
239    @property
240    def fixits(self):
241        class FixItIterator:
242            def __init__(self, diag):
243                self.diag = diag
244
245            def __len__(self):
246                return int(_clang_getDiagnosticNumFixIts(self.diag))
247
248            def __getitem__(self, key):
249                range = SourceRange()
250                value = _clang_getDiagnosticFixIt(self.diag, key, byref(range))
251                if len(value) == 0:
252                    raise IndexError
253
254                return FixIt(range, value)
255
256        return FixItIterator(self)
257
258    def __repr__(self):
259        return "<Diagnostic severity %r, location %r, spelling %r>" % (
260            self.severity, self.location, self.spelling)
261
262    def from_param(self):
263      return self.ptr
264
265class FixIt(object):
266    """
267    A FixIt represents a transformation to be applied to the source to
268    "fix-it". The fix-it shouldbe applied by replacing the given source range
269    with the given value.
270    """
271
272    def __init__(self, range, value):
273        self.range = range
274        self.value = value
275
276    def __repr__(self):
277        return "<FixIt range %r, value %r>" % (self.range, self.value)
278
279### Cursor Kinds ###
280
281class CursorKind(object):
282    """
283    A CursorKind describes the kind of entity that a cursor points to.
284    """
285
286    # The unique kind objects, indexed by id.
287    _kinds = []
288    _name_map = None
289
290    def __init__(self, value):
291        if value >= len(CursorKind._kinds):
292            CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1)
293        if CursorKind._kinds[value] is not None:
294            raise ValueError,'CursorKind already loaded'
295        self.value = value
296        CursorKind._kinds[value] = self
297        CursorKind._name_map = None
298
299    def from_param(self):
300        return self.value
301
302    @property
303    def name(self):
304        """Get the enumeration name of this cursor kind."""
305        if self._name_map is None:
306            self._name_map = {}
307            for key,value in CursorKind.__dict__.items():
308                if isinstance(value,CursorKind):
309                    self._name_map[value] = key
310        return self._name_map[self]
311
312    @staticmethod
313    def from_id(id):
314        if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None:
315            raise ValueError,'Unknown cursor kind'
316        return CursorKind._kinds[id]
317
318    @staticmethod
319    def get_all_kinds():
320        """Return all CursorKind enumeration instances."""
321        return filter(None, CursorKind._kinds)
322
323    def is_declaration(self):
324        """Test if this is a declaration kind."""
325        return CursorKind_is_decl(self)
326
327    def is_reference(self):
328        """Test if this is a reference kind."""
329        return CursorKind_is_ref(self)
330
331    def is_expression(self):
332        """Test if this is an expression kind."""
333        return CursorKind_is_expr(self)
334
335    def is_statement(self):
336        """Test if this is a statement kind."""
337        return CursorKind_is_stmt(self)
338
339    def is_attribute(self):
340        """Test if this is an attribute kind."""
341        return CursorKind_is_attribute(self)
342
343    def is_invalid(self):
344        """Test if this is an invalid kind."""
345        return CursorKind_is_inv(self)
346
347    def __repr__(self):
348        return 'CursorKind.%s' % (self.name,)
349
350# FIXME: Is there a nicer way to expose this enumeration? We could potentially
351# represent the nested structure, or even build a class hierarchy. The main
352# things we want for sure are (a) simple external access to kinds, (b) a place
353# to hang a description and name, (c) easy to keep in sync with Index.h.
354
355###
356# Declaration Kinds
357
358# A declaration whose specific kind is not exposed via this interface.
359#
360# Unexposed declarations have the same operations as any other kind of
361# declaration; one can extract their location information, spelling, find their
362# definitions, etc. However, the specific kind of the declaration is not
363# reported.
364CursorKind.UNEXPOSED_DECL = CursorKind(1)
365
366# A C or C++ struct.
367CursorKind.STRUCT_DECL = CursorKind(2)
368
369# A C or C++ union.
370CursorKind.UNION_DECL = CursorKind(3)
371
372# A C++ class.
373CursorKind.CLASS_DECL = CursorKind(4)
374
375# An enumeration.
376CursorKind.ENUM_DECL = CursorKind(5)
377
378# A field (in C) or non-static data member (in C++) in a struct, union, or C++
379# class.
380CursorKind.FIELD_DECL = CursorKind(6)
381
382# An enumerator constant.
383CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
384
385# A function.
386CursorKind.FUNCTION_DECL = CursorKind(8)
387
388# A variable.
389CursorKind.VAR_DECL = CursorKind(9)
390
391# A function or method parameter.
392CursorKind.PARM_DECL = CursorKind(10)
393
394# An Objective-C @interface.
395CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
396
397# An Objective-C @interface for a category.
398CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
399
400# An Objective-C @protocol declaration.
401CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
402
403# An Objective-C @property declaration.
404CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
405
406# An Objective-C instance variable.
407CursorKind.OBJC_IVAR_DECL = CursorKind(15)
408
409# An Objective-C instance method.
410CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
411
412# An Objective-C class method.
413CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
414
415# An Objective-C @implementation.
416CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
417
418# An Objective-C @implementation for a category.
419CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
420
421# A typedef.
422CursorKind.TYPEDEF_DECL = CursorKind(20)
423
424# A C++ class method.
425CursorKind.CXX_METHOD = CursorKind(21)
426
427# A C++ namespace.
428CursorKind.NAMESPACE = CursorKind(22)
429
430# A linkage specification, e.g. 'extern "C"'.
431CursorKind.LINKAGE_SPEC = CursorKind(23)
432
433# A C++ constructor.
434CursorKind.CONSTRUCTOR = CursorKind(24)
435
436# A C++ destructor.
437CursorKind.DESTRUCTOR = CursorKind(25)
438
439# A C++ conversion function.
440CursorKind.CONVERSION_FUNCTION = CursorKind(26)
441
442# A C++ template type parameter
443CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
444
445# A C++ non-type template paramater.
446CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
447
448# A C++ template template parameter.
449CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29)
450
451# A C++ function template.
452CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
453
454# A C++ class template.
455CursorKind.CLASS_TEMPLATE = CursorKind(31)
456
457# A C++ class template partial specialization.
458CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
459
460# A C++ namespace alias declaration.
461CursorKind.NAMESPACE_ALIAS = CursorKind(33)
462
463# A C++ using directive
464CursorKind.USING_DIRECTIVE = CursorKind(34)
465
466# A C++ using declaration
467CursorKind.USING_DECLARATION = CursorKind(35)
468
469# A Type alias decl.
470CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
471
472# A Objective-C synthesize decl
473CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
474
475# A Objective-C dynamic decl
476CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
477
478# A C++ access specifier decl.
479CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
480
481
482###
483# Reference Kinds
484
485CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
486CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
487CursorKind.OBJC_CLASS_REF = CursorKind(42)
488
489# A reference to a type declaration.
490#
491# A type reference occurs anywhere where a type is named but not
492# declared. For example, given:
493#   typedef unsigned size_type;
494#   size_type size;
495#
496# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
497# while the type of the variable "size" is referenced. The cursor
498# referenced by the type of size is the typedef for size_type.
499CursorKind.TYPE_REF = CursorKind(43)
500CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
501
502# A reference to a class template, function template, template
503# template parameter, or class template partial specialization.
504CursorKind.TEMPLATE_REF = CursorKind(45)
505
506# A reference to a namespace or namepsace alias.
507CursorKind.NAMESPACE_REF = CursorKind(46)
508
509# A reference to a member of a struct, union, or class that occurs in
510# some non-expression context, e.g., a designated initializer.
511CursorKind.MEMBER_REF = CursorKind(47)
512
513# A reference to a labeled statement.
514CursorKind.LABEL_REF = CursorKind(48)
515
516# A reference toa a set of overloaded functions or function templates
517# that has not yet been resolved to a specific function or function template.
518CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
519
520###
521# Invalid/Error Kinds
522
523CursorKind.INVALID_FILE = CursorKind(70)
524CursorKind.NO_DECL_FOUND = CursorKind(71)
525CursorKind.NOT_IMPLEMENTED = CursorKind(72)
526CursorKind.INVALID_CODE = CursorKind(73)
527
528###
529# Expression Kinds
530
531# An expression whose specific kind is not exposed via this interface.
532#
533# Unexposed expressions have the same operations as any other kind of
534# expression; one can extract their location information, spelling, children,
535# etc. However, the specific kind of the expression is not reported.
536CursorKind.UNEXPOSED_EXPR = CursorKind(100)
537
538# An expression that refers to some value declaration, such as a function,
539# varible, or enumerator.
540CursorKind.DECL_REF_EXPR = CursorKind(101)
541
542# An expression that refers to a member of a struct, union, class, Objective-C
543# class, etc.
544CursorKind.MEMBER_REF_EXPR = CursorKind(102)
545
546# An expression that calls a function.
547CursorKind.CALL_EXPR = CursorKind(103)
548
549# An expression that sends a message to an Objective-C object or class.
550CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
551
552# An expression that represents a block literal.
553CursorKind.BLOCK_EXPR = CursorKind(105)
554
555# An integer literal.
556CursorKind.INTEGER_LITERAL = CursorKind(106)
557
558# A floating point number literal.
559CursorKind.FLOATING_LITERAL = CursorKind(107)
560
561# An imaginary number literal.
562CursorKind.IMAGINARY_LITERAL = CursorKind(108)
563
564# A string literal.
565CursorKind.STRING_LITERAL = CursorKind(109)
566
567# A character literal.
568CursorKind.CHARACTER_LITERAL = CursorKind(110)
569
570# A parenthesized expression, e.g. "(1)".
571#
572# This AST node is only formed if full location information is requested.
573CursorKind.PAREN_EXPR = CursorKind(111)
574
575# This represents the unary-expression's (except sizeof and
576# alignof).
577CursorKind.UNARY_OPERATOR = CursorKind(112)
578
579# [C99 6.5.2.1] Array Subscripting.
580CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
581
582# A builtin binary operation expression such as "x + y" or
583# "x <= y".
584CursorKind.BINARY_OPERATOR = CursorKind(114)
585
586# Compound assignment such as "+=".
587CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
588
589# The ?: ternary operator.
590CursorKind.CONDITONAL_OPERATOR = CursorKind(116)
591
592# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
593# (C++ [expr.cast]), which uses the syntax (Type)expr.
594#
595# For example: (int)f.
596CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
597
598# [C99 6.5.2.5]
599CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
600
601# Describes an C or C++ initializer list.
602CursorKind.INIT_LIST_EXPR = CursorKind(119)
603
604# The GNU address of label extension, representing &&label.
605CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
606
607# This is the GNU Statement Expression extension: ({int X=4; X;})
608CursorKind.StmtExpr = CursorKind(121)
609
610# Represents a C1X generic selection.
611CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
612
613# Implements the GNU __null extension, which is a name for a null
614# pointer constant that has integral type (e.g., int or long) and is the same
615# size and alignment as a pointer.
616#
617# The __null extension is typically only used by system headers, which define
618# NULL as __null in C++ rather than using 0 (which is an integer that may not
619# match the size of a pointer).
620CursorKind.GNU_NULL_EXPR = CursorKind(123)
621
622# C++'s static_cast<> expression.
623CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
624
625# C++'s dynamic_cast<> expression.
626CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
627
628# C++'s reinterpret_cast<> expression.
629CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
630
631# C++'s const_cast<> expression.
632CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
633
634# Represents an explicit C++ type conversion that uses "functional"
635# notion (C++ [expr.type.conv]).
636#
637# Example:
638# \code
639#   x = int(0.5);
640# \endcode
641CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
642
643# A C++ typeid expression (C++ [expr.typeid]).
644CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
645
646# [C++ 2.13.5] C++ Boolean Literal.
647CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
648
649# [C++0x 2.14.7] C++ Pointer Literal.
650CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
651
652# Represents the "this" expression in C++
653CursorKind.CXX_THIS_EXPR = CursorKind(132)
654
655# [C++ 15] C++ Throw Expression.
656#
657# This handles 'throw' and 'throw' assignment-expression. When
658# assignment-expression isn't present, Op will be null.
659CursorKind.CXX_THROW_EXPR = CursorKind(133)
660
661# A new expression for memory allocation and constructor calls, e.g:
662# "new CXXNewExpr(foo)".
663CursorKind.CXX_NEW_EXPR = CursorKind(134)
664
665# A delete expression for memory deallocation and destructor calls,
666# e.g. "delete[] pArray".
667CursorKind.CXX_DELETE_EXPR = CursorKind(135)
668
669# Represents a unary expression.
670CursorKind.CXX_UNARY_EXPR = CursorKind(136)
671
672# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
673CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
674
675# ObjCEncodeExpr, used for in Objective-C.
676CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
677
678# ObjCSelectorExpr used for in Objective-C.
679CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
680
681# Objective-C's protocol expression.
682CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
683
684# An Objective-C "bridged" cast expression, which casts between
685# Objective-C pointers and C pointers, transferring ownership in the process.
686#
687# \code
688#   NSString *str = (__bridge_transfer NSString *)CFCreateString();
689# \endcode
690CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
691
692# Represents a C++0x pack expansion that produces a sequence of
693# expressions.
694#
695# A pack expansion expression contains a pattern (which itself is an
696# expression) followed by an ellipsis. For example:
697CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
698
699# Represents an expression that computes the length of a parameter
700# pack.
701CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
702
703# A statement whose specific kind is not exposed via this interface.
704#
705# Unexposed statements have the same operations as any other kind of statement;
706# one can extract their location information, spelling, children, etc. However,
707# the specific kind of the statement is not reported.
708CursorKind.UNEXPOSED_STMT = CursorKind(200)
709
710# A labelled statement in a function.
711CursorKind.LABEL_STMT = CursorKind(201)
712
713# A compound statement
714CursorKind.COMPOUND_STMT = CursorKind(202)
715
716# A case statement.
717CursorKind.CASE_STMT = CursorKind(203)
718
719# A default statement.
720CursorKind.DEFAULT_STMT = CursorKind(204)
721
722# An if statement.
723CursorKind.IF_STMT = CursorKind(205)
724
725# A switch statement.
726CursorKind.SWITCH_STMT = CursorKind(206)
727
728# A while statement.
729CursorKind.WHILE_STMT = CursorKind(207)
730
731# A do statement.
732CursorKind.DO_STMT = CursorKind(208)
733
734# A for statement.
735CursorKind.FOR_STMT = CursorKind(209)
736
737# A goto statement.
738CursorKind.GOTO_STMT = CursorKind(210)
739
740# An indirect goto statement.
741CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
742
743# A continue statement.
744CursorKind.CONTINUE_STMT = CursorKind(212)
745
746# A break statement.
747CursorKind.BREAK_STMT = CursorKind(213)
748
749# A return statement.
750CursorKind.RETURN_STMT = CursorKind(214)
751
752# A GNU-style inline assembler statement.
753CursorKind.ASM_STMT = CursorKind(215)
754
755# Objective-C's overall @try-@catch-@finally statement.
756CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
757
758# Objective-C's @catch statement.
759CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
760
761# Objective-C's @finally statement.
762CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
763
764# Objective-C's @throw statement.
765CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
766
767# Objective-C's @synchronized statement.
768CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
769
770# Objective-C's autorealease pool statement.
771CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
772
773# Objective-C's for collection statement.
774CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
775
776# C++'s catch statement.
777CursorKind.CXX_CATCH_STMT = CursorKind(223)
778
779# C++'s try statement.
780CursorKind.CXX_TRY_STMT = CursorKind(224)
781
782# C++'s for (* : *) statement.
783CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
784
785# Windows Structured Exception Handling's try statement.
786CursorKind.SEH_TRY_STMT = CursorKind(226)
787
788# Windows Structured Exception Handling's except statement.
789CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
790
791# Windows Structured Exception Handling's finally statement.
792CursorKind.SEH_FINALLY_STMT = CursorKind(228)
793
794# The null statement.
795CursorKind.NULL_STMT = CursorKind(230)
796
797# Adaptor class for mixing declarations with statements and expressions.
798CursorKind.DECL_STMT = CursorKind(231)
799
800###
801# Other Kinds
802
803# Cursor that represents the translation unit itself.
804#
805# The translation unit cursor exists primarily to act as the root cursor for
806# traversing the contents of a translation unit.
807CursorKind.TRANSLATION_UNIT = CursorKind(300)
808
809###
810# Attributes
811
812# An attribute whoe specific kind is note exposed via this interface
813CursorKind.UNEXPOSED_ATTR = CursorKind(400)
814
815CursorKind.IB_ACTION_ATTR = CursorKind(401)
816CursorKind.IB_OUTLET_ATTR = CursorKind(402)
817CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
818
819###
820# Preprocessing
821CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
822CursorKind.MACRO_DEFINITION = CursorKind(501)
823CursorKind.MACRO_INSTANTIATION = CursorKind(502)
824CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
825
826### Cursors ###
827
828class Cursor(Structure):
829    """
830    The Cursor class represents a reference to an element within the AST. It
831    acts as a kind of iterator.
832    """
833    _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
834
835    @staticmethod
836    def from_location(tu, location):
837        return Cursor_get(tu, location)
838
839    def __eq__(self, other):
840        return Cursor_eq(self, other)
841
842    def __ne__(self, other):
843        return not Cursor_eq(self, other)
844
845    def is_definition(self):
846        """
847        Returns true if the declaration pointed at by the cursor is also a
848        definition of that entity.
849        """
850        return Cursor_is_def(self)
851
852    def get_definition(self):
853        """
854        If the cursor is a reference to a declaration or a declaration of
855        some entity, return a cursor that points to the definition of that
856        entity.
857        """
858        # TODO: Should probably check that this is either a reference or
859        # declaration prior to issuing the lookup.
860        return Cursor_def(self)
861
862    def get_usr(self):
863        """Return the Unified Symbol Resultion (USR) for the entity referenced
864        by the given cursor (or None).
865
866        A Unified Symbol Resolution (USR) is a string that identifies a
867        particular entity (function, class, variable, etc.) within a
868        program. USRs can be compared across translation units to determine,
869        e.g., when references in one translation refer to an entity defined in
870        another translation unit."""
871        return Cursor_usr(self)
872
873    @property
874    def kind(self):
875        """Return the kind of this cursor."""
876        return CursorKind.from_id(self._kind_id)
877
878    @property
879    def spelling(self):
880        """Return the spelling of the entity pointed at by the cursor."""
881        if not self.kind.is_declaration():
882            # FIXME: clang_getCursorSpelling should be fixed to not assert on
883            # this, for consistency with clang_getCursorUSR.
884            return None
885        if not hasattr(self, '_spelling'):
886            self._spelling = Cursor_spelling(self)
887        return self._spelling
888
889    @property
890    def displayname(self):
891        """
892        Return the display name for the entity referenced by this cursor.
893
894        The display name contains extra information that helps identify the cursor,
895        such as the parameters of a function or template or the arguments of a
896        class template specialization.
897        """
898        if not hasattr(self, '_displayname'):
899            self._displayname = Cursor_displayname(self)
900        return self._displayname
901
902    @property
903    def location(self):
904        """
905        Return the source location (the starting character) of the entity
906        pointed at by the cursor.
907        """
908        if not hasattr(self, '_loc'):
909            self._loc = Cursor_loc(self)
910        return self._loc
911
912    @property
913    def extent(self):
914        """
915        Return the source range (the range of text) occupied by the entity
916        pointed at by the cursor.
917        """
918        if not hasattr(self, '_extent'):
919            self._extent = Cursor_extent(self)
920        return self._extent
921
922    @property
923    def type(self):
924        """
925        Retrieve the type (if any) of of the entity pointed at by the
926        cursor.
927        """
928        if not hasattr(self, '_type'):
929            self._type = Cursor_type(self)
930        return self._type
931
932    def get_children(self):
933        """Return an iterator for accessing the children of this cursor."""
934
935        # FIXME: Expose iteration from CIndex, PR6125.
936        def visitor(child, parent, children):
937            # FIXME: Document this assertion in API.
938            # FIXME: There should just be an isNull method.
939            assert child != Cursor_null()
940            children.append(child)
941            return 1 # continue
942        children = []
943        Cursor_visit(self, Cursor_visit_callback(visitor), children)
944        return iter(children)
945
946    @staticmethod
947    def from_result(res, fn, args):
948        assert isinstance(res, Cursor)
949        # FIXME: There should just be an isNull method.
950        if res == Cursor_null():
951            return None
952        return res
953
954
955### Type Kinds ###
956
957class TypeKind(object):
958    """
959    Describes the kind of type.
960    """
961
962    # The unique kind objects, indexed by id.
963    _kinds = []
964    _name_map = None
965
966    def __init__(self, value):
967        if value >= len(TypeKind._kinds):
968            TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
969        if TypeKind._kinds[value] is not None:
970            raise ValueError,'TypeKind already loaded'
971        self.value = value
972        TypeKind._kinds[value] = self
973        TypeKind._name_map = None
974
975    def from_param(self):
976        return self.value
977
978    @property
979    def name(self):
980        """Get the enumeration name of this cursor kind."""
981        if self._name_map is None:
982            self._name_map = {}
983            for key,value in TypeKind.__dict__.items():
984                if isinstance(value,TypeKind):
985                    self._name_map[value] = key
986        return self._name_map[self]
987
988    @staticmethod
989    def from_id(id):
990        if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
991            raise ValueError,'Unknown type kind %d' % id
992        return TypeKind._kinds[id]
993
994    def __repr__(self):
995        return 'TypeKind.%s' % (self.name,)
996
997
998
999TypeKind.INVALID = TypeKind(0)
1000TypeKind.UNEXPOSED = TypeKind(1)
1001TypeKind.VOID = TypeKind(2)
1002TypeKind.BOOL = TypeKind(3)
1003TypeKind.CHAR_U = TypeKind(4)
1004TypeKind.UCHAR = TypeKind(5)
1005TypeKind.CHAR16 = TypeKind(6)
1006TypeKind.CHAR32 = TypeKind(7)
1007TypeKind.USHORT = TypeKind(8)
1008TypeKind.UINT = TypeKind(9)
1009TypeKind.ULONG = TypeKind(10)
1010TypeKind.ULONGLONG = TypeKind(11)
1011TypeKind.UINT128 = TypeKind(12)
1012TypeKind.CHAR_S = TypeKind(13)
1013TypeKind.SCHAR = TypeKind(14)
1014TypeKind.WCHAR = TypeKind(15)
1015TypeKind.SHORT = TypeKind(16)
1016TypeKind.INT = TypeKind(17)
1017TypeKind.LONG = TypeKind(18)
1018TypeKind.LONGLONG = TypeKind(19)
1019TypeKind.INT128 = TypeKind(20)
1020TypeKind.FLOAT = TypeKind(21)
1021TypeKind.DOUBLE = TypeKind(22)
1022TypeKind.LONGDOUBLE = TypeKind(23)
1023TypeKind.NULLPTR = TypeKind(24)
1024TypeKind.OVERLOAD = TypeKind(25)
1025TypeKind.DEPENDENT = TypeKind(26)
1026TypeKind.OBJCID = TypeKind(27)
1027TypeKind.OBJCCLASS = TypeKind(28)
1028TypeKind.OBJCSEL = TypeKind(29)
1029TypeKind.COMPLEX = TypeKind(100)
1030TypeKind.POINTER = TypeKind(101)
1031TypeKind.BLOCKPOINTER = TypeKind(102)
1032TypeKind.LVALUEREFERENCE = TypeKind(103)
1033TypeKind.RVALUEREFERENCE = TypeKind(104)
1034TypeKind.RECORD = TypeKind(105)
1035TypeKind.ENUM = TypeKind(106)
1036TypeKind.TYPEDEF = TypeKind(107)
1037TypeKind.OBJCINTERFACE = TypeKind(108)
1038TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1039TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1040TypeKind.FUNCTIONPROTO = TypeKind(111)
1041TypeKind.CONSTANTARRAY = TypeKind(112)
1042
1043class Type(Structure):
1044    """
1045    The type of an element in the abstract syntax tree.
1046    """
1047    _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1048
1049    @property
1050    def kind(self):
1051        """Return the kind of this type."""
1052        return TypeKind.from_id(self._kind_id)
1053
1054    @staticmethod
1055    def from_result(res, fn, args):
1056        assert isinstance(res, Type)
1057        return res
1058
1059    def get_canonical(self):
1060        """
1061        Return the canonical type for a Type.
1062
1063        Clang's type system explicitly models typedefs and all the
1064        ways a specific type can be represented.  The canonical type
1065        is the underlying type with all the "sugar" removed.  For
1066        example, if 'T' is a typedef for 'int', the canonical type for
1067        'T' would be 'int'.
1068        """
1069        return Type_get_canonical(self)
1070
1071    def is_const_qualified(self):
1072        """
1073        Determine whether a Type has the "const" qualifier set,
1074        without looking through typedefs that may have added "const"
1075        at a different level.
1076        """
1077        return Type_is_const_qualified(self)
1078
1079    def is_volatile_qualified(self):
1080        """
1081        Determine whether a Type has the "volatile" qualifier set,
1082        without looking through typedefs that may have added
1083        "volatile" at a different level.
1084        """
1085        return Type_is_volatile_qualified(self)
1086
1087    def is_restrict_qualified(self):
1088        """
1089        Determine whether a Type has the "restrict" qualifier set,
1090        without looking through typedefs that may have added
1091        "restrict" at a different level.
1092        """
1093        return Type_is_restrict_qualified(self)
1094
1095    def get_pointee(self):
1096        """
1097        For pointer types, returns the type of the pointee.
1098        """
1099        return Type_get_pointee(self)
1100
1101    def get_declaration(self):
1102        """
1103        Return the cursor for the declaration of the given type.
1104        """
1105        return Type_get_declaration(self)
1106
1107    def get_result(self):
1108        """
1109        Retrieve the result type associated with a function type.
1110        """
1111        return Type_get_result(self)
1112
1113    def get_array_element_type(self):
1114        """
1115        Retrieve the type of the elements of the array type.
1116        """
1117        return Type_get_array_element(self)
1118
1119    def get_array_size(self):
1120        """
1121        Retrieve the size of the constant array.
1122        """
1123        return Type_get_array_size(self)
1124
1125## CIndex Objects ##
1126
1127# CIndex objects (derived from ClangObject) are essentially lightweight
1128# wrappers attached to some underlying object, which is exposed via CIndex as
1129# a void*.
1130
1131class ClangObject(object):
1132    """
1133    A helper for Clang objects. This class helps act as an intermediary for
1134    the ctypes library and the Clang CIndex library.
1135    """
1136    def __init__(self, obj):
1137        assert isinstance(obj, c_object_p) and obj
1138        self.obj = self._as_parameter_ = obj
1139
1140    def from_param(self):
1141        return self._as_parameter_
1142
1143
1144class _CXUnsavedFile(Structure):
1145    """Helper for passing unsaved file arguments."""
1146    _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1147
1148## Diagnostic Conversion ##
1149
1150_clang_getNumDiagnostics = lib.clang_getNumDiagnostics
1151_clang_getNumDiagnostics.argtypes = [c_object_p]
1152_clang_getNumDiagnostics.restype = c_uint
1153
1154_clang_getDiagnostic = lib.clang_getDiagnostic
1155_clang_getDiagnostic.argtypes = [c_object_p, c_uint]
1156_clang_getDiagnostic.restype = c_object_p
1157
1158_clang_disposeDiagnostic = lib.clang_disposeDiagnostic
1159_clang_disposeDiagnostic.argtypes = [Diagnostic]
1160
1161_clang_getDiagnosticSeverity = lib.clang_getDiagnosticSeverity
1162_clang_getDiagnosticSeverity.argtypes = [Diagnostic]
1163_clang_getDiagnosticSeverity.restype = c_int
1164
1165_clang_getDiagnosticLocation = lib.clang_getDiagnosticLocation
1166_clang_getDiagnosticLocation.argtypes = [Diagnostic]
1167_clang_getDiagnosticLocation.restype = SourceLocation
1168
1169_clang_getDiagnosticSpelling = lib.clang_getDiagnosticSpelling
1170_clang_getDiagnosticSpelling.argtypes = [Diagnostic]
1171_clang_getDiagnosticSpelling.restype = _CXString
1172_clang_getDiagnosticSpelling.errcheck = _CXString.from_result
1173
1174_clang_getDiagnosticNumRanges = lib.clang_getDiagnosticNumRanges
1175_clang_getDiagnosticNumRanges.argtypes = [Diagnostic]
1176_clang_getDiagnosticNumRanges.restype = c_uint
1177
1178_clang_getDiagnosticRange = lib.clang_getDiagnosticRange
1179_clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint]
1180_clang_getDiagnosticRange.restype = SourceRange
1181
1182_clang_getDiagnosticNumFixIts = lib.clang_getDiagnosticNumFixIts
1183_clang_getDiagnosticNumFixIts.argtypes = [Diagnostic]
1184_clang_getDiagnosticNumFixIts.restype = c_uint
1185
1186_clang_getDiagnosticFixIt = lib.clang_getDiagnosticFixIt
1187_clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint, POINTER(SourceRange)]
1188_clang_getDiagnosticFixIt.restype = _CXString
1189_clang_getDiagnosticFixIt.errcheck = _CXString.from_result
1190
1191###
1192
1193class CompletionChunk:
1194    class Kind:
1195        def __init__(self, name):
1196            self.name = name
1197
1198        def __str__(self):
1199            return self.name
1200
1201        def __repr__(self):
1202            return "<ChunkKind: %s>" % self
1203
1204    def __init__(self, completionString, key):
1205        self.cs = completionString
1206        self.key = key
1207
1208    def __repr__(self):
1209        return "{'" + self.spelling + "', " + str(self.kind) + "}"
1210
1211    @property
1212    def spelling(self):
1213        return _clang_getCompletionChunkText(self.cs, self.key).spelling
1214
1215    @property
1216    def kind(self):
1217        res = _clang_getCompletionChunkKind(self.cs, self.key)
1218        return completionChunkKindMap[res]
1219
1220    @property
1221    def string(self):
1222        res = _clang_getCompletionChunkCompletionString(self.cs, self.key)
1223
1224        if (res):
1225          return CompletionString(res)
1226        else:
1227          None
1228
1229    def isKindOptional(self):
1230      return self.kind == completionChunkKindMap[0]
1231
1232    def isKindTypedText(self):
1233      return self.kind == completionChunkKindMap[1]
1234
1235    def isKindPlaceHolder(self):
1236      return self.kind == completionChunkKindMap[3]
1237
1238    def isKindInformative(self):
1239      return self.kind == completionChunkKindMap[4]
1240
1241    def isKindResultType(self):
1242      return self.kind == completionChunkKindMap[15]
1243
1244completionChunkKindMap = {
1245            0: CompletionChunk.Kind("Optional"),
1246            1: CompletionChunk.Kind("TypedText"),
1247            2: CompletionChunk.Kind("Text"),
1248            3: CompletionChunk.Kind("Placeholder"),
1249            4: CompletionChunk.Kind("Informative"),
1250            5: CompletionChunk.Kind("CurrentParameter"),
1251            6: CompletionChunk.Kind("LeftParen"),
1252            7: CompletionChunk.Kind("RightParen"),
1253            8: CompletionChunk.Kind("LeftBracket"),
1254            9: CompletionChunk.Kind("RightBracket"),
1255            10: CompletionChunk.Kind("LeftBrace"),
1256            11: CompletionChunk.Kind("RightBrace"),
1257            12: CompletionChunk.Kind("LeftAngle"),
1258            13: CompletionChunk.Kind("RightAngle"),
1259            14: CompletionChunk.Kind("Comma"),
1260            15: CompletionChunk.Kind("ResultType"),
1261            16: CompletionChunk.Kind("Colon"),
1262            17: CompletionChunk.Kind("SemiColon"),
1263            18: CompletionChunk.Kind("Equal"),
1264            19: CompletionChunk.Kind("HorizontalSpace"),
1265            20: CompletionChunk.Kind("VerticalSpace")}
1266
1267class CompletionString(ClangObject):
1268    class Availability:
1269        def __init__(self, name):
1270            self.name = name
1271
1272        def __str__(self):
1273            return self.name
1274
1275        def __repr__(self):
1276            return "<Availability: %s>" % self
1277
1278    def __len__(self):
1279        return _clang_getNumCompletionChunks(self.obj)
1280
1281    def __getitem__(self, key):
1282        if len(self) <= key:
1283            raise IndexError
1284        return CompletionChunk(self.obj, key)
1285
1286    @property
1287    def priority(self):
1288        return _clang_getCompletionPriority(self.obj)
1289
1290    @property
1291    def availability(self):
1292        res = _clang_getCompletionAvailability(self.obj)
1293        return availabilityKinds[res]
1294
1295    def __repr__(self):
1296        return " | ".join([str(a) for a in self]) \
1297               + " || Priority: " + str(self.priority) \
1298               + " || Availability: " + str(self.availability)
1299
1300availabilityKinds = {
1301            0: CompletionChunk.Kind("Available"),
1302            1: CompletionChunk.Kind("Deprecated"),
1303            2: CompletionChunk.Kind("NotAvailable")}
1304
1305class CodeCompletionResult(Structure):
1306    _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
1307
1308    def __repr__(self):
1309        return str(CompletionString(self.completionString))
1310
1311    @property
1312    def kind(self):
1313        return CursorKind.from_id(self.cursorKind)
1314
1315    @property
1316    def string(self):
1317        return CompletionString(self.completionString)
1318
1319class CCRStructure(Structure):
1320    _fields_ = [('results', POINTER(CodeCompletionResult)),
1321                ('numResults', c_int)]
1322
1323    def __len__(self):
1324        return self.numResults
1325
1326    def __getitem__(self, key):
1327        if len(self) <= key:
1328            raise IndexError
1329
1330        return self.results[key]
1331
1332class CodeCompletionResults(ClangObject):
1333    def __init__(self, ptr):
1334        assert isinstance(ptr, POINTER(CCRStructure)) and ptr
1335        self.ptr = self._as_parameter_ = ptr
1336
1337    def from_param(self):
1338        return self._as_parameter_
1339
1340    def __del__(self):
1341        CodeCompletionResults_dispose(self)
1342
1343    @property
1344    def results(self):
1345        return self.ptr.contents
1346
1347    @property
1348    def diagnostics(self):
1349        class DiagnosticsItr:
1350            def __init__(self, ccr):
1351                self.ccr= ccr
1352
1353            def __len__(self):
1354                return int(_clang_codeCompleteGetNumDiagnostics(self.ccr))
1355
1356            def __getitem__(self, key):
1357                return _clang_codeCompleteGetDiagnostic(self.ccr, key)
1358
1359        return DiagnosticsItr(self)
1360
1361
1362class Index(ClangObject):
1363    """
1364    The Index type provides the primary interface to the Clang CIndex library,
1365    primarily by providing an interface for reading and parsing translation
1366    units.
1367    """
1368
1369    @staticmethod
1370    def create(excludeDecls=False):
1371        """
1372        Create a new Index.
1373        Parameters:
1374        excludeDecls -- Exclude local declarations from translation units.
1375        """
1376        return Index(Index_create(excludeDecls, 0))
1377
1378    def __del__(self):
1379        Index_dispose(self)
1380
1381    def read(self, path):
1382        """Load the translation unit from the given AST file."""
1383        ptr = TranslationUnit_read(self, path)
1384        if ptr:
1385            return TranslationUnit(ptr)
1386        return None
1387
1388    def parse(self, path, args = [], unsaved_files = [], options = 0):
1389        """
1390        Load the translation unit from the given source code file by running
1391        clang and generating the AST before loading. Additional command line
1392        parameters can be passed to clang via the args parameter.
1393
1394        In-memory contents for files can be provided by passing a list of pairs
1395        to as unsaved_files, the first item should be the filenames to be mapped
1396        and the second should be the contents to be substituted for the
1397        file. The contents may be passed as strings or file objects.
1398        """
1399        arg_array = 0
1400        if len(args):
1401            arg_array = (c_char_p * len(args))(* args)
1402        unsaved_files_array = 0
1403        if len(unsaved_files):
1404            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
1405            for i,(name,value) in enumerate(unsaved_files):
1406                if not isinstance(value, str):
1407                    # FIXME: It would be great to support an efficient version
1408                    # of this, one day.
1409                    value = value.read()
1410                    print value
1411                if not isinstance(value, str):
1412                    raise TypeError,'Unexpected unsaved file contents.'
1413                unsaved_files_array[i].name = name
1414                unsaved_files_array[i].contents = value
1415                unsaved_files_array[i].length = len(value)
1416        ptr = TranslationUnit_parse(self, path, arg_array, len(args),
1417                                    unsaved_files_array, len(unsaved_files),
1418                                    options)
1419        if ptr:
1420            return TranslationUnit(ptr)
1421        return None
1422
1423
1424class TranslationUnit(ClangObject):
1425    """
1426    The TranslationUnit class represents a source code translation unit and
1427    provides read-only access to its top-level declarations.
1428    """
1429
1430    def __init__(self, ptr):
1431        ClangObject.__init__(self, ptr)
1432
1433    def __del__(self):
1434        TranslationUnit_dispose(self)
1435
1436    @property
1437    def cursor(self):
1438        """Retrieve the cursor that represents the given translation unit."""
1439        return TranslationUnit_cursor(self)
1440
1441    @property
1442    def spelling(self):
1443        """Get the original translation unit source file name."""
1444        return TranslationUnit_spelling(self)
1445
1446    def get_includes(self):
1447        """
1448        Return an iterable sequence of FileInclusion objects that describe the
1449        sequence of inclusions in a translation unit. The first object in
1450        this sequence is always the input file. Note that this method will not
1451        recursively iterate over header files included through precompiled
1452        headers.
1453        """
1454        def visitor(fobj, lptr, depth, includes):
1455            if depth > 0:
1456                loc = lptr.contents
1457                includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
1458
1459        # Automatically adapt CIndex/ctype pointers to python objects
1460        includes = []
1461        TranslationUnit_includes(self,
1462                                 TranslationUnit_includes_callback(visitor),
1463                                 includes)
1464        return iter(includes)
1465
1466    @property
1467    def diagnostics(self):
1468        """
1469        Return an iterable (and indexable) object containing the diagnostics.
1470        """
1471        class DiagIterator:
1472            def __init__(self, tu):
1473                self.tu = tu
1474
1475            def __len__(self):
1476                return int(_clang_getNumDiagnostics(self.tu))
1477
1478            def __getitem__(self, key):
1479                diag = _clang_getDiagnostic(self.tu, key)
1480                if not diag:
1481                    raise IndexError
1482                return Diagnostic(diag)
1483
1484        return DiagIterator(self)
1485
1486    def reparse(self, unsaved_files = [], options = 0):
1487        """
1488        Reparse an already parsed translation unit.
1489
1490        In-memory contents for files can be provided by passing a list of pairs
1491        as unsaved_files, the first items should be the filenames to be mapped
1492        and the second should be the contents to be substituted for the
1493        file. The contents may be passed as strings or file objects.
1494        """
1495        unsaved_files_array = 0
1496        if len(unsaved_files):
1497            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
1498            for i,(name,value) in enumerate(unsaved_files):
1499                if not isinstance(value, str):
1500                    # FIXME: It would be great to support an efficient version
1501                    # of this, one day.
1502                    value = value.read()
1503                    print value
1504                if not isinstance(value, str):
1505                    raise TypeError,'Unexpected unsaved file contents.'
1506                unsaved_files_array[i].name = name
1507                unsaved_files_array[i].contents = value
1508                unsaved_files_array[i].length = len(value)
1509        ptr = TranslationUnit_reparse(self, len(unsaved_files),
1510                                      unsaved_files_array,
1511                                      options)
1512    def codeComplete(self, path, line, column, unsaved_files = [], options = 0):
1513        """
1514        Code complete in this translation unit.
1515
1516        In-memory contents for files can be provided by passing a list of pairs
1517        as unsaved_files, the first items should be the filenames to be mapped
1518        and the second should be the contents to be substituted for the
1519        file. The contents may be passed as strings or file objects.
1520        """
1521        unsaved_files_array = 0
1522        if len(unsaved_files):
1523            unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
1524            for i,(name,value) in enumerate(unsaved_files):
1525                if not isinstance(value, str):
1526                    # FIXME: It would be great to support an efficient version
1527                    # of this, one day.
1528                    value = value.read()
1529                    print value
1530                if not isinstance(value, str):
1531                    raise TypeError,'Unexpected unsaved file contents.'
1532                unsaved_files_array[i].name = name
1533                unsaved_files_array[i].contents = value
1534                unsaved_files_array[i].length = len(value)
1535        ptr = TranslationUnit_codeComplete(self, path,
1536                                           line, column,
1537                                           unsaved_files_array,
1538                                           len(unsaved_files),
1539                                           options)
1540        if ptr:
1541            return CodeCompletionResults(ptr)
1542        return None
1543
1544class File(ClangObject):
1545    """
1546    The File class represents a particular source file that is part of a
1547    translation unit.
1548    """
1549
1550    @staticmethod
1551    def from_name(translation_unit, file_name):
1552        """Retrieve a file handle within the given translation unit."""
1553        return File(File_getFile(translation_unit, file_name))
1554
1555    @property
1556    def name(self):
1557        """Return the complete file and path name of the file."""
1558        return _CXString_getCString(File_name(self))
1559
1560    @property
1561    def time(self):
1562        """Return the last modification time of the file."""
1563        return File_time(self)
1564
1565    def __str__(self):
1566        return self.name
1567
1568    def __repr__(self):
1569        return "<File: %s>" % (self.name)
1570
1571class FileInclusion(object):
1572    """
1573    The FileInclusion class represents the inclusion of one source file by
1574    another via a '#include' directive or as the input file for the translation
1575    unit. This class provides information about the included file, the including
1576    file, the location of the '#include' directive and the depth of the included
1577    file in the stack. Note that the input file has depth 0.
1578    """
1579
1580    def __init__(self, src, tgt, loc, depth):
1581        self.source = src
1582        self.include = tgt
1583        self.location = loc
1584        self.depth = depth
1585
1586    @property
1587    def is_input_file(self):
1588        """True if the included file is the input file."""
1589        return self.depth == 0
1590
1591# Additional Functions and Types
1592
1593# String Functions
1594_CXString_dispose = lib.clang_disposeString
1595_CXString_dispose.argtypes = [_CXString]
1596
1597_CXString_getCString = lib.clang_getCString
1598_CXString_getCString.argtypes = [_CXString]
1599_CXString_getCString.restype = c_char_p
1600
1601# Source Location Functions
1602SourceLocation_loc = lib.clang_getInstantiationLocation
1603SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_object_p),
1604                               POINTER(c_uint), POINTER(c_uint),
1605                               POINTER(c_uint)]
1606
1607SourceLocation_getLocation = lib.clang_getLocation
1608SourceLocation_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint]
1609SourceLocation_getLocation.restype = SourceLocation
1610
1611# Source Range Functions
1612SourceRange_getRange = lib.clang_getRange
1613SourceRange_getRange.argtypes = [SourceLocation, SourceLocation]
1614SourceRange_getRange.restype = SourceRange
1615
1616SourceRange_start = lib.clang_getRangeStart
1617SourceRange_start.argtypes = [SourceRange]
1618SourceRange_start.restype = SourceLocation
1619
1620SourceRange_end = lib.clang_getRangeEnd
1621SourceRange_end.argtypes = [SourceRange]
1622SourceRange_end.restype = SourceLocation
1623
1624# CursorKind Functions
1625CursorKind_is_decl = lib.clang_isDeclaration
1626CursorKind_is_decl.argtypes = [CursorKind]
1627CursorKind_is_decl.restype = bool
1628
1629CursorKind_is_ref = lib.clang_isReference
1630CursorKind_is_ref.argtypes = [CursorKind]
1631CursorKind_is_ref.restype = bool
1632
1633CursorKind_is_expr = lib.clang_isExpression
1634CursorKind_is_expr.argtypes = [CursorKind]
1635CursorKind_is_expr.restype = bool
1636
1637CursorKind_is_stmt = lib.clang_isStatement
1638CursorKind_is_stmt.argtypes = [CursorKind]
1639CursorKind_is_stmt.restype = bool
1640
1641CursorKind_is_attribute = lib.clang_isAttribute
1642CursorKind_is_attribute.argtypes = [CursorKind]
1643CursorKind_is_attribute.restype = bool
1644
1645CursorKind_is_inv = lib.clang_isInvalid
1646CursorKind_is_inv.argtypes = [CursorKind]
1647CursorKind_is_inv.restype = bool
1648
1649# Cursor Functions
1650# TODO: Implement this function
1651Cursor_get = lib.clang_getCursor
1652Cursor_get.argtypes = [TranslationUnit, SourceLocation]
1653Cursor_get.restype = Cursor
1654
1655Cursor_null = lib.clang_getNullCursor
1656Cursor_null.restype = Cursor
1657
1658Cursor_usr = lib.clang_getCursorUSR
1659Cursor_usr.argtypes = [Cursor]
1660Cursor_usr.restype = _CXString
1661Cursor_usr.errcheck = _CXString.from_result
1662
1663Cursor_is_def = lib.clang_isCursorDefinition
1664Cursor_is_def.argtypes = [Cursor]
1665Cursor_is_def.restype = bool
1666
1667Cursor_def = lib.clang_getCursorDefinition
1668Cursor_def.argtypes = [Cursor]
1669Cursor_def.restype = Cursor
1670Cursor_def.errcheck = Cursor.from_result
1671
1672Cursor_eq = lib.clang_equalCursors
1673Cursor_eq.argtypes = [Cursor, Cursor]
1674Cursor_eq.restype = c_uint
1675
1676Cursor_spelling = lib.clang_getCursorSpelling
1677Cursor_spelling.argtypes = [Cursor]
1678Cursor_spelling.restype = _CXString
1679Cursor_spelling.errcheck = _CXString.from_result
1680
1681Cursor_displayname = lib.clang_getCursorDisplayName
1682Cursor_displayname.argtypes = [Cursor]
1683Cursor_displayname.restype = _CXString
1684Cursor_displayname.errcheck = _CXString.from_result
1685
1686Cursor_loc = lib.clang_getCursorLocation
1687Cursor_loc.argtypes = [Cursor]
1688Cursor_loc.restype = SourceLocation
1689
1690Cursor_extent = lib.clang_getCursorExtent
1691Cursor_extent.argtypes = [Cursor]
1692Cursor_extent.restype = SourceRange
1693
1694Cursor_ref = lib.clang_getCursorReferenced
1695Cursor_ref.argtypes = [Cursor]
1696Cursor_ref.restype = Cursor
1697Cursor_ref.errcheck = Cursor.from_result
1698
1699Cursor_type = lib.clang_getCursorType
1700Cursor_type.argtypes = [Cursor]
1701Cursor_type.restype = Type
1702Cursor_type.errcheck = Type.from_result
1703
1704Cursor_visit_callback = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
1705Cursor_visit = lib.clang_visitChildren
1706Cursor_visit.argtypes = [Cursor, Cursor_visit_callback, py_object]
1707Cursor_visit.restype = c_uint
1708
1709# Type Functions
1710Type_get_canonical = lib.clang_getCanonicalType
1711Type_get_canonical.argtypes = [Type]
1712Type_get_canonical.restype = Type
1713Type_get_canonical.errcheck = Type.from_result
1714
1715Type_is_const_qualified = lib.clang_isConstQualifiedType
1716Type_is_const_qualified.argtypes = [Type]
1717Type_is_const_qualified.restype = bool
1718
1719Type_is_volatile_qualified = lib.clang_isVolatileQualifiedType
1720Type_is_volatile_qualified.argtypes = [Type]
1721Type_is_volatile_qualified.restype = bool
1722
1723Type_is_restrict_qualified = lib.clang_isRestrictQualifiedType
1724Type_is_restrict_qualified.argtypes = [Type]
1725Type_is_restrict_qualified.restype = bool
1726
1727Type_get_pointee = lib.clang_getPointeeType
1728Type_get_pointee.argtypes = [Type]
1729Type_get_pointee.restype = Type
1730Type_get_pointee.errcheck = Type.from_result
1731
1732Type_get_declaration = lib.clang_getTypeDeclaration
1733Type_get_declaration.argtypes = [Type]
1734Type_get_declaration.restype = Cursor
1735Type_get_declaration.errcheck = Cursor.from_result
1736
1737Type_get_result = lib.clang_getResultType
1738Type_get_result.argtypes = [Type]
1739Type_get_result.restype = Type
1740Type_get_result.errcheck = Type.from_result
1741
1742Type_get_array_element = lib.clang_getArrayElementType
1743Type_get_array_element.argtypes = [Type]
1744Type_get_array_element.restype = Type
1745Type_get_array_element.errcheck = Type.from_result
1746
1747Type_get_array_size = lib.clang_getArraySize
1748Type_get_array_size.argtype = [Type]
1749Type_get_array_size.restype = c_longlong
1750
1751# Index Functions
1752Index_create = lib.clang_createIndex
1753Index_create.argtypes = [c_int, c_int]
1754Index_create.restype = c_object_p
1755
1756Index_dispose = lib.clang_disposeIndex
1757Index_dispose.argtypes = [Index]
1758
1759# Translation Unit Functions
1760TranslationUnit_read = lib.clang_createTranslationUnit
1761TranslationUnit_read.argtypes = [Index, c_char_p]
1762TranslationUnit_read.restype = c_object_p
1763
1764TranslationUnit_parse = lib.clang_parseTranslationUnit
1765TranslationUnit_parse.argtypes = [Index, c_char_p, c_void_p,
1766                                  c_int, c_void_p, c_int, c_int]
1767TranslationUnit_parse.restype = c_object_p
1768
1769TranslationUnit_reparse = lib.clang_reparseTranslationUnit
1770TranslationUnit_reparse.argtypes = [TranslationUnit, c_int, c_void_p, c_int]
1771TranslationUnit_reparse.restype = c_int
1772
1773TranslationUnit_codeComplete = lib.clang_codeCompleteAt
1774TranslationUnit_codeComplete.argtypes = [TranslationUnit, c_char_p, c_int,
1775                                         c_int, c_void_p, c_int, c_int]
1776TranslationUnit_codeComplete.restype = POINTER(CCRStructure)
1777
1778TranslationUnit_cursor = lib.clang_getTranslationUnitCursor
1779TranslationUnit_cursor.argtypes = [TranslationUnit]
1780TranslationUnit_cursor.restype = Cursor
1781TranslationUnit_cursor.errcheck = Cursor.from_result
1782
1783TranslationUnit_spelling = lib.clang_getTranslationUnitSpelling
1784TranslationUnit_spelling.argtypes = [TranslationUnit]
1785TranslationUnit_spelling.restype = _CXString
1786TranslationUnit_spelling.errcheck = _CXString.from_result
1787
1788TranslationUnit_dispose = lib.clang_disposeTranslationUnit
1789TranslationUnit_dispose.argtypes = [TranslationUnit]
1790
1791TranslationUnit_includes_callback = CFUNCTYPE(None,
1792                                              c_object_p,
1793                                              POINTER(SourceLocation),
1794                                              c_uint, py_object)
1795TranslationUnit_includes = lib.clang_getInclusions
1796TranslationUnit_includes.argtypes = [TranslationUnit,
1797                                     TranslationUnit_includes_callback,
1798                                     py_object]
1799
1800# File Functions
1801File_getFile = lib.clang_getFile
1802File_getFile.argtypes = [TranslationUnit, c_char_p]
1803File_getFile.restype = c_object_p
1804
1805File_name = lib.clang_getFileName
1806File_name.argtypes = [File]
1807File_name.restype = _CXString
1808
1809File_time = lib.clang_getFileTime
1810File_time.argtypes = [File]
1811File_time.restype = c_uint
1812
1813# Code completion
1814
1815CodeCompletionResults_dispose = lib.clang_disposeCodeCompleteResults
1816CodeCompletionResults_dispose.argtypes = [CodeCompletionResults]
1817
1818_clang_codeCompleteGetNumDiagnostics = lib.clang_codeCompleteGetNumDiagnostics
1819_clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults]
1820_clang_codeCompleteGetNumDiagnostics.restype = c_int
1821
1822_clang_codeCompleteGetDiagnostic = lib.clang_codeCompleteGetDiagnostic
1823_clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults, c_int]
1824_clang_codeCompleteGetDiagnostic.restype = Diagnostic
1825
1826_clang_getCompletionChunkText = lib.clang_getCompletionChunkText
1827_clang_getCompletionChunkText.argtypes = [c_void_p, c_int]
1828_clang_getCompletionChunkText.restype = _CXString
1829
1830_clang_getCompletionChunkKind = lib.clang_getCompletionChunkKind
1831_clang_getCompletionChunkKind.argtypes = [c_void_p, c_int]
1832_clang_getCompletionChunkKind.restype = c_int
1833
1834_clang_getCompletionChunkCompletionString = lib.clang_getCompletionChunkCompletionString
1835_clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int]
1836_clang_getCompletionChunkCompletionString.restype = c_object_p
1837
1838_clang_getNumCompletionChunks = lib.clang_getNumCompletionChunks
1839_clang_getNumCompletionChunks.argtypes = [c_void_p]
1840_clang_getNumCompletionChunks.restype = c_int
1841
1842_clang_getCompletionAvailability = lib.clang_getCompletionAvailability
1843_clang_getCompletionAvailability.argtypes = [c_void_p]
1844_clang_getCompletionAvailability.restype = c_int
1845
1846_clang_getCompletionPriority = lib.clang_getCompletionPriority
1847_clang_getCompletionPriority.argtypes = [c_void_p]
1848_clang_getCompletionPriority.restype = c_int
1849
1850
1851###
1852
1853__all__ = ['Index', 'TranslationUnit', 'Cursor', 'CursorKind', 'Type', 'TypeKind',
1854           'Diagnostic', 'FixIt', 'CodeCompletionResults', 'SourceRange',
1855           'SourceLocation', 'File']
1856