blob: 1bc7d0bae9d4264b9da3f3008dad6102517389a5 [file] [log] [blame]
Daniel Dunbar4efd6322010-01-25 00:43:08 +00001#===- 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#
Daniel Dunbar532fc632010-01-30 23:59:02 +000051# 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#
Daniel Dunbar4efd6322010-01-25 00:43:08 +000055# 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.
Daniel Dunbar30c0f262010-01-24 02:02:07 +000064
65from ctypes import *
Gregory Szorc826fce52012-02-20 17:45:30 +000066import collections
Daniel Dunbar30c0f262010-01-24 02:02:07 +000067
68def get_cindex_library():
69 # FIXME: It's probably not the case that the library is actually found in
70 # this location. We need a better system of identifying and loading the
71 # CIndex library. It could be on path or elsewhere, or versioned, etc.
72 import platform
73 name = platform.system()
74 if name == 'Darwin':
Daniel Dunbarf51f20f2010-04-30 21:51:10 +000075 return cdll.LoadLibrary('libclang.dylib')
Daniel Dunbar30c0f262010-01-24 02:02:07 +000076 elif name == 'Windows':
Daniel Dunbarf51f20f2010-04-30 21:51:10 +000077 return cdll.LoadLibrary('libclang.dll')
Daniel Dunbar30c0f262010-01-24 02:02:07 +000078 else:
Daniel Dunbarf51f20f2010-04-30 21:51:10 +000079 return cdll.LoadLibrary('libclang.so')
Daniel Dunbar12bf15c2010-01-24 21:20:29 +000080
Daniel Dunbar30c0f262010-01-24 02:02:07 +000081# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
82# object. This is a problem, because it means that from_parameter will see an
83# integer and pass the wrong value on platforms where int != void*. Work around
84# this by marshalling object arguments as void**.
85c_object_p = POINTER(c_void_p)
86
87lib = get_cindex_library()
Gregory Szorc9537e202012-07-12 04:56:46 +000088callbacks = {}
Daniel Dunbar30c0f262010-01-24 02:02:07 +000089
Gregory Szorcfbf620b2012-05-08 05:56:38 +000090### Exception Classes ###
91
92class TranslationUnitLoadError(Exception):
93 """Represents an error that occurred when loading a TranslationUnit.
94
95 This is raised in the case where a TranslationUnit could not be
96 instantiated due to failure in the libclang library.
97
98 FIXME: Make libclang expose additional error information in this scenario.
99 """
100 pass
101
102class TranslationUnitSaveError(Exception):
103 """Represents an error that occurred when saving a TranslationUnit.
104
105 Each error has associated with it an enumerated value, accessible under
106 e.save_error. Consumers can compare the value with one of the ERROR_
107 constants in this class.
108 """
109
110 # Indicates that an unknown error occurred. This typically indicates that
111 # I/O failed during save.
112 ERROR_UNKNOWN = 1
113
114 # Indicates that errors during translation prevented saving. The errors
115 # should be available via the TranslationUnit's diagnostics.
116 ERROR_TRANSLATION_ERRORS = 2
117
118 # Indicates that the translation unit was somehow invalid.
119 ERROR_INVALID_TU = 3
120
121 def __init__(self, enumeration, message):
122 assert isinstance(enumeration, int)
123
124 if enumeration < 1 or enumeration > 3:
125 raise Exception("Encountered undefined TranslationUnit save error "
126 "constant: %d. Please file a bug to have this "
127 "value supported." % enumeration)
128
129 self.save_error = enumeration
Gregory Szorc2283b462012-05-12 20:49:13 +0000130 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
Gregory Szorcfbf620b2012-05-08 05:56:38 +0000131
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000132### Structures and Utility Classes ###
133
Daniel Dunbara33dca42010-01-24 21:19:57 +0000134class _CXString(Structure):
135 """Helper for transforming CXString results."""
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000136
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000137 _fields_ = [("spelling", c_char_p), ("free", c_int)]
138
139 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000140 lib.clang_disposeString(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000141
Daniel Dunbara33dca42010-01-24 21:19:57 +0000142 @staticmethod
143 def from_result(res, fn, args):
144 assert isinstance(res, _CXString)
Gregory Szorc9537e202012-07-12 04:56:46 +0000145 return lib.clang_getCString(res)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000146
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000147class SourceLocation(Structure):
148 """
Daniel Dunbar149f38a2010-01-24 04:09:58 +0000149 A SourceLocation represents a particular location within a source file.
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000150 """
Daniel Dunbare32af422010-01-30 23:58:50 +0000151 _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
Daniel Dunbarf8690832010-01-24 21:20:21 +0000152 _data = None
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000153
Daniel Dunbarf8690832010-01-24 21:20:21 +0000154 def _get_instantiation(self):
155 if self._data is None:
Daniel Dunbar3239a672010-01-29 17:02:32 +0000156 f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
Gregory Szorc9537e202012-07-12 04:56:46 +0000157 lib.clang_getInstantiationLocation(self, byref(f), byref(l),
158 byref(c), byref(o))
Tobias Grosser81982882011-10-31 00:49:07 +0000159 if f:
160 f = File(f)
161 else:
162 f = None
Argyrios Kyrtzidis6b046232011-08-17 17:20:24 +0000163 self._data = (f, int(l.value), int(c.value), int(o.value))
Daniel Dunbarf8690832010-01-24 21:20:21 +0000164 return self._data
165
Tobias Grosser58ba8c92011-10-31 00:31:32 +0000166 @staticmethod
167 def from_position(tu, file, line, column):
168 """
169 Retrieve the source location associated with a given file/line/column in
170 a particular translation unit.
171 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000172 return lib.clang_getLocation(tu, file, line, column)
Tobias Grosser58ba8c92011-10-31 00:31:32 +0000173
Gregory Szorc74bb7102012-06-11 11:11:48 +0000174 @staticmethod
175 def from_offset(tu, file, offset):
176 """Retrieve a SourceLocation from a given character offset.
177
178 tu -- TranslationUnit file belongs to
179 file -- File instance to obtain offset from
180 offset -- Integer character offset within file
181 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000182 return lib.clang_getLocationForOffset(tu, file, offset)
Gregory Szorc74bb7102012-06-11 11:11:48 +0000183
Daniel Dunbarf8690832010-01-24 21:20:21 +0000184 @property
185 def file(self):
186 """Get the file represented by this source location."""
187 return self._get_instantiation()[0]
188
189 @property
190 def line(self):
191 """Get the line represented by this source location."""
192 return self._get_instantiation()[1]
193
194 @property
195 def column(self):
196 """Get the column represented by this source location."""
197 return self._get_instantiation()[2]
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000198
Daniel Dunbar3239a672010-01-29 17:02:32 +0000199 @property
200 def offset(self):
201 """Get the file offset represented by this source location."""
202 return self._get_instantiation()[3]
203
Tobias Grosser74858332012-02-05 11:40:59 +0000204 def __eq__(self, other):
Gregory Szorc9537e202012-07-12 04:56:46 +0000205 return lib.clang_equalLocations(self, other)
Tobias Grosser74858332012-02-05 11:40:59 +0000206
207 def __ne__(self, other):
208 return not self.__eq__(other)
209
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000210 def __repr__(self):
Tobias Grosser81982882011-10-31 00:49:07 +0000211 if self.file:
212 filename = self.file.name
213 else:
214 filename = None
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000215 return "<SourceLocation file %r, line %r, column %r>" % (
Tobias Grosser81982882011-10-31 00:49:07 +0000216 filename, self.line, self.column)
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000217
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000218class SourceRange(Structure):
219 """
220 A SourceRange describes a range of source locations within the source
221 code.
222 """
223 _fields_ = [
Daniel Dunbare32af422010-01-30 23:58:50 +0000224 ("ptr_data", c_void_p * 2),
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000225 ("begin_int_data", c_uint),
226 ("end_int_data", c_uint)]
227
Daniel Dunbar532fc632010-01-30 23:59:02 +0000228 # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
229 # object.
230 @staticmethod
231 def from_locations(start, end):
Gregory Szorc9537e202012-07-12 04:56:46 +0000232 return lib.clang_getRange(start, end)
Daniel Dunbar532fc632010-01-30 23:59:02 +0000233
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000234 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000235 def start(self):
236 """
237 Return a SourceLocation representing the first character within a
238 source range.
239 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000240 return lib.clang_getRangeStart(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000241
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000242 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000243 def end(self):
244 """
245 Return a SourceLocation representing the last character within a
246 source range.
247 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000248 return lib.clang_getRangeEnd(self)
Daniel Dunbarf8690832010-01-24 21:20:21 +0000249
Tobias Grosser74858332012-02-05 11:40:59 +0000250 def __eq__(self, other):
Gregory Szorc9537e202012-07-12 04:56:46 +0000251 return lib.clang_equalRanges(self, other)
Tobias Grosser74858332012-02-05 11:40:59 +0000252
253 def __ne__(self, other):
254 return not self.__eq__(other)
255
Daniel Dunbarf8690832010-01-24 21:20:21 +0000256 def __repr__(self):
257 return "<SourceRange start %r, end %r>" % (self.start, self.end)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000258
Daniel Dunbar532fc632010-01-30 23:59:02 +0000259class Diagnostic(object):
260 """
261 A Diagnostic is a single instance of a Clang diagnostic. It includes the
262 diagnostic severity, the message, the location the diagnostic occurred, as
263 well as additional source ranges and associated fix-it hints.
264 """
265
266 Ignored = 0
267 Note = 1
268 Warning = 2
269 Error = 3
270 Fatal = 4
271
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000272 def __init__(self, ptr):
273 self.ptr = ptr
274
275 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000276 lib.clang_disposeDiagnostic(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000277
278 @property
279 def severity(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000280 return lib.clang_getDiagnosticSeverity(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000281
282 @property
283 def location(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000284 return lib.clang_getDiagnosticLocation(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000285
286 @property
287 def spelling(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000288 return lib.clang_getDiagnosticSpelling(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000289
290 @property
291 def ranges(self):
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000292 class RangeIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000293 def __init__(self, diag):
294 self.diag = diag
295
296 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000297 return int(lib.clang_getDiagnosticNumRanges(self.diag))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000298
299 def __getitem__(self, key):
Tobias Grosserba5d10b2011-10-31 02:06:50 +0000300 if (key >= len(self)):
301 raise IndexError
Gregory Szorc9537e202012-07-12 04:56:46 +0000302 return lib.clang_getDiagnosticRange(self.diag, key)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000303
Tobias Grosserff090ca2011-02-05 17:53:48 +0000304 return RangeIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000305
306 @property
307 def fixits(self):
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000308 class FixItIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000309 def __init__(self, diag):
310 self.diag = diag
311
312 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000313 return int(lib.clang_getDiagnosticNumFixIts(self.diag))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000314
315 def __getitem__(self, key):
316 range = SourceRange()
Gregory Szorc9537e202012-07-12 04:56:46 +0000317 value = lib.clang_getDiagnosticFixIt(self.diag, key,
318 byref(range))
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000319 if len(value) == 0:
320 raise IndexError
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000321
322 return FixIt(range, value)
323
Tobias Grosserff090ca2011-02-05 17:53:48 +0000324 return FixItIterator(self)
Daniel Dunbar532fc632010-01-30 23:59:02 +0000325
Tobias Grosserea403822012-02-05 11:41:58 +0000326 @property
327 def category_number(self):
328 """The category number for this diagnostic."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000329 return lib.clang_getDiagnosticCategory(self)
Tobias Grosserea403822012-02-05 11:41:58 +0000330
331 @property
332 def category_name(self):
333 """The string name of the category for this diagnostic."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000334 return lib.clang_getDiagnosticCategoryName(self.category_number)
Tobias Grosserea403822012-02-05 11:41:58 +0000335
336 @property
337 def option(self):
338 """The command-line option that enables this diagnostic."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000339 return lib.clang_getDiagnosticOption(self, None)
Tobias Grosserea403822012-02-05 11:41:58 +0000340
341 @property
342 def disable_option(self):
343 """The command-line option that disables this diagnostic."""
344 disable = _CXString()
Gregory Szorc9537e202012-07-12 04:56:46 +0000345 lib.clang_getDiagnosticOption(self, byref(disable))
Tobias Grosserea403822012-02-05 11:41:58 +0000346
Gregory Szorc9537e202012-07-12 04:56:46 +0000347 return lib.clang_getCString(disable)
Tobias Grosserea403822012-02-05 11:41:58 +0000348
Daniel Dunbar532fc632010-01-30 23:59:02 +0000349 def __repr__(self):
350 return "<Diagnostic severity %r, location %r, spelling %r>" % (
351 self.severity, self.location, self.spelling)
352
Tobias Grosserff090ca2011-02-05 17:53:48 +0000353 def from_param(self):
354 return self.ptr
355
Daniel Dunbar532fc632010-01-30 23:59:02 +0000356class FixIt(object):
357 """
358 A FixIt represents a transformation to be applied to the source to
359 "fix-it". The fix-it shouldbe applied by replacing the given source range
360 with the given value.
361 """
362
363 def __init__(self, range, value):
364 self.range = range
365 self.value = value
366
367 def __repr__(self):
368 return "<FixIt range %r, value %r>" % (self.range, self.value)
369
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000370### Cursor Kinds ###
371
372class CursorKind(object):
373 """
374 A CursorKind describes the kind of entity that a cursor points to.
375 """
376
377 # The unique kind objects, indexed by id.
378 _kinds = []
379 _name_map = None
380
381 def __init__(self, value):
382 if value >= len(CursorKind._kinds):
383 CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1)
384 if CursorKind._kinds[value] is not None:
385 raise ValueError,'CursorKind already loaded'
386 self.value = value
387 CursorKind._kinds[value] = self
388 CursorKind._name_map = None
389
390 def from_param(self):
391 return self.value
392
393 @property
394 def name(self):
395 """Get the enumeration name of this cursor kind."""
396 if self._name_map is None:
397 self._name_map = {}
398 for key,value in CursorKind.__dict__.items():
399 if isinstance(value,CursorKind):
400 self._name_map[value] = key
401 return self._name_map[self]
402
403 @staticmethod
404 def from_id(id):
405 if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None:
406 raise ValueError,'Unknown cursor kind'
407 return CursorKind._kinds[id]
408
Daniel Dunbara6a64992010-01-24 21:20:39 +0000409 @staticmethod
410 def get_all_kinds():
Daniel Dunbar4efd6322010-01-25 00:43:08 +0000411 """Return all CursorKind enumeration instances."""
Daniel Dunbara6a64992010-01-24 21:20:39 +0000412 return filter(None, CursorKind._kinds)
413
414 def is_declaration(self):
415 """Test if this is a declaration kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000416 return lib.clang_isDeclaration(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000417
418 def is_reference(self):
419 """Test if this is a reference kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000420 return lib.clang_isReference(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000421
422 def is_expression(self):
423 """Test if this is an expression kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000424 return lib.clang_isExpression(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000425
426 def is_statement(self):
427 """Test if this is a statement kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000428 return lib.clang_isStatement(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000429
Douglas Gregor8be80e12011-07-06 03:00:34 +0000430 def is_attribute(self):
431 """Test if this is an attribute kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000432 return lib.clang_isAttribute(self)
Douglas Gregor8be80e12011-07-06 03:00:34 +0000433
Daniel Dunbara6a64992010-01-24 21:20:39 +0000434 def is_invalid(self):
435 """Test if this is an invalid kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000436 return lib.clang_isInvalid(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000437
Tobias Grossereb136342012-02-05 11:42:09 +0000438 def is_translation_unit(self):
439 """Test if this is a translation unit kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000440 return lib.clang_isTranslationUnit(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000441
442 def is_preprocessing(self):
443 """Test if this is a preprocessing kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000444 return lib.clang_isPreprocessing(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000445
446 def is_unexposed(self):
447 """Test if this is an unexposed kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000448 return lib.clang_isUnexposed(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000449
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000450 def __repr__(self):
451 return 'CursorKind.%s' % (self.name,)
452
453# FIXME: Is there a nicer way to expose this enumeration? We could potentially
454# represent the nested structure, or even build a class hierarchy. The main
455# things we want for sure are (a) simple external access to kinds, (b) a place
456# to hang a description and name, (c) easy to keep in sync with Index.h.
457
Daniel Dunbara6a64992010-01-24 21:20:39 +0000458###
459# Declaration Kinds
460
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000461# A declaration whose specific kind is not exposed via this interface.
462#
463# Unexposed declarations have the same operations as any other kind of
464# declaration; one can extract their location information, spelling, find their
465# definitions, etc. However, the specific kind of the declaration is not
466# reported.
467CursorKind.UNEXPOSED_DECL = CursorKind(1)
468
469# A C or C++ struct.
470CursorKind.STRUCT_DECL = CursorKind(2)
471
472# A C or C++ union.
473CursorKind.UNION_DECL = CursorKind(3)
474
475# A C++ class.
476CursorKind.CLASS_DECL = CursorKind(4)
477
478# An enumeration.
479CursorKind.ENUM_DECL = CursorKind(5)
480
481# A field (in C) or non-static data member (in C++) in a struct, union, or C++
482# class.
483CursorKind.FIELD_DECL = CursorKind(6)
484
485# An enumerator constant.
486CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
487
488# A function.
489CursorKind.FUNCTION_DECL = CursorKind(8)
490
491# A variable.
492CursorKind.VAR_DECL = CursorKind(9)
493
494# A function or method parameter.
495CursorKind.PARM_DECL = CursorKind(10)
496
497# An Objective-C @interface.
498CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
499
500# An Objective-C @interface for a category.
501CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
502
503# An Objective-C @protocol declaration.
504CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
505
506# An Objective-C @property declaration.
507CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
508
509# An Objective-C instance variable.
510CursorKind.OBJC_IVAR_DECL = CursorKind(15)
511
512# An Objective-C instance method.
513CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
514
515# An Objective-C class method.
516CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
517
518# An Objective-C @implementation.
519CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
520
521# An Objective-C @implementation for a category.
522CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
523
Daniel Dunbara6a64992010-01-24 21:20:39 +0000524# A typedef.
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000525CursorKind.TYPEDEF_DECL = CursorKind(20)
526
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000527# A C++ class method.
528CursorKind.CXX_METHOD = CursorKind(21)
529
530# A C++ namespace.
531CursorKind.NAMESPACE = CursorKind(22)
532
533# A linkage specification, e.g. 'extern "C"'.
534CursorKind.LINKAGE_SPEC = CursorKind(23)
535
536# A C++ constructor.
537CursorKind.CONSTRUCTOR = CursorKind(24)
538
539# A C++ destructor.
540CursorKind.DESTRUCTOR = CursorKind(25)
541
542# A C++ conversion function.
543CursorKind.CONVERSION_FUNCTION = CursorKind(26)
544
545# A C++ template type parameter
546CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
547
548# A C++ non-type template paramater.
549CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
550
551# A C++ template template parameter.
552CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29)
553
554# A C++ function template.
555CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
556
557# A C++ class template.
558CursorKind.CLASS_TEMPLATE = CursorKind(31)
559
560# A C++ class template partial specialization.
561CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
562
563# A C++ namespace alias declaration.
564CursorKind.NAMESPACE_ALIAS = CursorKind(33)
565
566# A C++ using directive
567CursorKind.USING_DIRECTIVE = CursorKind(34)
568
569# A C++ using declaration
570CursorKind.USING_DECLARATION = CursorKind(35)
571
Douglas Gregor42b29842011-10-05 19:00:14 +0000572# A Type alias decl.
573CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
574
575# A Objective-C synthesize decl
576CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
577
578# A Objective-C dynamic decl
579CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
580
581# A C++ access specifier decl.
582CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
583
584
Daniel Dunbara6a64992010-01-24 21:20:39 +0000585###
586# Reference Kinds
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000587
588CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
589CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
590CursorKind.OBJC_CLASS_REF = CursorKind(42)
591
592# A reference to a type declaration.
593#
594# A type reference occurs anywhere where a type is named but not
595# declared. For example, given:
596# typedef unsigned size_type;
597# size_type size;
598#
599# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
600# while the type of the variable "size" is referenced. The cursor
601# referenced by the type of size is the typedef for size_type.
602CursorKind.TYPE_REF = CursorKind(43)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000603CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
604
605# A reference to a class template, function template, template
606# template parameter, or class template partial specialization.
607CursorKind.TEMPLATE_REF = CursorKind(45)
608
609# A reference to a namespace or namepsace alias.
610CursorKind.NAMESPACE_REF = CursorKind(46)
611
612# A reference to a member of a struct, union, or class that occurs in
613# some non-expression context, e.g., a designated initializer.
614CursorKind.MEMBER_REF = CursorKind(47)
615
616# A reference to a labeled statement.
617CursorKind.LABEL_REF = CursorKind(48)
618
619# A reference toa a set of overloaded functions or function templates
620# that has not yet been resolved to a specific function or function template.
621CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000622
Daniel Dunbara6a64992010-01-24 21:20:39 +0000623###
624# Invalid/Error Kinds
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000625
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000626CursorKind.INVALID_FILE = CursorKind(70)
627CursorKind.NO_DECL_FOUND = CursorKind(71)
628CursorKind.NOT_IMPLEMENTED = CursorKind(72)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000629CursorKind.INVALID_CODE = CursorKind(73)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000630
Daniel Dunbara6a64992010-01-24 21:20:39 +0000631###
632# Expression Kinds
633
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000634# An expression whose specific kind is not exposed via this interface.
635#
636# Unexposed expressions have the same operations as any other kind of
637# expression; one can extract their location information, spelling, children,
638# etc. However, the specific kind of the expression is not reported.
639CursorKind.UNEXPOSED_EXPR = CursorKind(100)
640
641# An expression that refers to some value declaration, such as a function,
642# varible, or enumerator.
643CursorKind.DECL_REF_EXPR = CursorKind(101)
644
645# An expression that refers to a member of a struct, union, class, Objective-C
646# class, etc.
647CursorKind.MEMBER_REF_EXPR = CursorKind(102)
648
649# An expression that calls a function.
650CursorKind.CALL_EXPR = CursorKind(103)
651
652# An expression that sends a message to an Objective-C object or class.
653CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
654
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000655# An expression that represents a block literal.
656CursorKind.BLOCK_EXPR = CursorKind(105)
657
Douglas Gregor42b29842011-10-05 19:00:14 +0000658# An integer literal.
659CursorKind.INTEGER_LITERAL = CursorKind(106)
660
661# A floating point number literal.
662CursorKind.FLOATING_LITERAL = CursorKind(107)
663
664# An imaginary number literal.
665CursorKind.IMAGINARY_LITERAL = CursorKind(108)
666
667# A string literal.
668CursorKind.STRING_LITERAL = CursorKind(109)
669
670# A character literal.
671CursorKind.CHARACTER_LITERAL = CursorKind(110)
672
673# A parenthesized expression, e.g. "(1)".
674#
675# This AST node is only formed if full location information is requested.
676CursorKind.PAREN_EXPR = CursorKind(111)
677
678# This represents the unary-expression's (except sizeof and
679# alignof).
680CursorKind.UNARY_OPERATOR = CursorKind(112)
681
682# [C99 6.5.2.1] Array Subscripting.
683CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
684
685# A builtin binary operation expression such as "x + y" or
686# "x <= y".
687CursorKind.BINARY_OPERATOR = CursorKind(114)
688
689# Compound assignment such as "+=".
690CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
691
692# The ?: ternary operator.
Douglas Gregor39a03d12012-06-08 00:16:27 +0000693CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
Douglas Gregor42b29842011-10-05 19:00:14 +0000694
695# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
696# (C++ [expr.cast]), which uses the syntax (Type)expr.
697#
698# For example: (int)f.
699CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
700
701# [C99 6.5.2.5]
702CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
703
704# Describes an C or C++ initializer list.
705CursorKind.INIT_LIST_EXPR = CursorKind(119)
706
707# The GNU address of label extension, representing &&label.
708CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
709
710# This is the GNU Statement Expression extension: ({int X=4; X;})
711CursorKind.StmtExpr = CursorKind(121)
712
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000713# Represents a C11 generic selection.
Douglas Gregor42b29842011-10-05 19:00:14 +0000714CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
715
716# Implements the GNU __null extension, which is a name for a null
717# pointer constant that has integral type (e.g., int or long) and is the same
718# size and alignment as a pointer.
719#
720# The __null extension is typically only used by system headers, which define
721# NULL as __null in C++ rather than using 0 (which is an integer that may not
722# match the size of a pointer).
723CursorKind.GNU_NULL_EXPR = CursorKind(123)
724
725# C++'s static_cast<> expression.
726CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
727
728# C++'s dynamic_cast<> expression.
729CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
730
731# C++'s reinterpret_cast<> expression.
732CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
733
734# C++'s const_cast<> expression.
735CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
736
737# Represents an explicit C++ type conversion that uses "functional"
738# notion (C++ [expr.type.conv]).
739#
740# Example:
741# \code
742# x = int(0.5);
743# \endcode
744CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
745
746# A C++ typeid expression (C++ [expr.typeid]).
747CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
748
749# [C++ 2.13.5] C++ Boolean Literal.
750CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
751
752# [C++0x 2.14.7] C++ Pointer Literal.
753CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
754
755# Represents the "this" expression in C++
756CursorKind.CXX_THIS_EXPR = CursorKind(132)
757
758# [C++ 15] C++ Throw Expression.
759#
760# This handles 'throw' and 'throw' assignment-expression. When
761# assignment-expression isn't present, Op will be null.
762CursorKind.CXX_THROW_EXPR = CursorKind(133)
763
764# A new expression for memory allocation and constructor calls, e.g:
765# "new CXXNewExpr(foo)".
766CursorKind.CXX_NEW_EXPR = CursorKind(134)
767
768# A delete expression for memory deallocation and destructor calls,
769# e.g. "delete[] pArray".
770CursorKind.CXX_DELETE_EXPR = CursorKind(135)
771
772# Represents a unary expression.
773CursorKind.CXX_UNARY_EXPR = CursorKind(136)
774
775# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
776CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
777
778# ObjCEncodeExpr, used for in Objective-C.
779CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
780
781# ObjCSelectorExpr used for in Objective-C.
782CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
783
784# Objective-C's protocol expression.
785CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
786
787# An Objective-C "bridged" cast expression, which casts between
788# Objective-C pointers and C pointers, transferring ownership in the process.
789#
790# \code
791# NSString *str = (__bridge_transfer NSString *)CFCreateString();
792# \endcode
793CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
794
795# Represents a C++0x pack expansion that produces a sequence of
796# expressions.
797#
798# A pack expansion expression contains a pattern (which itself is an
799# expression) followed by an ellipsis. For example:
800CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
801
802# Represents an expression that computes the length of a parameter
803# pack.
804CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
805
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000806# A statement whose specific kind is not exposed via this interface.
807#
808# Unexposed statements have the same operations as any other kind of statement;
809# one can extract their location information, spelling, children, etc. However,
810# the specific kind of the statement is not reported.
811CursorKind.UNEXPOSED_STMT = CursorKind(200)
812
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000813# A labelled statement in a function.
814CursorKind.LABEL_STMT = CursorKind(201)
815
Douglas Gregor42b29842011-10-05 19:00:14 +0000816# A compound statement
817CursorKind.COMPOUND_STMT = CursorKind(202)
818
819# A case statement.
820CursorKind.CASE_STMT = CursorKind(203)
821
822# A default statement.
823CursorKind.DEFAULT_STMT = CursorKind(204)
824
825# An if statement.
826CursorKind.IF_STMT = CursorKind(205)
827
828# A switch statement.
829CursorKind.SWITCH_STMT = CursorKind(206)
830
831# A while statement.
832CursorKind.WHILE_STMT = CursorKind(207)
833
834# A do statement.
835CursorKind.DO_STMT = CursorKind(208)
836
837# A for statement.
838CursorKind.FOR_STMT = CursorKind(209)
839
840# A goto statement.
841CursorKind.GOTO_STMT = CursorKind(210)
842
843# An indirect goto statement.
844CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
845
846# A continue statement.
847CursorKind.CONTINUE_STMT = CursorKind(212)
848
849# A break statement.
850CursorKind.BREAK_STMT = CursorKind(213)
851
852# A return statement.
853CursorKind.RETURN_STMT = CursorKind(214)
854
855# A GNU-style inline assembler statement.
856CursorKind.ASM_STMT = CursorKind(215)
857
858# Objective-C's overall @try-@catch-@finally statement.
859CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
860
861# Objective-C's @catch statement.
862CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
863
864# Objective-C's @finally statement.
865CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
866
867# Objective-C's @throw statement.
868CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
869
870# Objective-C's @synchronized statement.
871CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
872
873# Objective-C's autorealease pool statement.
874CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
875
876# Objective-C's for collection statement.
877CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
878
879# C++'s catch statement.
880CursorKind.CXX_CATCH_STMT = CursorKind(223)
881
882# C++'s try statement.
883CursorKind.CXX_TRY_STMT = CursorKind(224)
884
885# C++'s for (* : *) statement.
886CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
887
888# Windows Structured Exception Handling's try statement.
889CursorKind.SEH_TRY_STMT = CursorKind(226)
890
891# Windows Structured Exception Handling's except statement.
892CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
893
894# Windows Structured Exception Handling's finally statement.
895CursorKind.SEH_FINALLY_STMT = CursorKind(228)
896
897# The null statement.
898CursorKind.NULL_STMT = CursorKind(230)
899
900# Adaptor class for mixing declarations with statements and expressions.
901CursorKind.DECL_STMT = CursorKind(231)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000902
Daniel Dunbara6a64992010-01-24 21:20:39 +0000903###
904# Other Kinds
905
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000906# Cursor that represents the translation unit itself.
907#
908# The translation unit cursor exists primarily to act as the root cursor for
909# traversing the contents of a translation unit.
910CursorKind.TRANSLATION_UNIT = CursorKind(300)
911
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000912###
913# Attributes
914
915# An attribute whoe specific kind is note exposed via this interface
916CursorKind.UNEXPOSED_ATTR = CursorKind(400)
917
918CursorKind.IB_ACTION_ATTR = CursorKind(401)
919CursorKind.IB_OUTLET_ATTR = CursorKind(402)
920CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
921
Rafael Espindolabf3cc732011-12-30 15:27:22 +0000922CursorKind.CXX_FINAL_ATTR = CursorKind(404)
923CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
924CursorKind.ANNOTATE_ATTR = CursorKind(406)
925CursorKind.ASM_LABEL_ATTR = CursorKind(407)
926
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000927###
928# Preprocessing
929CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
930CursorKind.MACRO_DEFINITION = CursorKind(501)
931CursorKind.MACRO_INSTANTIATION = CursorKind(502)
932CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
933
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000934### Cursors ###
935
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000936class Cursor(Structure):
937 """
938 The Cursor class represents a reference to an element within the AST. It
939 acts as a kind of iterator.
940 """
Douglas Gregor2abfec32011-10-19 05:47:46 +0000941 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000942
Tobias Grosser58ba8c92011-10-31 00:31:32 +0000943 @staticmethod
944 def from_location(tu, location):
Gregory Szorca63ef1f2012-05-15 19:51:02 +0000945 # We store a reference to the TU in the instance so the TU won't get
946 # collected before the cursor.
Gregory Szorc9537e202012-07-12 04:56:46 +0000947 cursor = lib.clang_getCursor(tu, location)
Gregory Szorca63ef1f2012-05-15 19:51:02 +0000948 cursor._tu = tu
949
950 return cursor
Tobias Grosser58ba8c92011-10-31 00:31:32 +0000951
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000952 def __eq__(self, other):
Gregory Szorc9537e202012-07-12 04:56:46 +0000953 return lib.clang_equalCursors(self, other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000954
955 def __ne__(self, other):
Gregory Szorc9d008fd2012-03-05 00:42:15 +0000956 return not self.__eq__(other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000957
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000958 def is_definition(self):
959 """
960 Returns true if the declaration pointed at by the cursor is also a
961 definition of that entity.
962 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000963 return lib.clang_isCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000964
Gregory Szorce65b34d2012-06-09 16:21:34 +0000965 def is_static_method(self):
966 """Returns True if the cursor refers to a C++ member function or member
967 function template that is declared 'static'.
968 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000969 return lib.clang_CXXMethod_isStatic(self)
Gregory Szorce65b34d2012-06-09 16:21:34 +0000970
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000971 def get_definition(self):
972 """
973 If the cursor is a reference to a declaration or a declaration of
974 some entity, return a cursor that points to the definition of that
975 entity.
976 """
977 # TODO: Should probably check that this is either a reference or
978 # declaration prior to issuing the lookup.
Gregory Szorc9537e202012-07-12 04:56:46 +0000979 return lib.clang_getCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000980
Daniel Dunbar3d855f82010-01-24 21:20:13 +0000981 def get_usr(self):
982 """Return the Unified Symbol Resultion (USR) for the entity referenced
983 by the given cursor (or None).
984
985 A Unified Symbol Resolution (USR) is a string that identifies a
986 particular entity (function, class, variable, etc.) within a
987 program. USRs can be compared across translation units to determine,
988 e.g., when references in one translation refer to an entity defined in
989 another translation unit."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000990 return lib.clang_getCursorUSR(self)
Daniel Dunbar3d855f82010-01-24 21:20:13 +0000991
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000992 @property
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000993 def kind(self):
994 """Return the kind of this cursor."""
995 return CursorKind.from_id(self._kind_id)
996
997 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000998 def spelling(self):
999 """Return the spelling of the entity pointed at by the cursor."""
Daniel Dunbara6a64992010-01-24 21:20:39 +00001000 if not self.kind.is_declaration():
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001001 # FIXME: clang_getCursorSpelling should be fixed to not assert on
1002 # this, for consistency with clang_getCursorUSR.
1003 return None
Douglas Gregor42b29842011-10-05 19:00:14 +00001004 if not hasattr(self, '_spelling'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001005 self._spelling = lib.clang_getCursorSpelling(self)
1006
Douglas Gregor42b29842011-10-05 19:00:14 +00001007 return self._spelling
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001008
1009 @property
Douglas Gregorb60a2be2011-08-30 00:15:34 +00001010 def displayname(self):
1011 """
1012 Return the display name for the entity referenced by this cursor.
1013
1014 The display name contains extra information that helps identify the cursor,
1015 such as the parameters of a function or template or the arguments of a
1016 class template specialization.
1017 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001018 if not hasattr(self, '_displayname'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001019 self._displayname = lib.clang_getCursorDisplayName(self)
1020
Douglas Gregor42b29842011-10-05 19:00:14 +00001021 return self._displayname
Douglas Gregorb60a2be2011-08-30 00:15:34 +00001022
1023 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001024 def location(self):
1025 """
1026 Return the source location (the starting character) of the entity
1027 pointed at by the cursor.
1028 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001029 if not hasattr(self, '_loc'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001030 self._loc = lib.clang_getCursorLocation(self)
1031
Douglas Gregor42b29842011-10-05 19:00:14 +00001032 return self._loc
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001033
1034 @property
1035 def extent(self):
1036 """
1037 Return the source range (the range of text) occupied by the entity
1038 pointed at by the cursor.
1039 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001040 if not hasattr(self, '_extent'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001041 self._extent = lib.clang_getCursorExtent(self)
1042
Douglas Gregor42b29842011-10-05 19:00:14 +00001043 return self._extent
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001044
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001045 @property
1046 def type(self):
1047 """
Tobias Grosser2d106802012-02-05 12:15:56 +00001048 Retrieve the Type (if any) of the entity pointed at by the cursor.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001049 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001050 if not hasattr(self, '_type'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001051 self._type = lib.clang_getCursorType(self)
1052
Douglas Gregor42b29842011-10-05 19:00:14 +00001053 return self._type
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001054
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001055 @property
Gregory Szorc2c408352012-05-14 03:56:33 +00001056 def canonical(self):
1057 """Return the canonical Cursor corresponding to this Cursor.
1058
1059 The canonical cursor is the cursor which is representative for the
1060 underlying entity. For example, if you have multiple forward
1061 declarations for the same class, the canonical cursor for the forward
1062 declarations will be identical.
1063 """
1064 if not hasattr(self, '_canonical'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001065 self._canonical = lib.clang_getCanonicalCursor(self)
Gregory Szorc2c408352012-05-14 03:56:33 +00001066
1067 return self._canonical
1068
1069 @property
Gregory Szorc1e370ab2012-05-14 03:53:29 +00001070 def result_type(self):
1071 """Retrieve the Type of the result for this Cursor."""
1072 if not hasattr(self, '_result_type'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001073 self._result_type = lib.clang_getResultType(self.type)
Gregory Szorc1e370ab2012-05-14 03:53:29 +00001074
1075 return self._result_type
1076
1077 @property
Tobias Grosser28d939f2012-02-05 11:42:20 +00001078 def underlying_typedef_type(self):
1079 """Return the underlying type of a typedef declaration.
1080
Tobias Grosser2d106802012-02-05 12:15:56 +00001081 Returns a Type for the typedef this cursor is a declaration for. If
Tobias Grosser28d939f2012-02-05 11:42:20 +00001082 the current cursor is not a typedef, this raises.
1083 """
1084 if not hasattr(self, '_underlying_type'):
1085 assert self.kind.is_declaration()
Gregory Szorc9537e202012-07-12 04:56:46 +00001086 self._underlying_type = lib.clang_getTypedefDeclUnderlyingType(self)
Tobias Grosser28d939f2012-02-05 11:42:20 +00001087
1088 return self._underlying_type
1089
1090 @property
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001091 def enum_type(self):
1092 """Return the integer type of an enum declaration.
1093
Tobias Grosser2d106802012-02-05 12:15:56 +00001094 Returns a Type corresponding to an integer. If the cursor is not for an
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001095 enum, this raises.
1096 """
1097 if not hasattr(self, '_enum_type'):
1098 assert self.kind == CursorKind.ENUM_DECL
Gregory Szorc9537e202012-07-12 04:56:46 +00001099 self._enum_type = lib.clang_getEnumDeclIntegerType(self)
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001100
1101 return self._enum_type
1102
1103 @property
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001104 def enum_value(self):
1105 """Return the value of an enum constant."""
1106 if not hasattr(self, '_enum_value'):
1107 assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1108 # Figure out the underlying type of the enum to know if it
1109 # is a signed or unsigned quantity.
1110 underlying_type = self.type
1111 if underlying_type.kind == TypeKind.ENUM:
1112 underlying_type = underlying_type.get_declaration().enum_type
1113 if underlying_type.kind in (TypeKind.CHAR_U,
1114 TypeKind.UCHAR,
1115 TypeKind.CHAR16,
1116 TypeKind.CHAR32,
1117 TypeKind.USHORT,
1118 TypeKind.UINT,
1119 TypeKind.ULONG,
1120 TypeKind.ULONGLONG,
1121 TypeKind.UINT128):
Gregory Szorc9537e202012-07-12 04:56:46 +00001122 self._enum_value = lib.clang_getEnumConstantDeclUnsignedValue(self)
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001123 else:
Gregory Szorc9537e202012-07-12 04:56:46 +00001124 self._enum_value = lib.clang_getEnumConstantDeclValue(self)
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001125 return self._enum_value
1126
1127 @property
Gregory Szorc5cc67872012-03-10 22:23:27 +00001128 def objc_type_encoding(self):
1129 """Return the Objective-C type encoding as a str."""
1130 if not hasattr(self, '_objc_type_encoding'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001131 self._objc_type_encoding = lib.clang_getDeclObjCTypeEncoding(self)
Gregory Szorc5cc67872012-03-10 22:23:27 +00001132
1133 return self._objc_type_encoding
1134
1135 @property
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001136 def hash(self):
1137 """Returns a hash of the cursor as an int."""
1138 if not hasattr(self, '_hash'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001139 self._hash = lib.clang_hashCursor(self)
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001140
1141 return self._hash
1142
Manuel Klimek667fd802012-05-07 05:56:03 +00001143 @property
1144 def semantic_parent(self):
1145 """Return the semantic parent for this cursor."""
1146 if not hasattr(self, '_semantic_parent'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001147 self._semantic_parent = lib.clang_getCursorSemanticParent(self)
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001148
Manuel Klimek667fd802012-05-07 05:56:03 +00001149 return self._semantic_parent
1150
1151 @property
1152 def lexical_parent(self):
1153 """Return the lexical parent for this cursor."""
1154 if not hasattr(self, '_lexical_parent'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001155 self._lexical_parent = lib.clang_getCursorLexicalParent(self)
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001156
Manuel Klimek667fd802012-05-07 05:56:03 +00001157 return self._lexical_parent
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001158
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001159 @property
1160 def translation_unit(self):
1161 """Returns the TranslationUnit to which this Cursor belongs."""
1162 # If this triggers an AttributeError, the instance was not properly
1163 # created.
1164 return self._tu
1165
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001166 def get_children(self):
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001167 """Return an iterator for accessing the children of this cursor."""
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001168
1169 # FIXME: Expose iteration from CIndex, PR6125.
1170 def visitor(child, parent, children):
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001171 # FIXME: Document this assertion in API.
1172 # FIXME: There should just be an isNull method.
Gregory Szorc9537e202012-07-12 04:56:46 +00001173 assert child != lib.clang_getNullCursor()
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001174
1175 # Create reference to TU so it isn't GC'd before Cursor.
1176 child._tu = self._tu
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001177 children.append(child)
1178 return 1 # continue
1179 children = []
Gregory Szorc9537e202012-07-12 04:56:46 +00001180 lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
1181 children)
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001182 return iter(children)
1183
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001184 @staticmethod
1185 def from_result(res, fn, args):
1186 assert isinstance(res, Cursor)
1187 # FIXME: There should just be an isNull method.
Gregory Szorc9537e202012-07-12 04:56:46 +00001188 if res == lib.clang_getNullCursor():
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001189 return None
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001190
1191 # Store a reference to the TU in the Python object so it won't get GC'd
1192 # before the Cursor.
1193 tu = None
1194 for arg in args:
1195 if isinstance(arg, TranslationUnit):
1196 tu = arg
1197 break
1198
1199 if hasattr(arg, 'translation_unit'):
1200 tu = arg.translation_unit
1201 break
1202
1203 assert tu is not None
1204
1205 res._tu = tu
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001206 return res
1207
Gregory Szorc9537e202012-07-12 04:56:46 +00001208 @staticmethod
1209 def from_cursor_result(res, fn, args):
1210 assert isinstance(res, Cursor)
1211 if res == lib.clang_getNullCursor():
1212 return None
1213
1214 res._tu = args[0]._tu
1215 return res
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001216
1217### Type Kinds ###
1218
1219class TypeKind(object):
1220 """
1221 Describes the kind of type.
1222 """
1223
1224 # The unique kind objects, indexed by id.
1225 _kinds = []
1226 _name_map = None
1227
1228 def __init__(self, value):
1229 if value >= len(TypeKind._kinds):
1230 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
1231 if TypeKind._kinds[value] is not None:
1232 raise ValueError,'TypeKind already loaded'
1233 self.value = value
1234 TypeKind._kinds[value] = self
1235 TypeKind._name_map = None
1236
1237 def from_param(self):
1238 return self.value
1239
1240 @property
1241 def name(self):
1242 """Get the enumeration name of this cursor kind."""
1243 if self._name_map is None:
1244 self._name_map = {}
1245 for key,value in TypeKind.__dict__.items():
1246 if isinstance(value,TypeKind):
1247 self._name_map[value] = key
1248 return self._name_map[self]
1249
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001250 @property
1251 def spelling(self):
1252 """Retrieve the spelling of this TypeKind."""
Gregory Szorc9537e202012-07-12 04:56:46 +00001253 return lib.clang_getTypeKindSpelling(self.value)
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001254
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001255 @staticmethod
1256 def from_id(id):
1257 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
Douglas Gregor9d342ab2011-10-19 05:49:29 +00001258 raise ValueError,'Unknown type kind %d' % id
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001259 return TypeKind._kinds[id]
1260
1261 def __repr__(self):
1262 return 'TypeKind.%s' % (self.name,)
1263
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001264TypeKind.INVALID = TypeKind(0)
1265TypeKind.UNEXPOSED = TypeKind(1)
1266TypeKind.VOID = TypeKind(2)
1267TypeKind.BOOL = TypeKind(3)
1268TypeKind.CHAR_U = TypeKind(4)
1269TypeKind.UCHAR = TypeKind(5)
1270TypeKind.CHAR16 = TypeKind(6)
1271TypeKind.CHAR32 = TypeKind(7)
1272TypeKind.USHORT = TypeKind(8)
1273TypeKind.UINT = TypeKind(9)
1274TypeKind.ULONG = TypeKind(10)
1275TypeKind.ULONGLONG = TypeKind(11)
1276TypeKind.UINT128 = TypeKind(12)
1277TypeKind.CHAR_S = TypeKind(13)
1278TypeKind.SCHAR = TypeKind(14)
1279TypeKind.WCHAR = TypeKind(15)
1280TypeKind.SHORT = TypeKind(16)
1281TypeKind.INT = TypeKind(17)
1282TypeKind.LONG = TypeKind(18)
1283TypeKind.LONGLONG = TypeKind(19)
1284TypeKind.INT128 = TypeKind(20)
1285TypeKind.FLOAT = TypeKind(21)
1286TypeKind.DOUBLE = TypeKind(22)
1287TypeKind.LONGDOUBLE = TypeKind(23)
1288TypeKind.NULLPTR = TypeKind(24)
1289TypeKind.OVERLOAD = TypeKind(25)
1290TypeKind.DEPENDENT = TypeKind(26)
1291TypeKind.OBJCID = TypeKind(27)
1292TypeKind.OBJCCLASS = TypeKind(28)
1293TypeKind.OBJCSEL = TypeKind(29)
1294TypeKind.COMPLEX = TypeKind(100)
1295TypeKind.POINTER = TypeKind(101)
1296TypeKind.BLOCKPOINTER = TypeKind(102)
1297TypeKind.LVALUEREFERENCE = TypeKind(103)
1298TypeKind.RVALUEREFERENCE = TypeKind(104)
1299TypeKind.RECORD = TypeKind(105)
1300TypeKind.ENUM = TypeKind(106)
1301TypeKind.TYPEDEF = TypeKind(107)
1302TypeKind.OBJCINTERFACE = TypeKind(108)
1303TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1304TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1305TypeKind.FUNCTIONPROTO = TypeKind(111)
Douglas Gregor38d2d552011-10-19 05:50:34 +00001306TypeKind.CONSTANTARRAY = TypeKind(112)
Tobias Grosser250d2172012-02-05 11:42:14 +00001307TypeKind.VECTOR = TypeKind(113)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001308
1309class Type(Structure):
1310 """
1311 The type of an element in the abstract syntax tree.
1312 """
1313 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1314
1315 @property
1316 def kind(self):
1317 """Return the kind of this type."""
1318 return TypeKind.from_id(self._kind_id)
1319
Gregory Szorc826fce52012-02-20 17:45:30 +00001320 def argument_types(self):
1321 """Retrieve a container for the non-variadic arguments for this type.
1322
1323 The returned object is iterable and indexable. Each item in the
1324 container is a Type instance.
1325 """
1326 class ArgumentsIterator(collections.Sequence):
1327 def __init__(self, parent):
1328 self.parent = parent
1329 self.length = None
1330
1331 def __len__(self):
1332 if self.length is None:
Gregory Szorc9537e202012-07-12 04:56:46 +00001333 self.length = lib.clang_getNumArgTypes(self.parent)
Gregory Szorc826fce52012-02-20 17:45:30 +00001334
1335 return self.length
1336
1337 def __getitem__(self, key):
1338 # FIXME Support slice objects.
1339 if not isinstance(key, int):
1340 raise TypeError("Must supply a non-negative int.")
1341
1342 if key < 0:
1343 raise IndexError("Only non-negative indexes are accepted.")
1344
1345 if key >= len(self):
1346 raise IndexError("Index greater than container length: "
1347 "%d > %d" % ( key, len(self) ))
1348
Gregory Szorc9537e202012-07-12 04:56:46 +00001349 result = lib.clang_getArgType(self.parent, key)
Gregory Szorc826fce52012-02-20 17:45:30 +00001350 if result.kind == TypeKind.INVALID:
1351 raise IndexError("Argument could not be retrieved.")
1352
1353 return result
1354
1355 assert self.kind == TypeKind.FUNCTIONPROTO
1356 return ArgumentsIterator(self)
1357
Gregory Szorc86057602012-02-17 07:44:46 +00001358 @property
1359 def element_type(self):
1360 """Retrieve the Type of elements within this Type.
1361
1362 If accessed on a type that is not an array, complex, or vector type, an
1363 exception will be raised.
1364 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001365 result = lib.clang_getElementType(self)
Gregory Szorc86057602012-02-17 07:44:46 +00001366 if result.kind == TypeKind.INVALID:
1367 raise Exception('Element type not available on this type.')
1368
1369 return result
1370
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001371 @property
1372 def element_count(self):
1373 """Retrieve the number of elements in this type.
1374
1375 Returns an int.
1376
1377 If the Type is not an array or vector, this raises.
1378 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001379 result = lib.clang_getNumElements(self)
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001380 if result < 0:
1381 raise Exception('Type does not have elements.')
1382
1383 return result
1384
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001385 @property
1386 def translation_unit(self):
1387 """The TranslationUnit to which this Type is associated."""
1388 # If this triggers an AttributeError, the instance was not properly
1389 # instantiated.
1390 return self._tu
1391
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001392 @staticmethod
1393 def from_result(res, fn, args):
1394 assert isinstance(res, Type)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001395
1396 tu = None
1397 for arg in args:
1398 if hasattr(arg, 'translation_unit'):
1399 tu = arg.translation_unit
1400 break
1401
1402 assert tu is not None
1403 res._tu = tu
1404
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001405 return res
1406
1407 def get_canonical(self):
1408 """
1409 Return the canonical type for a Type.
1410
1411 Clang's type system explicitly models typedefs and all the
1412 ways a specific type can be represented. The canonical type
1413 is the underlying type with all the "sugar" removed. For
1414 example, if 'T' is a typedef for 'int', the canonical type for
1415 'T' would be 'int'.
1416 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001417 return lib.clang_getCanonicalType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001418
1419 def is_const_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001420 """Determine whether a Type has the "const" qualifier set.
1421
1422 This does not look through typedefs that may have added "const"
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001423 at a different level.
1424 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001425 return lib.clang_isConstQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001426
1427 def is_volatile_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001428 """Determine whether a Type has the "volatile" qualifier set.
1429
1430 This does not look through typedefs that may have added "volatile"
1431 at a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001432 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001433 return lib.clang_isVolatileQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001434
1435 def is_restrict_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001436 """Determine whether a Type has the "restrict" qualifier set.
1437
1438 This does not look through typedefs that may have added "restrict" at
1439 a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001440 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001441 return lib.clang_isRestrictQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001442
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001443 def is_function_variadic(self):
1444 """Determine whether this function Type is a variadic function type."""
1445 assert self.kind == TypeKind.FUNCTIONPROTO
1446
Gregory Szorc9537e202012-07-12 04:56:46 +00001447 return lib.clang_isFunctionTypeVariadic(self)
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001448
Gregory Szorc96ad6332012-02-05 19:42:06 +00001449 def is_pod(self):
1450 """Determine whether this Type represents plain old data (POD)."""
Gregory Szorc9537e202012-07-12 04:56:46 +00001451 return lib.clang_isPODType(self)
Gregory Szorc96ad6332012-02-05 19:42:06 +00001452
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001453 def get_pointee(self):
1454 """
1455 For pointer types, returns the type of the pointee.
1456 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001457 return lib.clang_getPointeeType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001458
1459 def get_declaration(self):
1460 """
1461 Return the cursor for the declaration of the given type.
1462 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001463 return lib.clang_getTypeDeclaration(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001464
1465 def get_result(self):
1466 """
1467 Retrieve the result type associated with a function type.
1468 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001469 return lib.clang_getResultType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001470
Douglas Gregor13102ff2011-10-19 05:51:43 +00001471 def get_array_element_type(self):
1472 """
1473 Retrieve the type of the elements of the array type.
1474 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001475 return lib.clang_getArrayElementType(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001476
1477 def get_array_size(self):
1478 """
1479 Retrieve the size of the constant array.
1480 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001481 return lib.clang_getArraySize(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001482
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001483 def __eq__(self, other):
1484 if type(other) != type(self):
1485 return False
1486
Gregory Szorc9537e202012-07-12 04:56:46 +00001487 return lib.clang_equalTypes(self, other)
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001488
1489 def __ne__(self, other):
1490 return not self.__eq__(other)
1491
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001492## CIndex Objects ##
1493
1494# CIndex objects (derived from ClangObject) are essentially lightweight
1495# wrappers attached to some underlying object, which is exposed via CIndex as
1496# a void*.
1497
1498class ClangObject(object):
1499 """
1500 A helper for Clang objects. This class helps act as an intermediary for
1501 the ctypes library and the Clang CIndex library.
1502 """
1503 def __init__(self, obj):
1504 assert isinstance(obj, c_object_p) and obj
1505 self.obj = self._as_parameter_ = obj
1506
1507 def from_param(self):
1508 return self._as_parameter_
1509
Daniel Dunbar5b534f62010-01-25 00:44:11 +00001510
1511class _CXUnsavedFile(Structure):
1512 """Helper for passing unsaved file arguments."""
1513 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1514
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001515class CompletionChunk:
1516 class Kind:
1517 def __init__(self, name):
1518 self.name = name
1519
1520 def __str__(self):
1521 return self.name
1522
1523 def __repr__(self):
1524 return "<ChunkKind: %s>" % self
1525
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001526 def __init__(self, completionString, key):
1527 self.cs = completionString
1528 self.key = key
1529
1530 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001531 return "{'" + self.spelling + "', " + str(self.kind) + "}"
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001532
1533 @property
1534 def spelling(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001535 return lib.clang_getCompletionChunkText(self.cs, self.key).spelling
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001536
1537 @property
1538 def kind(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001539 res = lib.clang_getCompletionChunkKind(self.cs, self.key)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001540 return completionChunkKindMap[res]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001541
1542 @property
1543 def string(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001544 res = lib.clang_getCompletionChunkCompletionString(self.cs, self.key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001545
1546 if (res):
1547 return CompletionString(res)
1548 else:
1549 None
1550
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001551 def isKindOptional(self):
1552 return self.kind == completionChunkKindMap[0]
1553
1554 def isKindTypedText(self):
1555 return self.kind == completionChunkKindMap[1]
1556
1557 def isKindPlaceHolder(self):
1558 return self.kind == completionChunkKindMap[3]
1559
1560 def isKindInformative(self):
1561 return self.kind == completionChunkKindMap[4]
1562
1563 def isKindResultType(self):
1564 return self.kind == completionChunkKindMap[15]
1565
1566completionChunkKindMap = {
1567 0: CompletionChunk.Kind("Optional"),
1568 1: CompletionChunk.Kind("TypedText"),
1569 2: CompletionChunk.Kind("Text"),
1570 3: CompletionChunk.Kind("Placeholder"),
1571 4: CompletionChunk.Kind("Informative"),
1572 5: CompletionChunk.Kind("CurrentParameter"),
1573 6: CompletionChunk.Kind("LeftParen"),
1574 7: CompletionChunk.Kind("RightParen"),
1575 8: CompletionChunk.Kind("LeftBracket"),
1576 9: CompletionChunk.Kind("RightBracket"),
1577 10: CompletionChunk.Kind("LeftBrace"),
1578 11: CompletionChunk.Kind("RightBrace"),
1579 12: CompletionChunk.Kind("LeftAngle"),
1580 13: CompletionChunk.Kind("RightAngle"),
1581 14: CompletionChunk.Kind("Comma"),
1582 15: CompletionChunk.Kind("ResultType"),
1583 16: CompletionChunk.Kind("Colon"),
1584 17: CompletionChunk.Kind("SemiColon"),
1585 18: CompletionChunk.Kind("Equal"),
1586 19: CompletionChunk.Kind("HorizontalSpace"),
1587 20: CompletionChunk.Kind("VerticalSpace")}
1588
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001589class CompletionString(ClangObject):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001590 class Availability:
1591 def __init__(self, name):
1592 self.name = name
1593
1594 def __str__(self):
1595 return self.name
1596
1597 def __repr__(self):
1598 return "<Availability: %s>" % self
1599
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001600 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001601 return lib.clang_getNumCompletionChunks(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001602
1603 def __getitem__(self, key):
1604 if len(self) <= key:
1605 raise IndexError
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001606 return CompletionChunk(self.obj, key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001607
1608 @property
1609 def priority(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001610 return lib.clang_getCompletionPriority(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001611
1612 @property
1613 def availability(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001614 res = lib.clang_getCompletionAvailability(self.obj)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001615 return availabilityKinds[res]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001616
1617 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001618 return " | ".join([str(a) for a in self]) \
1619 + " || Priority: " + str(self.priority) \
1620 + " || Availability: " + str(self.availability)
1621
1622availabilityKinds = {
1623 0: CompletionChunk.Kind("Available"),
1624 1: CompletionChunk.Kind("Deprecated"),
1625 2: CompletionChunk.Kind("NotAvailable")}
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001626
Tobias Grosser0a166802011-02-05 17:54:04 +00001627class CodeCompletionResult(Structure):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001628 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
1629
1630 def __repr__(self):
1631 return str(CompletionString(self.completionString))
1632
1633 @property
1634 def kind(self):
1635 return CursorKind.from_id(self.cursorKind)
1636
1637 @property
1638 def string(self):
1639 return CompletionString(self.completionString)
Tobias Grosser0a166802011-02-05 17:54:04 +00001640
1641class CCRStructure(Structure):
1642 _fields_ = [('results', POINTER(CodeCompletionResult)),
1643 ('numResults', c_int)]
1644
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001645 def __len__(self):
1646 return self.numResults
1647
1648 def __getitem__(self, key):
1649 if len(self) <= key:
1650 raise IndexError
1651
1652 return self.results[key]
1653
Tobias Grosser0a166802011-02-05 17:54:04 +00001654class CodeCompletionResults(ClangObject):
1655 def __init__(self, ptr):
1656 assert isinstance(ptr, POINTER(CCRStructure)) and ptr
1657 self.ptr = self._as_parameter_ = ptr
1658
1659 def from_param(self):
1660 return self._as_parameter_
1661
1662 def __del__(self):
1663 CodeCompletionResults_dispose(self)
1664
1665 @property
1666 def results(self):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001667 return self.ptr.contents
Tobias Grosser0a166802011-02-05 17:54:04 +00001668
1669 @property
1670 def diagnostics(self):
1671 class DiagnosticsItr:
1672 def __init__(self, ccr):
1673 self.ccr= ccr
1674
1675 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001676 return int(lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
Tobias Grosser0a166802011-02-05 17:54:04 +00001677
1678 def __getitem__(self, key):
Gregory Szorc9537e202012-07-12 04:56:46 +00001679 return lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
Tobias Grosser0a166802011-02-05 17:54:04 +00001680
1681 return DiagnosticsItr(self)
1682
1683
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001684class Index(ClangObject):
1685 """
1686 The Index type provides the primary interface to the Clang CIndex library,
1687 primarily by providing an interface for reading and parsing translation
1688 units.
1689 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001690
1691 @staticmethod
Daniel Dunbar2791dfc2010-01-30 23:58:39 +00001692 def create(excludeDecls=False):
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001693 """
1694 Create a new Index.
1695 Parameters:
1696 excludeDecls -- Exclude local declarations from translation units.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001697 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001698 return Index(lib.clang_createIndex(excludeDecls, 0))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001699
1700 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001701 lib.clang_disposeIndex(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001702
1703 def read(self, path):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001704 """Load a TranslationUnit from the given AST file."""
1705 return TranslationUnit.from_ast(path, self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001706
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001707 def parse(self, path, args=None, unsaved_files=None, options = 0):
1708 """Load the translation unit from the given source code file by running
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001709 clang and generating the AST before loading. Additional command line
1710 parameters can be passed to clang via the args parameter.
Daniel Dunbar5b534f62010-01-25 00:44:11 +00001711
1712 In-memory contents for files can be provided by passing a list of pairs
1713 to as unsaved_files, the first item should be the filenames to be mapped
1714 and the second should be the contents to be substituted for the
1715 file. The contents may be passed as strings or file objects.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001716
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001717 If an error was encountered during parsing, a TranslationUnitLoadError
1718 will be raised.
1719 """
1720 return TranslationUnit.from_source(path, args, unsaved_files, options,
1721 self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001722
1723class TranslationUnit(ClangObject):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001724 """Represents a source code translation unit.
1725
1726 This is one of the main types in the API. Any time you wish to interact
1727 with Clang's representation of a source file, you typically start with a
1728 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001729 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001730
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001731 # Default parsing mode.
1732 PARSE_NONE = 0
1733
1734 # Instruct the parser to create a detailed processing record containing
1735 # metadata not normally retained.
1736 PARSE_DETAILED_PROCESSING_RECORD = 1
1737
1738 # Indicates that the translation unit is incomplete. This is typically used
1739 # when parsing headers.
1740 PARSE_INCOMPLETE = 2
1741
1742 # Instruct the parser to create a pre-compiled preamble for the translation
1743 # unit. This caches the preamble (included files at top of source file).
1744 # This is useful if the translation unit will be reparsed and you don't
1745 # want to incur the overhead of reparsing the preamble.
1746 PARSE_PRECOMPILED_PREAMBLE = 4
1747
1748 # Cache code completion information on parse. This adds time to parsing but
1749 # speeds up code completion.
1750 PARSE_CACHE_COMPLETION_RESULTS = 8
1751
1752 # Flags with values 16 and 32 are deprecated and intentionally omitted.
1753
1754 # Do not parse function bodies. This is useful if you only care about
1755 # searching for declarations/definitions.
1756 PARSE_SKIP_FUNCTION_BODIES = 64
1757
1758 @classmethod
1759 def from_source(cls, filename, args=None, unsaved_files=None, options=0,
1760 index=None):
1761 """Create a TranslationUnit by parsing source.
1762
1763 This is capable of processing source code both from files on the
1764 filesystem as well as in-memory contents.
1765
1766 Command-line arguments that would be passed to clang are specified as
1767 a list via args. These can be used to specify include paths, warnings,
1768 etc. e.g. ["-Wall", "-I/path/to/include"].
1769
1770 In-memory file content can be provided via unsaved_files. This is an
1771 iterable of 2-tuples. The first element is the str filename. The
1772 second element defines the content. Content can be provided as str
1773 source code or as file objects (anything with a read() method). If
1774 a file object is being used, content will be read until EOF and the
1775 read cursor will not be reset to its original position.
1776
1777 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
1778 control parsing behavior.
1779
Gregory Szorc2283b462012-05-12 20:49:13 +00001780 index is an Index instance to utilize. If not provided, a new Index
1781 will be created for this TranslationUnit.
1782
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001783 To parse source from the filesystem, the filename of the file to parse
1784 is specified by the filename argument. Or, filename could be None and
1785 the args list would contain the filename(s) to parse.
1786
1787 To parse source from an in-memory buffer, set filename to the virtual
1788 filename you wish to associate with this source (e.g. "test.c"). The
1789 contents of that file are then provided in unsaved_files.
1790
1791 If an error occurs, a TranslationUnitLoadError is raised.
1792
1793 Please note that a TranslationUnit with parser errors may be returned.
1794 It is the caller's responsibility to check tu.diagnostics for errors.
1795
1796 Also note that Clang infers the source language from the extension of
1797 the input filename. If you pass in source code containing a C++ class
1798 declaration with the filename "test.c" parsing will fail.
1799 """
1800 if args is None:
1801 args = []
1802
1803 if unsaved_files is None:
1804 unsaved_files = []
1805
1806 if index is None:
1807 index = Index.create()
1808
1809 args_array = None
1810 if len(args) > 0:
1811 args_array = (c_char_p * len(args))(* args)
1812
1813 unsaved_array = None
1814 if len(unsaved_files) > 0:
1815 unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
1816 for i, (name, contents) in enumerate(unsaved_files):
1817 if hasattr(contents, "read"):
1818 contents = contents.read()
1819
1820 unsaved_array[i].name = name
1821 unsaved_array[i].contents = contents
1822 unsaved_array[i].length = len(contents)
1823
Gregory Szorc9537e202012-07-12 04:56:46 +00001824 ptr = lib.clang_parseTranslationUnit(index, filename, args_array,
1825 len(args), unsaved_array,
1826 len(unsaved_files), options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001827
1828 if ptr is None:
1829 raise TranslationUnitLoadError("Error parsing translation unit.")
1830
1831 return cls(ptr, index=index)
1832
1833 @classmethod
1834 def from_ast_file(cls, filename, index=None):
1835 """Create a TranslationUnit instance from a saved AST file.
1836
1837 A previously-saved AST file (provided with -emit-ast or
1838 TranslationUnit.save()) is loaded from the filename specified.
1839
1840 If the file cannot be loaded, a TranslationUnitLoadError will be
1841 raised.
1842
1843 index is optional and is the Index instance to use. If not provided,
1844 a default Index will be created.
1845 """
1846 if index is None:
1847 index = Index.create()
1848
Gregory Szorc9537e202012-07-12 04:56:46 +00001849 ptr = lib.clang_createTranslationUnit(index, filename)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001850 if ptr is None:
1851 raise TranslationUnitLoadError(filename)
1852
1853 return cls(ptr=ptr, index=index)
1854
1855 def __init__(self, ptr, index):
1856 """Create a TranslationUnit instance.
1857
1858 TranslationUnits should be created using one of the from_* @classmethod
1859 functions above. __init__ is only called internally.
1860 """
1861 assert isinstance(index, Index)
1862
Daniel Dunbar532fc632010-01-30 23:59:02 +00001863 ClangObject.__init__(self, ptr)
Daniel Dunbar532fc632010-01-30 23:59:02 +00001864
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001865 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001866 lib.clang_disposeTranslationUnit(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001867
Daniel Dunbar1b945a72010-01-24 04:09:43 +00001868 @property
1869 def cursor(self):
1870 """Retrieve the cursor that represents the given translation unit."""
Gregory Szorc9537e202012-07-12 04:56:46 +00001871 return lib.clang_getTranslationUnitCursor(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001872
1873 @property
1874 def spelling(self):
Daniel Dunbar1b945a72010-01-24 04:09:43 +00001875 """Get the original translation unit source file name."""
Gregory Szorc9537e202012-07-12 04:56:46 +00001876 return lib.clang_getTranslationUnitSpelling(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001877
Daniel Dunbaref7f7982010-02-13 18:33:18 +00001878 def get_includes(self):
1879 """
1880 Return an iterable sequence of FileInclusion objects that describe the
1881 sequence of inclusions in a translation unit. The first object in
1882 this sequence is always the input file. Note that this method will not
1883 recursively iterate over header files included through precompiled
1884 headers.
1885 """
1886 def visitor(fobj, lptr, depth, includes):
Douglas Gregor8be80e12011-07-06 03:00:34 +00001887 if depth > 0:
1888 loc = lptr.contents
1889 includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
Daniel Dunbaref7f7982010-02-13 18:33:18 +00001890
1891 # Automatically adapt CIndex/ctype pointers to python objects
1892 includes = []
Gregory Szorc9537e202012-07-12 04:56:46 +00001893 lib.clang_getInclusions(self,
1894 callbacks['translation_unit_includes'](visitor), includes)
1895
Daniel Dunbaref7f7982010-02-13 18:33:18 +00001896 return iter(includes)
1897
Gregory Szorc0f1964a2012-07-12 05:05:56 +00001898 def get_file(self, filename):
1899 """Obtain a File from this translation unit."""
1900
1901 return File.from_name(self, filename)
1902
1903 def get_location(self, filename, position):
1904 """Obtain a SourceLocation for a file in this translation unit.
1905
1906 The position can be specified by passing:
1907
1908 - Integer file offset. Initial file offset is 0.
1909 - 2-tuple of (line number, column number). Initial file position is
1910 (0, 0)
1911 """
1912 f = self.get_file(filename)
1913
1914 if isinstance(position, int):
1915 return SourceLocation.from_offset(self, f, position)
1916
1917 return SourceLocation.from_position(self, f, position[0], position[1])
1918
1919 def get_extent(self, filename, locations):
1920 """Obtain a SourceRange from this translation unit.
1921
1922 The bounds of the SourceRange must ultimately be defined by a start and
1923 end SourceLocation. For the locations argument, you can pass:
1924
1925 - 2 SourceLocation instances in a 2-tuple or list.
1926 - 2 int file offsets via a 2-tuple or list.
1927 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
1928
1929 e.g.
1930
1931 get_extent('foo.c', (5, 10))
1932 get_extent('foo.c', ((1, 1), (1, 15)))
1933 """
1934 f = self.get_file(filename)
1935
1936 if len(locations) < 2:
1937 raise Exception('Must pass object with at least 2 elements')
1938
1939 start_location, end_location = locations
1940
1941 if hasattr(start_location, '__len__'):
1942 start_location = SourceLocation.from_position(self, f,
1943 start_location[0], start_location[1])
1944 elif isinstance(start_location, int):
1945 start_location = SourceLocation.from_offset(self, f,
1946 start_location)
1947
1948 if hasattr(end_location, '__len__'):
1949 end_location = SourceLocation.from_position(self, f,
1950 end_location[0], end_location[1])
1951 elif isinstance(end_location, int):
1952 end_location = SourceLocation.from_offset(self, f, end_location)
1953
1954 assert isinstance(start_location, SourceLocation)
1955 assert isinstance(end_location, SourceLocation)
1956
1957 return SourceRange.from_locations(start_location, end_location)
1958
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00001959 @property
1960 def diagnostics(self):
1961 """
1962 Return an iterable (and indexable) object containing the diagnostics.
1963 """
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00001964 class DiagIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00001965 def __init__(self, tu):
1966 self.tu = tu
1967
1968 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001969 return int(lib.clang_getNumDiagnostics(self.tu))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00001970
1971 def __getitem__(self, key):
Gregory Szorc9537e202012-07-12 04:56:46 +00001972 diag = lib.clang_getDiagnostic(self.tu, key)
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00001973 if not diag:
1974 raise IndexError
1975 return Diagnostic(diag)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00001976
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00001977 return DiagIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00001978
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001979 def reparse(self, unsaved_files=None, options=0):
Tobias Grosser265e6b22011-02-05 17:54:00 +00001980 """
1981 Reparse an already parsed translation unit.
1982
1983 In-memory contents for files can be provided by passing a list of pairs
1984 as unsaved_files, the first items should be the filenames to be mapped
1985 and the second should be the contents to be substituted for the
1986 file. The contents may be passed as strings or file objects.
1987 """
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001988 if unsaved_files is None:
1989 unsaved_files = []
1990
Tobias Grosser265e6b22011-02-05 17:54:00 +00001991 unsaved_files_array = 0
1992 if len(unsaved_files):
1993 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
1994 for i,(name,value) in enumerate(unsaved_files):
1995 if not isinstance(value, str):
1996 # FIXME: It would be great to support an efficient version
1997 # of this, one day.
1998 value = value.read()
1999 print value
2000 if not isinstance(value, str):
2001 raise TypeError,'Unexpected unsaved file contents.'
2002 unsaved_files_array[i].name = name
2003 unsaved_files_array[i].contents = value
2004 unsaved_files_array[i].length = len(value)
Gregory Szorc9537e202012-07-12 04:56:46 +00002005 ptr = lib.clang_reparseTranslationUnit(self, len(unsaved_files),
2006 unsaved_files_array, options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002007
2008 def save(self, filename):
2009 """Saves the TranslationUnit to a file.
2010
2011 This is equivalent to passing -emit-ast to the clang frontend. The
2012 saved file can be loaded back into a TranslationUnit. Or, if it
2013 corresponds to a header, it can be used as a pre-compiled header file.
2014
2015 If an error occurs while saving, a TranslationUnitSaveError is raised.
2016 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
2017 the constructed TranslationUnit was not valid at time of save. In this
2018 case, the reason(s) why should be available via
2019 TranslationUnit.diagnostics().
2020
2021 filename -- The path to save the translation unit to.
2022 """
Gregory Szorc9537e202012-07-12 04:56:46 +00002023 options = lib.clang_defaultSaveOptions(self)
2024 result = int(lib.clang_saveTranslationUnit(self, filename, options))
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002025 if result != 0:
2026 raise TranslationUnitSaveError(result,
2027 'Error saving TranslationUnit.')
2028
Gregory Szorc2283b462012-05-12 20:49:13 +00002029 def codeComplete(self, path, line, column, unsaved_files=None, options=0):
Tobias Grosser0a166802011-02-05 17:54:04 +00002030 """
2031 Code complete in this translation unit.
2032
2033 In-memory contents for files can be provided by passing a list of pairs
2034 as unsaved_files, the first items should be the filenames to be mapped
2035 and the second should be the contents to be substituted for the
2036 file. The contents may be passed as strings or file objects.
2037 """
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002038 if unsaved_files is None:
2039 unsaved_files = []
2040
Tobias Grosser0a166802011-02-05 17:54:04 +00002041 unsaved_files_array = 0
2042 if len(unsaved_files):
2043 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2044 for i,(name,value) in enumerate(unsaved_files):
2045 if not isinstance(value, str):
2046 # FIXME: It would be great to support an efficient version
2047 # of this, one day.
2048 value = value.read()
2049 print value
2050 if not isinstance(value, str):
2051 raise TypeError,'Unexpected unsaved file contents.'
2052 unsaved_files_array[i].name = name
2053 unsaved_files_array[i].contents = value
2054 unsaved_files_array[i].length = len(value)
Gregory Szorc9537e202012-07-12 04:56:46 +00002055 ptr = lib.clang_codeCompleteAt(self, path, line, column,
2056 unsaved_files_array, len(unsaved_files), options)
Tobias Grosserba5d10b2011-10-31 02:06:50 +00002057 if ptr:
2058 return CodeCompletionResults(ptr)
2059 return None
Tobias Grosser265e6b22011-02-05 17:54:00 +00002060
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002061class File(ClangObject):
2062 """
Daniel Dunbar7b48b352010-01-24 04:09:34 +00002063 The File class represents a particular source file that is part of a
2064 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002065 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002066
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002067 @staticmethod
2068 def from_name(translation_unit, file_name):
2069 """Retrieve a file handle within the given translation unit."""
Gregory Szorc9537e202012-07-12 04:56:46 +00002070 return File(lib.clang_getFile(translation_unit, file_name))
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002071
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002072 @property
2073 def name(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002074 """Return the complete file and path name of the file."""
Gregory Szorc9537e202012-07-12 04:56:46 +00002075 return lib.clang_getCString(lib.clang_getFileName(self))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002076
2077 @property
2078 def time(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002079 """Return the last modification time of the file."""
Gregory Szorc9537e202012-07-12 04:56:46 +00002080 return lib.clang_getFileTime(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002081
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002082 def __str__(self):
2083 return self.name
2084
2085 def __repr__(self):
2086 return "<File: %s>" % (self.name)
2087
Gregory Szorc9537e202012-07-12 04:56:46 +00002088 @staticmethod
2089 def from_cursor_result(res, fn, args):
2090 assert isinstance(res, File)
2091
2092 # Copy a reference to the TranslationUnit to prevent premature GC.
2093 res._tu = args[0]._tu
2094 return res
2095
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002096class FileInclusion(object):
2097 """
2098 The FileInclusion class represents the inclusion of one source file by
2099 another via a '#include' directive or as the input file for the translation
2100 unit. This class provides information about the included file, the including
2101 file, the location of the '#include' directive and the depth of the included
2102 file in the stack. Note that the input file has depth 0.
2103 """
2104
2105 def __init__(self, src, tgt, loc, depth):
2106 self.source = src
2107 self.include = tgt
2108 self.location = loc
2109 self.depth = depth
2110
2111 @property
2112 def is_input_file(self):
2113 """True if the included file is the input file."""
2114 return self.depth == 0
2115
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002116class CompilationDatabaseError(Exception):
2117 """Represents an error that occurred when working with a CompilationDatabase
2118
2119 Each error is associated to an enumerated value, accessible under
2120 e.cdb_error. Consumers can compare the value with one of the ERROR_
2121 constants in this class.
2122 """
2123
2124 # An unknown error occured
2125 ERROR_UNKNOWN = 0
2126
2127 # The database could not be loaded
2128 ERROR_CANNOTLOADDATABASE = 1
2129
2130 def __init__(self, enumeration, message):
2131 assert isinstance(enumeration, int)
2132
2133 if enumeration > 1:
2134 raise Exception("Encountered undefined CompilationDatabase error "
2135 "constant: %d. Please file a bug to have this "
2136 "value supported." % enumeration)
2137
2138 self.cdb_error = enumeration
2139 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
2140
2141class CompileCommand(object):
2142 """Represents the compile command used to build a file"""
2143 def __init__(self, cmd, ccmds):
2144 self.cmd = cmd
2145 # Keep a reference to the originating CompileCommands
2146 # to prevent garbage collection
2147 self.ccmds = ccmds
2148
2149 @property
2150 def directory(self):
2151 """Get the working directory for this CompileCommand"""
Gregory Szorc9537e202012-07-12 04:56:46 +00002152 return lib.clang_CompileCommand_getDirectory(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002153
2154 @property
2155 def arguments(self):
2156 """
2157 Get an iterable object providing each argument in the
2158 command line for the compiler invocation as a _CXString.
2159
Arnaud A. de Grandmaison577c5302012-07-06 08:22:05 +00002160 Invariant : the first argument is the compiler executable
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002161 """
Gregory Szorc9537e202012-07-12 04:56:46 +00002162 length = lib.clang_CompileCommand_getNumArgs(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002163 for i in xrange(length):
Gregory Szorc9537e202012-07-12 04:56:46 +00002164 yield lib.clang_CompileCommand_getArg(self.cmd, i)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002165
2166class CompileCommands(object):
2167 """
2168 CompileCommands is an iterable object containing all CompileCommand
2169 that can be used for building a specific file.
2170 """
2171 def __init__(self, ccmds):
2172 self.ccmds = ccmds
2173
2174 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00002175 lib.clang_CompileCommands_dispose(self.ccmds)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002176
2177 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00002178 return int(lib.clang_CompileCommands_getSize(self.ccmds))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002179
2180 def __getitem__(self, i):
Gregory Szorc9537e202012-07-12 04:56:46 +00002181 cc = lib.clang_CompileCommands_getCommand(self.ccmds, i)
Arnaud A. de Grandmaisonb1614042012-07-09 11:57:30 +00002182 if not cc:
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002183 raise IndexError
2184 return CompileCommand(cc, self)
2185
2186 @staticmethod
2187 def from_result(res, fn, args):
2188 if not res:
2189 return None
2190 return CompileCommands(res)
2191
2192class CompilationDatabase(ClangObject):
2193 """
2194 The CompilationDatabase is a wrapper class around
2195 clang::tooling::CompilationDatabase
2196
2197 It enables querying how a specific source file can be built.
2198 """
2199
2200 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00002201 lib.clang_CompilationDatabase_dispose(self)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002202
2203 @staticmethod
2204 def from_result(res, fn, args):
2205 if not res:
2206 raise CompilationDatabaseError(0,
2207 "CompilationDatabase loading failed")
2208 return CompilationDatabase(res)
2209
2210 @staticmethod
2211 def fromDirectory(buildDir):
2212 """Builds a CompilationDatabase from the database found in buildDir"""
2213 errorCode = c_uint()
2214 try:
Gregory Szorc9537e202012-07-12 04:56:46 +00002215 cdb = lib.clang_CompilationDatabase_fromDirectory(buildDir,
2216 byref(errorCode))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002217 except CompilationDatabaseError as e:
Gregory Szorc9537e202012-07-12 04:56:46 +00002218 raise CompilationDatabaseError(int(errorCode.value),
2219 "CompilationDatabase loading failed")
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002220 return cdb
2221
2222 def getCompileCommands(self, filename):
2223 """
2224 Get an iterable object providing all the CompileCommands available to
Arnaud A. de Grandmaison44394782012-06-30 20:43:37 +00002225 build filename. Returns None if filename is not found in the database.
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002226 """
Gregory Szorc9537e202012-07-12 04:56:46 +00002227 return lib.clang_CompilationDatabase_getCompileCommands(self, filename)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002228
Gregory Szorc9537e202012-07-12 04:56:46 +00002229# Now comes the plumbing to hook up the C library.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002230
Gregory Szorc9537e202012-07-12 04:56:46 +00002231# Register callback types in common container.
2232callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
2233 POINTER(SourceLocation), c_uint, py_object)
2234callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
Daniel Dunbara33dca42010-01-24 21:19:57 +00002235
Gregory Szorc9537e202012-07-12 04:56:46 +00002236def register_functions(lib):
2237 """Register function prototypes with a libclang library instance.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002238
Gregory Szorc9537e202012-07-12 04:56:46 +00002239 This must be called as part of library instantiation so Python knows how
2240 to call out to the shared library.
2241 """
2242 # Functions are registered in strictly alphabetical order.
2243 #lib.clang_annotateTokens.argtype = [TranslationUnit, POINTER(Token),
2244 # c_uint, POINTER(Cursor)]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002245
Gregory Szorc9537e202012-07-12 04:56:46 +00002246 lib.clang_CompilationDatabase_dispose.argtypes = [c_object_p]
Tobias Grosser58ba8c92011-10-31 00:31:32 +00002247
Gregory Szorc9537e202012-07-12 04:56:46 +00002248 lib.clang_CompilationDatabase_fromDirectory.argtypes = [c_char_p,
2249 POINTER(c_uint)]
2250 lib.clang_CompilationDatabase_fromDirectory.restype = c_object_p
2251 lib.clang_CompilationDatabase_fromDirectory.errcheck = CompilationDatabase.from_result
Tobias Grosser74858332012-02-05 11:40:59 +00002252
Gregory Szorc9537e202012-07-12 04:56:46 +00002253 lib.clang_CompilationDatabase_getCompileCommands.argtypes = [c_object_p, c_char_p]
2254 lib.clang_CompilationDatabase_getCompileCommands.restype = c_object_p
2255 lib.clang_CompilationDatabase_getCompileCommands.errcheck = CompileCommands.from_result
Gregory Szorc74bb7102012-06-11 11:11:48 +00002256
Gregory Szorc9537e202012-07-12 04:56:46 +00002257 lib.clang_CompileCommands_dispose.argtypes = [c_object_p]
Daniel Dunbar532fc632010-01-30 23:59:02 +00002258
Gregory Szorc9537e202012-07-12 04:56:46 +00002259 lib.clang_CompileCommands_getCommand.argtypes = [c_object_p, c_uint]
2260 lib.clang_CompileCommands_getCommand.restype = c_object_p
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002261
Gregory Szorc9537e202012-07-12 04:56:46 +00002262 lib.clang_CompileCommands_getSize.argtypes = [c_object_p]
2263 lib.clang_CompileCommands_getSize.restype = c_uint
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002264
Gregory Szorc9537e202012-07-12 04:56:46 +00002265 lib.clang_CompileCommand_getArg.argtypes = [c_object_p, c_uint]
2266 lib.clang_CompileCommand_getArg.restype = _CXString
2267 lib.clang_CompileCommand_getArg.errcheck = _CXString.from_result
Tobias Grosser74858332012-02-05 11:40:59 +00002268
Gregory Szorc9537e202012-07-12 04:56:46 +00002269 lib.clang_CompileCommand_getDirectory.argtypes = [c_object_p]
2270 lib.clang_CompileCommand_getDirectory.restype = _CXString
2271 lib.clang_CompileCommand_getDirectory.errcheck = _CXString.from_result
Daniel Dunbara6a64992010-01-24 21:20:39 +00002272
Gregory Szorc9537e202012-07-12 04:56:46 +00002273 lib.clang_CompileCommand_getNumArgs.argtypes = [c_object_p]
2274 lib.clang_CompileCommand_getNumArgs.restype = c_uint
Daniel Dunbara6a64992010-01-24 21:20:39 +00002275
Gregory Szorc9537e202012-07-12 04:56:46 +00002276 lib.clang_codeCompleteAt.argtypes = [TranslationUnit, c_char_p, c_int,
2277 c_int, c_void_p, c_int, c_int]
2278 lib.clang_codeCompleteAt.restype = POINTER(CCRStructure)
Daniel Dunbara6a64992010-01-24 21:20:39 +00002279
Gregory Szorc9537e202012-07-12 04:56:46 +00002280 lib.clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults,
2281 c_int]
2282 lib.clang_codeCompleteGetDiagnostic.restype = Diagnostic
Daniel Dunbara6a64992010-01-24 21:20:39 +00002283
Gregory Szorc9537e202012-07-12 04:56:46 +00002284 lib.clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults]
2285 lib.clang_codeCompleteGetNumDiagnostics.restype = c_int
Douglas Gregor8be80e12011-07-06 03:00:34 +00002286
Gregory Szorc9537e202012-07-12 04:56:46 +00002287 lib.clang_createIndex.argtypes = [c_int, c_int]
2288 lib.clang_createIndex.restype = c_object_p
Daniel Dunbara6a64992010-01-24 21:20:39 +00002289
Gregory Szorc9537e202012-07-12 04:56:46 +00002290 lib.clang_createTranslationUnit.argtypes = [Index, c_char_p]
2291 lib.clang_createTranslationUnit.restype = c_object_p
Tobias Grossereb136342012-02-05 11:42:09 +00002292
Gregory Szorc9537e202012-07-12 04:56:46 +00002293 lib.clang_CXXMethod_isStatic.argtypes = [Cursor]
2294 lib.clang_CXXMethod_isStatic.restype = bool
Tobias Grossereb136342012-02-05 11:42:09 +00002295
Gregory Szorc9537e202012-07-12 04:56:46 +00002296 lib.clang_CXXMethod_isVirtual.argtypes = [Cursor]
2297 lib.clang_CXXMethod_isVirtual.restype = bool
Tobias Grossereb136342012-02-05 11:42:09 +00002298
Gregory Szorc9537e202012-07-12 04:56:46 +00002299 lib.clang_defaultSaveOptions.argtypes = [TranslationUnit]
2300 lib.clang_defaultSaveOptions.restype = c_uint
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002301
Gregory Szorc9537e202012-07-12 04:56:46 +00002302 lib.clang_disposeCodeCompleteResults.argtypes = [CodeCompletionResults]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002303
Gregory Szorc9537e202012-07-12 04:56:46 +00002304 #lib.clang_disposeCXTUResourceUsage.argtypes = [CXTUResourceUsage]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002305
Gregory Szorc9537e202012-07-12 04:56:46 +00002306 lib.clang_disposeDiagnostic.argtypes = [Diagnostic]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002307
Gregory Szorc9537e202012-07-12 04:56:46 +00002308 lib.clang_disposeIndex.argtypes = [Index]
Gregory Szorce65b34d2012-06-09 16:21:34 +00002309
Gregory Szorc9537e202012-07-12 04:56:46 +00002310 lib.clang_disposeString.argtypes = [_CXString]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002311
Gregory Szorc9537e202012-07-12 04:56:46 +00002312 #lib.clang_disposeTokens.argtype = [TranslationUnit, POINTER(Token), c_uint]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002313
Gregory Szorc9537e202012-07-12 04:56:46 +00002314 lib.clang_disposeTranslationUnit.argtypes = [TranslationUnit]
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00002315
Gregory Szorc9537e202012-07-12 04:56:46 +00002316 lib.clang_equalCursors.argtypes = [Cursor, Cursor]
2317 lib.clang_equalCursors.restype = bool
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002318
Gregory Szorc9537e202012-07-12 04:56:46 +00002319 lib.clang_equalLocations.argtypes = [SourceLocation, SourceLocation]
2320 lib.clang_equalLocations.restype = bool
Douglas Gregor8be80e12011-07-06 03:00:34 +00002321
Gregory Szorc9537e202012-07-12 04:56:46 +00002322 lib.clang_equalRanges.argtypes = [SourceRange, SourceRange]
2323 lib.clang_equalRanges.restype = bool
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002324
Gregory Szorc9537e202012-07-12 04:56:46 +00002325 lib.clang_equalTypes.argtypes = [Type, Type]
2326 lib.clang_equalTypes.restype = bool
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002327
Gregory Szorc9537e202012-07-12 04:56:46 +00002328 lib.clang_getArgType.argtypes = [Type, c_uint]
2329 lib.clang_getArgType.restype = Type
2330 lib.clang_getArgType.errcheck = Type.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002331
Gregory Szorc9537e202012-07-12 04:56:46 +00002332 lib.clang_getArrayElementType.argtypes = [Type]
2333 lib.clang_getArrayElementType.restype = Type
2334 lib.clang_getArrayElementType.errcheck = Type.from_result
Gregory Szorc2c408352012-05-14 03:56:33 +00002335
Gregory Szorc9537e202012-07-12 04:56:46 +00002336 lib.clang_getArraySize.argtypes = [Type]
2337 lib.clang_getArraySize.restype = c_longlong
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002338
Gregory Szorc9537e202012-07-12 04:56:46 +00002339 lib.clang_getCanonicalCursor.argtypes = [Cursor]
2340 lib.clang_getCanonicalCursor.restype = Cursor
2341 lib.clang_getCanonicalCursor.errcheck = Cursor.from_cursor_result
2342
2343 lib.clang_getCanonicalType.argtypes = [Type]
2344 lib.clang_getCanonicalType.restype = Type
2345 lib.clang_getCanonicalType.errcheck = Type.from_result
2346
2347 lib.clang_getCompletionAvailability.argtypes = [c_void_p]
2348 lib.clang_getCompletionAvailability.restype = c_int
2349
2350 lib.clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int]
2351 lib.clang_getCompletionChunkCompletionString.restype = c_object_p
2352
2353 lib.clang_getCompletionChunkKind.argtypes = [c_void_p, c_int]
2354 lib.clang_getCompletionChunkKind.restype = c_int
2355
2356 lib.clang_getCompletionChunkText.argtypes = [c_void_p, c_int]
2357 lib.clang_getCompletionChunkText.restype = _CXString
2358
2359 lib.clang_getCompletionPriority.argtypes = [c_void_p]
2360 lib.clang_getCompletionPriority.restype = c_int
2361
2362 lib.clang_getCString.argtypes = [_CXString]
2363 lib.clang_getCString.restype = c_char_p
2364
2365 lib.clang_getCursor.argtypes = [TranslationUnit, SourceLocation]
2366 lib.clang_getCursor.restype = Cursor
2367
2368 lib.clang_getCursorDefinition.argtypes = [Cursor]
2369 lib.clang_getCursorDefinition.restype = Cursor
2370 lib.clang_getCursorDefinition.errcheck = Cursor.from_result
2371
2372 lib.clang_getCursorDisplayName.argtypes = [Cursor]
2373 lib.clang_getCursorDisplayName.restype = _CXString
2374 lib.clang_getCursorDisplayName.errcheck = _CXString.from_result
2375
2376 lib.clang_getCursorExtent.argtypes = [Cursor]
2377 lib.clang_getCursorExtent.restype = SourceRange
2378
2379 lib.clang_getCursorLexicalParent.argtypes = [Cursor]
2380 lib.clang_getCursorLexicalParent.restype = Cursor
2381 lib.clang_getCursorLexicalParent.errcheck = Cursor.from_cursor_result
2382
2383 lib.clang_getCursorLocation.argtypes = [Cursor]
2384 lib.clang_getCursorLocation.restype = SourceLocation
2385
2386 lib.clang_getCursorReferenced.argtypes = [Cursor]
2387 lib.clang_getCursorReferenced.restype = Cursor
2388 lib.clang_getCursorReferenced.errcheck = Cursor.from_result
2389
2390 lib.clang_getCursorReferenceNameRange.argtypes = [Cursor, c_uint, c_uint]
2391 lib.clang_getCursorReferenceNameRange.restype = SourceRange
2392
2393 lib.clang_getCursorSemanticParent.argtypes = [Cursor]
2394 lib.clang_getCursorSemanticParent.restype = Cursor
2395 lib.clang_getCursorSemanticParent.errcheck = Cursor.from_cursor_result
2396
2397 lib.clang_getCursorSpelling.argtypes = [Cursor]
2398 lib.clang_getCursorSpelling.restype = _CXString
2399 lib.clang_getCursorSpelling.errcheck = _CXString.from_result
2400
2401 lib.clang_getCursorType.argtypes = [Cursor]
2402 lib.clang_getCursorType.restype = Type
2403 lib.clang_getCursorType.errcheck = Type.from_result
2404
2405 lib.clang_getCursorUSR.argtypes = [Cursor]
2406 lib.clang_getCursorUSR.restype = _CXString
2407 lib.clang_getCursorUSR.errcheck = _CXString.from_result
2408
2409 #lib.clang_getCXTUResourceUsage.argtypes = [TranslationUnit]
2410 #lib.clang_getCXTUResourceUsage.restype = CXTUResourceUsage
2411
2412 lib.clang_getCXXAccessSpecifier.argtypes = [Cursor]
2413 lib.clang_getCXXAccessSpecifier.restype = c_uint
2414
2415 lib.clang_getDeclObjCTypeEncoding.argtypes = [Cursor]
2416 lib.clang_getDeclObjCTypeEncoding.restype = _CXString
2417 lib.clang_getDeclObjCTypeEncoding.errcheck = _CXString.from_result
2418
2419 lib.clang_getDiagnostic.argtypes = [c_object_p, c_uint]
2420 lib.clang_getDiagnostic.restype = c_object_p
2421
2422 lib.clang_getDiagnosticCategory.argtypes = [Diagnostic]
2423 lib.clang_getDiagnosticCategory.restype = c_uint
2424
2425 lib.clang_getDiagnosticCategoryName.argtypes = [c_uint]
2426 lib.clang_getDiagnosticCategoryName.restype = _CXString
2427 lib.clang_getDiagnosticCategoryName.errcheck = _CXString.from_result
2428
2429 lib.clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint,
2430 POINTER(SourceRange)]
2431 lib.clang_getDiagnosticFixIt.restype = _CXString
2432 lib.clang_getDiagnosticFixIt.errcheck = _CXString.from_result
2433
2434 lib.clang_getDiagnosticLocation.argtypes = [Diagnostic]
2435 lib.clang_getDiagnosticLocation.restype = SourceLocation
2436
2437 lib.clang_getDiagnosticNumFixIts.argtypes = [Diagnostic]
2438 lib.clang_getDiagnosticNumFixIts.restype = c_uint
2439
2440 lib.clang_getDiagnosticNumRanges.argtypes = [Diagnostic]
2441 lib.clang_getDiagnosticNumRanges.restype = c_uint
2442
2443 lib.clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)]
2444 lib.clang_getDiagnosticOption.restype = _CXString
2445 lib.clang_getDiagnosticOption.errcheck = _CXString.from_result
2446
2447 lib.clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint]
2448 lib.clang_getDiagnosticRange.restype = SourceRange
2449
2450 lib.clang_getDiagnosticSeverity.argtypes = [Diagnostic]
2451 lib.clang_getDiagnosticSeverity.restype = c_int
2452
2453 lib.clang_getDiagnosticSpelling.argtypes = [Diagnostic]
2454 lib.clang_getDiagnosticSpelling.restype = _CXString
2455 lib.clang_getDiagnosticSpelling.errcheck = _CXString.from_result
2456
2457 lib.clang_getElementType.argtypes = [Type]
2458 lib.clang_getElementType.restype = Type
2459 lib.clang_getElementType.errcheck = Type.from_result
2460
2461 lib.clang_getEnumConstantDeclUnsignedValue.argtypes = [Cursor]
2462 lib.clang_getEnumConstantDeclUnsignedValue.restype = c_ulonglong
2463
2464 lib.clang_getEnumConstantDeclValue.argtypes = [Cursor]
2465 lib.clang_getEnumConstantDeclValue.restype = c_longlong
2466
2467 lib.clang_getEnumDeclIntegerType.argtypes = [Cursor]
2468 lib.clang_getEnumDeclIntegerType.restype = Type
2469 lib.clang_getEnumDeclIntegerType.errcheck = Type.from_result
Tobias Grosser28d939f2012-02-05 11:42:20 +00002470
Gregory Szorc9537e202012-07-12 04:56:46 +00002471 lib.clang_getFile.argtypes = [TranslationUnit, c_char_p]
2472 lib.clang_getFile.restype = c_object_p
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00002473
Gregory Szorc9537e202012-07-12 04:56:46 +00002474 lib.clang_getFileName.argtypes = [File]
2475 lib.clang_getFileName.restype = _CXString
2476 # TODO go through _CXString.from_result?
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00002477
Gregory Szorc9537e202012-07-12 04:56:46 +00002478 lib.clang_getFileTime.argtypes = [File]
2479 lib.clang_getFileTime.restype = c_uint
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00002480
Gregory Szorc9537e202012-07-12 04:56:46 +00002481 lib.clang_getIBOutletCollectionType.argtypes = [Cursor]
2482 lib.clang_getIBOutletCollectionType.restype = Type
2483 lib.clang_getIBOutletCollectionType.errcheck = Type.from_result
Gregory Szorc5cc67872012-03-10 22:23:27 +00002484
Gregory Szorc9537e202012-07-12 04:56:46 +00002485 lib.clang_getIncludedFile.argtypes = [Cursor]
2486 lib.clang_getIncludedFile.restype = File
2487 lib.clang_getIncludedFile.errcheck = File.from_cursor_result
Manuel Klimek667fd802012-05-07 05:56:03 +00002488
Gregory Szorc9537e202012-07-12 04:56:46 +00002489 lib.clang_getInclusions.argtypes = [TranslationUnit,
2490 callbacks['translation_unit_includes'], py_object]
Manuel Klimek667fd802012-05-07 05:56:03 +00002491
Gregory Szorc9537e202012-07-12 04:56:46 +00002492 lib.clang_getInstantiationLocation.argtypes = [SourceLocation,
2493 POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)]
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00002494
Gregory Szorc9537e202012-07-12 04:56:46 +00002495 lib.clang_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint]
2496 lib.clang_getLocation.restype = SourceLocation
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002497
Gregory Szorc9537e202012-07-12 04:56:46 +00002498 lib.clang_getLocationForOffset.argtypes = [TranslationUnit, File, c_uint]
2499 lib.clang_getLocationForOffset.restype = SourceLocation
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002500
Gregory Szorc9537e202012-07-12 04:56:46 +00002501 lib.clang_getNullCursor.restype = Cursor
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002502
Gregory Szorc9537e202012-07-12 04:56:46 +00002503 lib.clang_getNumArgTypes.argtypes = [Type]
2504 lib.clang_getNumArgTypes.restype = c_uint
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002505
Gregory Szorc9537e202012-07-12 04:56:46 +00002506 lib.clang_getNumCompletionChunks.argtypes = [c_void_p]
2507 lib.clang_getNumCompletionChunks.restype = c_int
Gregory Szorc96ad6332012-02-05 19:42:06 +00002508
Gregory Szorc9537e202012-07-12 04:56:46 +00002509 lib.clang_getNumDiagnostics.argtypes = [c_object_p]
2510 lib.clang_getNumDiagnostics.restype = c_uint
Gregory Szorc31cc38c2012-02-19 18:28:33 +00002511
Gregory Szorc9537e202012-07-12 04:56:46 +00002512 lib.clang_getNumElements.argtypes = [Type]
2513 lib.clang_getNumElements.restype = c_longlong
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002514
Gregory Szorc9537e202012-07-12 04:56:46 +00002515 lib.clang_getNumOverloadedDecls.argtypes = [Cursor]
2516 lib.clang_getNumOverloadedDecls.restyp = c_uint
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002517
Gregory Szorc9537e202012-07-12 04:56:46 +00002518 lib.clang_getOverloadedDecl.argtypes = [Cursor, c_uint]
2519 lib.clang_getOverloadedDecl.restype = Cursor
2520 lib.clang_getOverloadedDecl.errcheck = Cursor.from_cursor_result
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002521
Gregory Szorc9537e202012-07-12 04:56:46 +00002522 lib.clang_getPointeeType.argtypes = [Type]
2523 lib.clang_getPointeeType.restype = Type
2524 lib.clang_getPointeeType.errcheck = Type.from_result
Gregory Szorc826fce52012-02-20 17:45:30 +00002525
Gregory Szorc9537e202012-07-12 04:56:46 +00002526 lib.clang_getRange.argtypes = [SourceLocation, SourceLocation]
2527 lib.clang_getRange.restype = SourceRange
Gregory Szorc826fce52012-02-20 17:45:30 +00002528
Gregory Szorc9537e202012-07-12 04:56:46 +00002529 lib.clang_getRangeEnd.argtypes = [SourceRange]
2530 lib.clang_getRangeEnd.restype = SourceLocation
Gregory Szorc86057602012-02-17 07:44:46 +00002531
Gregory Szorc9537e202012-07-12 04:56:46 +00002532 lib.clang_getRangeStart.argtypes = [SourceRange]
2533 lib.clang_getRangeStart.restype = SourceLocation
Gregory Szorcbf8ca002012-02-17 07:47:38 +00002534
Gregory Szorc9537e202012-07-12 04:56:46 +00002535 lib.clang_getResultType.argtypes = [Type]
2536 lib.clang_getResultType.restype = Type
2537 lib.clang_getResultType.errcheck = Type.from_result
Douglas Gregor13102ff2011-10-19 05:51:43 +00002538
Gregory Szorc9537e202012-07-12 04:56:46 +00002539 lib.clang_getSpecializedCursorTemplate.argtypes = [Cursor]
2540 lib.clang_getSpecializedCursorTemplate.restype = Cursor
2541 lib.clang_getSpecializedCursorTemplate.errcheck = Cursor.from_cursor_result
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002542
Gregory Szorc9537e202012-07-12 04:56:46 +00002543 lib.clang_getTemplateCursorKind.argtypes = [Cursor]
2544 lib.clang_getTemplateCursorKind.restype = c_uint
Gregory Szorc7eb691a2012-02-20 17:44:49 +00002545
Gregory Szorc9537e202012-07-12 04:56:46 +00002546 #lib.clang_getTokenExtent.argtypes = [TranslationUnit, Token]
2547 #lib.clang_getTokenExtent.restype = SourceRange
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002548
Gregory Szorc9537e202012-07-12 04:56:46 +00002549 #lib.clang_getTokenKind.argtypes = [Token]
2550 #lib.clang_getTokenKind.restype = c_uint
2551 #lib.clang_getTokenKind.errcheck = TokenKind.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002552
Gregory Szorc9537e202012-07-12 04:56:46 +00002553 #lib.clang_getTokenLocation.argtype = [TranslationUnit, Token]
2554 #lib.clang_getTokenLocation.restype = SourceLocation
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002555
Gregory Szorc9537e202012-07-12 04:56:46 +00002556 #lib.clang_getTokenSpelling.argtype = [TranslationUnit, Token]
2557 #lib.clang_getTokenSpelling.restype = _CXString
2558 #lib.clang_getTokenSpelling.errcheck = _CXString.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002559
Gregory Szorc9537e202012-07-12 04:56:46 +00002560 lib.clang_getTranslationUnitCursor.argtypes = [TranslationUnit]
2561 lib.clang_getTranslationUnitCursor.restype = Cursor
2562 lib.clang_getTranslationUnitCursor.errcheck = Cursor.from_result
Tobias Grosser265e6b22011-02-05 17:54:00 +00002563
Gregory Szorc9537e202012-07-12 04:56:46 +00002564 lib.clang_getTranslationUnitSpelling.argtypes = [TranslationUnit]
2565 lib.clang_getTranslationUnitSpelling.restype = _CXString
2566 lib.clang_getTranslationUnitSpelling.errcheck = _CXString.from_result
Tobias Grosser0a166802011-02-05 17:54:04 +00002567
Gregory Szorc9537e202012-07-12 04:56:46 +00002568 lib.clang_getTUResourceUsageName.argtypes = [c_uint]
2569 lib.clang_getTUResourceUsageName.restype = c_char_p
Daniel Dunbar1b945a72010-01-24 04:09:43 +00002570
Gregory Szorc9537e202012-07-12 04:56:46 +00002571 lib.clang_getTypeDeclaration.argtypes = [Type]
2572 lib.clang_getTypeDeclaration.restype = Cursor
2573 lib.clang_getTypeDeclaration.errcheck = Cursor.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002574
Gregory Szorc9537e202012-07-12 04:56:46 +00002575 lib.clang_getTypedefDeclUnderlyingType.argtypes = [Cursor]
2576 lib.clang_getTypedefDeclUnderlyingType.restype = Type
2577 lib.clang_getTypedefDeclUnderlyingType.errcheck = Type.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002578
Gregory Szorc9537e202012-07-12 04:56:46 +00002579 lib.clang_getTypeKindSpelling.argtypes = [c_uint]
2580 lib.clang_getTypeKindSpelling.restype = _CXString
2581 lib.clang_getTypeKindSpelling.errcheck = _CXString.from_result
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002582
Gregory Szorc9537e202012-07-12 04:56:46 +00002583 lib.clang_hashCursor.argtypes = [Cursor]
2584 lib.clang_hashCursor.restype = c_uint
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002585
Gregory Szorc9537e202012-07-12 04:56:46 +00002586 lib.clang_isAttribute.argtypes = [CursorKind]
2587 lib.clang_isAttribute.restype = bool
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002588
Gregory Szorc9537e202012-07-12 04:56:46 +00002589 lib.clang_isConstQualifiedType.argtypes = [Type]
2590 lib.clang_isConstQualifiedType.restype = bool
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002591
Gregory Szorc9537e202012-07-12 04:56:46 +00002592 lib.clang_isCursorDefinition.argtypes = [Cursor]
2593 lib.clang_isCursorDefinition.restype = bool
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002594
Gregory Szorc9537e202012-07-12 04:56:46 +00002595 lib.clang_isDeclaration.argtypes = [CursorKind]
2596 lib.clang_isDeclaration.restype = bool
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002597
Gregory Szorc9537e202012-07-12 04:56:46 +00002598 lib.clang_isExpression.argtypes = [CursorKind]
2599 lib.clang_isExpression.restype = bool
Tobias Grosser0a166802011-02-05 17:54:04 +00002600
Gregory Szorc9537e202012-07-12 04:56:46 +00002601 lib.clang_isFileMultipleIncludeGuarded.argtypes = [TranslationUnit, File]
2602 lib.clang_isFileMultipleIncludeGuarded.restype = bool
Tobias Grosser0a166802011-02-05 17:54:04 +00002603
Gregory Szorc9537e202012-07-12 04:56:46 +00002604 lib.clang_isFunctionTypeVariadic.argtypes = [Type]
2605 lib.clang_isFunctionTypeVariadic.restype = bool
Tobias Grosser0a166802011-02-05 17:54:04 +00002606
Gregory Szorc9537e202012-07-12 04:56:46 +00002607 lib.clang_isInvalid.argtypes = [CursorKind]
2608 lib.clang_isInvalid.restype = bool
Tobias Grosser0a166802011-02-05 17:54:04 +00002609
Gregory Szorc9537e202012-07-12 04:56:46 +00002610 lib.clang_isPODType.argtypes = [Type]
2611 lib.clang_isPODType.restype = bool
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002612
Gregory Szorc9537e202012-07-12 04:56:46 +00002613 lib.clang_isPreprocessing.argtypes = [CursorKind]
2614 lib.clang_isPreprocessing.restype = bool
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002615
Gregory Szorc9537e202012-07-12 04:56:46 +00002616 lib.clang_isReference.argtypes = [CursorKind]
2617 lib.clang_isReference.restype = bool
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002618
Gregory Szorc9537e202012-07-12 04:56:46 +00002619 lib.clang_isRestrictQualifiedType.argtypes = [Type]
2620 lib.clang_isRestrictQualifiedType.restype = bool
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002621
Gregory Szorc9537e202012-07-12 04:56:46 +00002622 lib.clang_isStatement.argtypes = [CursorKind]
2623 lib.clang_isStatement.restype = bool
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002624
Gregory Szorc9537e202012-07-12 04:56:46 +00002625 lib.clang_isTranslationUnit.argtypes = [CursorKind]
2626 lib.clang_isTranslationUnit.restype = bool
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002627
Gregory Szorc9537e202012-07-12 04:56:46 +00002628 lib.clang_isUnexposed.argtypes = [CursorKind]
2629 lib.clang_isUnexposed.restype = bool
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002630
Gregory Szorc9537e202012-07-12 04:56:46 +00002631 lib.clang_isVirtualBase.argtypes = [Cursor]
2632 lib.clang_isVirtualBase.restype = bool
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002633
Gregory Szorc9537e202012-07-12 04:56:46 +00002634 lib.clang_isVolatileQualifiedType.argtypes = [Type]
2635 lib.clang_isVolatileQualifiedType.restype = bool
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002636
Gregory Szorc9537e202012-07-12 04:56:46 +00002637 lib.clang_parseTranslationUnit.argypes = [Index, c_char_p, c_void_p, c_int,
2638 c_void_p, c_int, c_int]
2639 lib.clang_parseTranslationUnit.restype = c_object_p
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002640
Gregory Szorc9537e202012-07-12 04:56:46 +00002641 lib.clang_reparseTranslationUnit.argtypes = [TranslationUnit, c_int,
2642 c_void_p, c_int]
2643 lib.clang_reparseTranslationUnit.restype = c_int
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002644
Gregory Szorc9537e202012-07-12 04:56:46 +00002645 lib.clang_saveTranslationUnit.argtypes = [TranslationUnit, c_char_p,
2646 c_uint]
2647 lib.clang_saveTranslationUnit.restype = c_int
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002648
Gregory Szorc9537e202012-07-12 04:56:46 +00002649 #lib.clang_tokenize.argtypes = [TranslationUnit, SourceRange,
2650 # POINTER(POINTER(Token)), POINTER(c_uint)]
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002651
Gregory Szorc9537e202012-07-12 04:56:46 +00002652 lib.clang_visitChildren.argtypes = [Cursor, callbacks['cursor_visit'],
2653 py_object]
2654 lib.clang_visitChildren.restype = c_uint
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002655
Gregory Szorc9537e202012-07-12 04:56:46 +00002656register_functions(lib)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002657
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002658__all__ = [
2659 'CodeCompletionResults',
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002660 'CompilationDatabase',
2661 'CompileCommands',
2662 'CompileCommand',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002663 'CursorKind',
2664 'Cursor',
2665 'Diagnostic',
2666 'File',
2667 'FixIt',
2668 'Index',
2669 'SourceLocation',
2670 'SourceRange',
2671 'TranslationUnitLoadError',
2672 'TranslationUnit',
2673 'TypeKind',
2674 'Type',
2675]